//################################################### 
//9/28/2010  Modified by JGL to include copyright notice and to reflect CDISC HL7 project
//10/25/2010  Modofied by JGL to include SiteID in Subject Identifier

//################################################################ 
//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;
var subjectsInstance = null;
var selectedInstance = null;
var sdInstance = null;
 var studyParticipationProcessor = new XSLTProcessor()
 
function initialize() {

    model = document.getElementById("model_Document");
    scratchInstance = model.getInstanceDocument("instance_scratch");
    templateInstance = model.getInstanceDocument("instance_template");
    buildInstance = model.getInstanceDocument("instance_build");
    subjectsInstance = model.getInstanceDocument("subject_scratch");
	sdInstance = model.getInstanceDocument("instance_sd");
	preview1572Instance = model.getInstanceDocument("1572_instance");

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

    var scr = document.getElementById("javaScripts");
    scr.addEventListener("setSaveInstance", setSaveInstance, true);
        scr.addEventListener("setExistingInstance", setExistingInstance, true);
           scr.addEventListener("setExistingInstanceFileName", setExistingInstanceFileName, true);
    scr.addEventListener("setLoadInstance", setLoadInstance, true);
    scr.addEventListener("setInstanceModel", setInstanceModel, true);
      scr.addEventListener("studyIdentifierExist", studyIdentifierExist, true); 
	  scr.addEventListener("setInstanceModelSD", setInstanceModelSD, true);
  	  scr.addEventListener("importStudyData", importStudyData, true);
  	    
   scr.addEventListener("SaveSuccess", SaveSuccess, true);
   scr.addEventListener("SaveFail", SaveFail, true);
   scr.addEventListener("OpenSuccess", OpenSuccess, true);
   scr.addEventListener("OpenFail", OpenFail, true);
 scr.addEventListener("removeEffectiveTimeNullFlavor", removeEffectiveTimeNullFlavor, true);


    scr.addEventListener("subjectAccrualInsert", subjectAccrualInsert, true);
    scr.addEventListener("subjectAccrualDelete", subjectAccrualDelete, true);

    scr.addEventListener("dataCollectionInsert",  dataCollectionInsert, true);
   scr.addEventListener("dataCollectionDelete",  dataCollectionDelete, true);

   
    scr.addEventListener("studyPrimaryCount", studyPrimaryCount, true);
    scr.addEventListener("primaryPerformerInsert", primaryPerformerInsert, true);
    scr.addEventListener("addNewPrimaryPerformerSO", addNewPrimaryPerformerSO, true);  
    scr.addEventListener("deletePrimaryPerformerSO", deletePrimaryPerformerSO, true);  
    scr.addEventListener("deleteInvestigatorDoc", deleteInvestigatorDoc, true);  
         scr.addEventListener("sponsorDetails", sponsorDetails, true);
    scr.addEventListener("removeNewPrimaryPerformerSite", removeNewPrimaryPerformerSite, true);  
    
    scr.addEventListener("addNewPrimaryPerformerLicense", addNewPrimaryPerformerLicense, true);
    scr.addEventListener("deletePrimaryPerformerLicense", deletePrimaryPerformerLicense, true);
    
    scr.addEventListener("secondaryPerformerInsert", secondaryPerformerInsert, true);
     scr.addEventListener("secondaryPerformerRoleInsert", secondaryPerformerRoleInsert, true);     
     scr.addEventListener("secondaryPerformerRoleDelete", secondaryPerformerRoleDelete, true);
	scr.addEventListener("removeSecondaryPerformer", removeSecondaryPerformer, true);      
 	scr.addEventListener("serviceProviderDetails", serviceProviderDetails, true);         

    
    scr.addEventListener("studyActivitiesSiteInsert", studyActivitiesSiteInsert, true);
    
     scr.addEventListener("addNewSubjectPerson", addNewSubjectPerson, true);
    
scr.addEventListener("SubjectFocusInAlert", SubjectFocusInAlert, true);
scr.addEventListener("checkSiteIDForSpaces", checkSiteIDForSpaces, true);
	scr.addEventListener("addNewSiteLocation", addNewSiteLocation, true);
	scr.addEventListener("deleteSiteLocation", deleteSiteLocation, true);
	
     scr.addEventListener("addNewPlaceInSite", addNewPlaceInSite, true);
     scr.addEventListener("deletePlaceInSite", deletePlaceInSite, true);
     scr.addEventListener("deletePrimaryPerformerSite", deletePrimaryPerformerSite, true);
     scr.addEventListener("deletePrimaryPerformerSUBSite", deletePrimaryPerformerSUBSite, true);
     
     
     scr.addEventListener("addNewDataCollectionSite", addNewDataCollectionSite, true);
     scr.addEventListener("dataCollectionDeleteSite", dataCollectionDeleteSite, true);
     scr.addEventListener("addSubjectAccrualSite", addSubjectAccrualSite, true);
     scr.addEventListener("subjectAccrualDeleteSite", subjectAccrualDeleteSite, true);
    scr.addEventListener("investigatorScratch", investigatorScratch, true);
     scr.addEventListener("investigatorSelect", investigatorSelect, true);
     scr.addEventListener("investigatorDeselect", investigatorDeselect, true);
       scr.addEventListener("removeSite", removeSite, true);

     
      scr.addEventListener("doesSiteExist", doesSiteExist, true);   
      
      
     scr.addEventListener("addNewSubjectNonPerson", addNewSubjectNonPerson, true);     
	 scr.addEventListener("generateNonPersonSubjects", generateNonPersonSubjects, true);          
	 scr.addEventListener("generateNonPersonSubjects2", generateNonPersonSubjects2, true);   
	      scr.addEventListener("generatePersonSubjects", generatePersonSubjects, true);     
	 	      scr.addEventListener("generatePersonSubjectsImport", generatePersonSubjectsImport, true);   
	      
     	 scr.addEventListener("deleteAllSubjectsSite", deleteAllSubjectsSite, true);        
     	 scr.addEventListener("deleteSubjectAtSite", deleteSubjectAtSite, true);        
     
     
         scr.addEventListener("addNewSubjectProduct", addNewSubjectProduct, true);      
     	 scr.addEventListener("generateProducts", generateProducts, true);      
     
     scr.addEventListener("addEUID", addEUID, true);     
     scr.addEventListener("addExistingSubjectPerson", addExistingSubjectPerson, true);
     scr.addEventListener("addNewPrimaryPerformerSite", addNewPrimaryPerformerSite, true);
    scr.addEventListener("addNewSubPerformerSite", addNewSubPerformerSite, true);  
     
          scr.addEventListener("addNewSecondaryPerformerSite", addNewSecondaryPerformerSite, true);
          scr.addEventListener("deleteSecondaryPerformerSite", deleteSecondaryPerformerSite, true);
	scr.addEventListener("addInvestigatorsSelection", addInvestigatorsSelection, true);     
	scr.addEventListener("deleteCurrent", deleteCurrent, true);          
	scr.addEventListener("addNewSubject2", addNewSubject2, true);
	scr.addEventListener("deleteSubject2", deleteSubject2, true);
	scr.addEventListener("addNewSubject2Verifier", addNewSubject2Verifier, true);
	scr.addEventListener("deleteSubject2Verifier", deleteSubject2Verifier, true);
     scr.addEventListener("organizationDetails", organizationDetails, true);
      scr.addEventListener("guid", guid, true);
     
    scr.addEventListener("addSelected", addSelected, true);
    		scr.addEventListener("setUserSelectInstance", setUserSelectInstance, true);     
  scr.addEventListener("myAlert", myAlert, true);   
  
scr.addEventListener("importSubjectPersonData", importSubjectPersonData, true);  

//scr.addEventListener("generateID", generateID, true);  
scr.addEventListener("setDeaultSaveName", setDeaultSaveName, true);  
      			    			
      			    			
		  scr.addEventListener("checkStudyType", checkStudyType, true); 	
			 scr.addEventListener("setRoot", setRoot, true); 	
			 scr.addEventListener("viewStylesheet", viewStylesheet, true); 	
				 scr.addEventListener("createStyleSheetInstance", createStyleSheetInstance, true); 			
				 scr.addEventListener("investigatorDoc", investigatorDoc, true); 			
				 scr.addEventListener("viewPrintableStylesheet", viewPrintableStylesheet, true); 	
				  
	    		};


function checkStudyType() {
//alert('Check Type of Study') 
scratchInstance.getElementsByTagName("studyParticipationMessage") [0].childNodes[0].nodeValue='No';
var studyParticipationMessage = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;
//alert('studyParticipationMessage ' + studyParticipationMessage)
if(studyParticipationMessage == true)
{
var humanElement = buildInstance.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", buildInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;	
	if ( humanElement == true)   
	{
		//alert('HUMAN STUDY');
		 scratchInstance.getElementsByTagName("TypeOfStudy") [0].childNodes[0].nodeValue='Human_Study';
		 scratchInstance.getElementsByTagName("SubjectsExist") [0].childNodes[0].nodeValue='Yes';
	}
	else
			{
			var animalElement = buildInstance.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", buildInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;	
			if ( animalElement == true)   
			{
				//alert('ANIMAL STUDY');
				 scratchInstance.getElementsByTagName("TypeOfStudy") [0].childNodes[0].nodeValue='Animal_Study';
				 		 scratchInstance.getElementsByTagName("SubjectsExist") [0].childNodes[0].nodeValue='Yes';
			}
			else
			{
			};		}; 
scratchInstance.getElementsByTagName("studyParticipationMessage") [0].childNodes[0].nodeValue='Yes';
var openStudyRoot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;
var openStudyLinkID = buildInstance.evaluate("/hl7-org_v3:study/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) ;
var openStudyLink = scratchInstance.evaluate("/data/studyLinkID", scratchInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
openStudyLink.setAttribute("extension", openStudyLinkID) ; 
removeEffectiveTimeNullFlavor() 


		
	}
	else
	{ 
	alert('Please open a valid Study Participation Message.')
	buildInstance = model.getInstanceDocument("instance_build");
	}
  };


function myAlert(){
alert('myAlert');
var newguid =  guid();
    alert(newguid);
	};

function setDeaultSaveName(){
	
	var studyID = buildInstance.evaluate("/hl7-org_v3:study[hl7-org_v3:id/@root='2.16.840.1.113883.4.548.2']/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;

	if (studyID != "")
		{	
		var saveName = 'FDA_STUDYPART_' +studyID
		scratchInstance.getElementsByTagName("defaultSaveName") [0].childNodes[0].nodeValue = saveName
		 return;
		 }

}



function dataCollectionInsert()
{
	//alert( "Value of dataCollectionIndex is " + scratchInstance.getElementsByTagName("dataCollectionIndex") [0].childNodes[0].nodeValue) ;
	var index=scratchInstance.getElementsByTagName("dataCollectionIndex") [0].childNodes[0].nodeValue;
	var allDataCollection = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component2", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var countDataCollection = allDataCollection.snapshotLength;
	//alert ("Total DataCollections are : " + countDataCollection);
	if (countDataCollection ==0)
			   {
				 addDataCollection();
			   }
	  else
			{
			   addPositionalDataCollection(index);
			}         
}


function dataCollectionDelete()
{
	var index=scratchInstance.getElementsByTagName("dataCollectionIndex") [0].childNodes[0].nodeValue-1;
	
	var allDataCollection = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component2", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var dataCollection = allDataCollection.snapshotItem(index);
	dataCollection.parentNode.removeChild(allDataCollection.snapshotItem(index));		
}








function addDataCollection() {
         var NewDataCollection = getNodesetTemplate("addDataCollection", "component2");
         var component3Count = countChildElements("component3");
		   if (component3Count !=0)
            {
                        // alert("Component3 exists");     
						var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allComponent3Nodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component3", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allComponent3Nodes.snapshotItem(0);
						parentElement.insertBefore(NewDataCollection,referenceElement);
				   }			
				   
          else 
          {
				 // alert("Append before Instantiation");     
				var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				var allInstantiationNodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:instantiation", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
				var referenceElement = allInstantiationNodes.snapshotItem(0);
				parentElement.insertBefore(NewDataCollection,referenceElement);
				}
}

function addPositionalDataCollection(index) {
	   // alert("addPositionalDataCollection");
		var NewDataCollection = getNodesetTemplate("addDataCollection", "component2");
		var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		var allDataCollectionNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component2", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var referenceElement = allDataCollectionNodes.snapshotItem(index-1);
		var elementToInsert= referenceElement.singleNodeValue;
		parentElement.insertBefore(NewDataCollection,referenceElement.nextSibling);
}

function subjectAccrualInsert()
{
	 //alert( "Value of subjectAccrualInsert is " + scratchInstance.getElementsByTagName("subjectAccrualIndex") [0].childNodes[0].nodeValue) ;
	var index=scratchInstance.getElementsByTagName("subjectAccrualIndex") [0].childNodes[0].nodeValue;
	var allSubjectAccrual = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component3", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var countSubjectAccrual = allSubjectAccrual.snapshotLength;
	//alert ("Total SubjectAccrual are : " + countSubjectAccrual);
	if (countSubjectAccrual ==0)
			   {
				 addSubjectAccrual();
			   }
	  else
			{
			   addPositionalSubjectAccrual(index);
			}         
}

function subjectAccrualDelete()
{
	var index=scratchInstance.getElementsByTagName("subjectAccrualIndex") [0].childNodes[0].nodeValue-1;
	
	var allSubjectAccruals = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component3", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var subjectAccrual = allSubjectAccruals.snapshotItem(index);
	subjectAccrual.parentNode.removeChild(allSubjectAccruals.snapshotItem(index));		

}


function addSubjectAccrual() {
          var NewSubjectAccrual = getNodesetTemplate("addSubjectAccrual", "component3");
		 // alert("Append before Instantiation");     
		var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		var allInstantiationNodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:instantiation", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var referenceElement = allInstantiationNodes.snapshotItem(0);
		parentElement.insertBefore(NewSubjectAccrual,referenceElement);
}



function addPositionalSubjectAccrual(index) {
		var NewSubjectAccrual = getNodesetTemplate("addSubjectAccrual", "component3");
		var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		var allSubjectAccrualNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component3", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var referenceElement = allSubjectAccrualNodes.snapshotItem(index-1);
		var elementToInsert= referenceElement.singleNodeValue;
		parentElement.insertBefore(NewSubjectAccrual,referenceElement.nextSibling);
}


function primaryPerformerInsert() 
{
	 // alert( "Value of primaryPerformerInsert is " + scratchInstance.getElementsByTagName("PrimaryPerformerIndex") [0].childNodes[0].nodeValue) ;
	var index=scratchInstance.getElementsByTagName("PrimaryPerformerIndex") [0].childNodes[0].nodeValue;
	var allPrimaryPerformer = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var countPrimaryPerformer = allPrimaryPerformer.snapshotLength;
	// alert ("Total PrimaryPerformer are : " + countPrimaryPerformer);
	if (countPrimaryPerformer ==0)
			   {
				 addPrimaryPerformer();
			   }
	  else
			{
			   addPositionalPrimaryPerformer(index);
			}         
}

function addPrimaryPerformer() 
{
         var NewPrimaryPerformer = getNodesetTemplate("addPrimaryPerformer", "primaryPerformer");
         var secondaryPerformerCount =  countChildElements("secondaryPerformer");
         var component1Count = countChildElements("component1");
         var component2Count = countChildElements("component2");
         var component3Count = countChildElements("component3");
           if (secondaryPerformerCount != 0)  /// The first PrimaryPerformer must always be added before any providers
				   {
				       // alert("providers exist so adding before providers");
						var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allSecondaryPerformerNodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allSecondaryPerformerNodes.snapshotItem(0);
						parentElement.insertBefore(NewPrimaryPerformer,referenceElement);
				   }

          else if (component1Count !=0)
            {
                        // alert("No providers Exist but component1 exist");     
						var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allComponent1Nodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allComponent1Nodes.snapshotItem(0);
						parentElement.insertBefore(NewPrimaryPerformer,referenceElement);
				   }
		   
		   else if (component2Count !=0)
            {
                        // alert("No component1 Exist but component2 exist");     
						var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allComponent2Nodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component2", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allComponent2Nodes.snapshotItem(0);
						parentElement.insertBefore(NewPrimaryPerformer,referenceElement);
				   }
				   
		   else if (component3Count !=0)
            {
                        // alert("No component2 Exist but component3 exist");     
						var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allComponent3Nodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component3", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allComponent3Nodes.snapshotItem(0);
						parentElement.insertBefore(NewPrimaryPerformer,referenceElement);
				   }			
				   
          else 
          {
				// alert("Append before Instantiation");     
				var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				var allInstantiationNodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:instantiation", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
				var referenceElement = allInstantiationNodes.snapshotItem(0);
				parentElement.insertBefore(NewPrimaryPerformer,referenceElement);
				}
};


function addPositionalPrimaryPerformer(index) 
	{
			 var NewPrimaryPerformer = getNodesetTemplate("addPrimaryPerformer", "primaryPerformer");
			var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
			var allPrimaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allPrimaryPerformerNodes.snapshotItem(index-1);
			var elementToInsert= referenceElement.singleNodeValue;
			parentElement.insertBefore(NewPrimaryPerformer,referenceElement.nextSibling);
	};
 
 

 
function addNewPrimaryPerformerSO() {
    var soIndex = scratchInstance.getElementsByTagName("PrimaryPerformerSOIndex") [0].textContent - 0;
		 // alert('PrimaryPerformerSOIndex    '  +  soIndex)
      var index = scratchInstance.getElementsByTagName("PrimaryPerformerIndex") [0].textContent - 1;
			// alert('PrimaryPerformerIndex    '  +  index)
    var NewSponsor = getNodesetTemplate("addSponsoringOrganization", "sponsoringOrganization");
    
     var subjectOfCount = countInvestigatorChildElements("subjectOf", index);

     if (subjectOfCount > 0)
    {
    		var primaryPerformerSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer/hl7-org_v3:investigator", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
		  var primaryPerformer = primaryPerformerSnapshot.snapshotItem(index);
		   // alert('primaryPerformer   '  +  primaryPerformer);
		  
		  
		var referenceElement = buildInstance.evaluate("hl7-org_v3:subjectOf", primaryPerformer, nsResolver,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
		  // alert('parentNode   '  +  parentNode);
primaryPerformer.insertBefore(NewSponsor,referenceElement);	
			
    
    }
    else
		{
		var primaryPerformerSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
		  var primaryPerformer = primaryPerformerSnapshot.snapshotItem(index);
		   // alert('primaryPerformer   '  +  primaryPerformer);
		  
		  
		var parentNode = buildInstance.evaluate("hl7-org_v3:investigator", primaryPerformer, nsResolver,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
		  // alert('parentNode   '  +  parentNode);
		  
		  var sponsoringOrganizations = buildInstance.evaluate("hl7-org_v3:sponsoringOrganization", parentNode, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var countOfsponsoringOrganizations = sponsoringOrganizations.snapshotLength;
		
		 if (countOfsponsoringOrganizations < 1)
		 {
		   parentNode.appendChild(NewSponsor);
		}
		else
		{
			alert('An Investigator may only have one Sponsoring Organization.')
		}
	}
};

 
function deletePrimaryPerformerSO() {
      var index = scratchInstance.getElementsByTagName("PrimaryPerformerIndex") [0].textContent - 1;
			// alert('PrimaryPerformerIndex    '  +  index)
    
    var primaryPerformerSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
      var primaryPerformer = primaryPerformerSnapshot.snapshotItem(index);
       // alert('primaryPerformer   '  +  primaryPerformer);
      
      var sponsoringOrganization = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:sponsoringOrganization", primaryPerformer, nsResolver,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
sponsoringOrganization.parentNode.removeChild(sponsoringOrganization);
};


function deleteInvestigatorDoc() {
      var index = scratchInstance.getElementsByTagName("PrimaryPerformerIndex") [0].textContent - 1;
  
    var primaryPerformerSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
      var primaryPerformer = primaryPerformerSnapshot.snapshotItem(index);
     
      var investigatorDoc = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:subjectOf", primaryPerformer, nsResolver,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
investigatorDoc.parentNode.removeChild(investigatorDoc);
};





function sponsorDetails() 
{
	var investigatorIndex = scratchInstance.getElementsByTagName("PrimaryPerformerIndex") [0].childNodes[0].nodeValue -1 ;
// alert(  "Value of PrimaryPerformerIndex is " + investigatorIndex);
	 	var sponsorIndex = scratchInstance.getElementsByTagName("PrimaryPerformerSOIndex") [0].childNodes[0].nodeValue -1 ;
	// alert(  "Value of PrimaryPerformerSOIndex is " + sponsorIndex);
	 var sponsorID = scratchInstance.getElementsByTagName("sponsorID") [0].childNodes[0].nodeValue ;
		// alert(  "Value of sponsorID is " + sponsorID);
	  
	  	var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var parentElementNode = parElement.snapshotItem(investigatorIndex);
		
		var sponsorElement = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:sponsoringOrganization", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var sponsorElementNode = sponsorElement.snapshotItem(sponsorIndex);
		
		var sponsorElement2 = buildInstance.evaluate("hl7-org_v3:investigator", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var sponsorElementNode2 = sponsorElement2.snapshotItem(sponsorIndex);		
		
		var referenceElement = buildInstance.evaluate("hl7-org_v3:sponsoringOrganization", sponsorElementNode2, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var referenceElementNode = referenceElement.snapshotItem(0);
		// 	 alert(  "Value of referenceElementNode is " + referenceElementNode);
	
		 var allSponsors = buildInstance.evaluate("//hl7-org_v3:investigator/hl7-org_v3:sponsoringOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		 
		 var foundMatch = 'No'
		 var matchIndex = ''
		for ( var j=0 ; j < allSponsors.snapshotLength; j++ )   
		{   
			var sponsors = allSponsors.snapshotItem(j)
			
				var sponsor = buildInstance.evaluate("hl7-org_v3:id", sponsors, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
			// 	alert(sponsor + '== ' +sponsorID)
			if (sponsor == sponsorID)
				{
			// 	alert('Found match')
					matchIndex = j;
					if(matchIndex == investigatorIndex)
						{
					//	alert('Found match but it is the current one  keep looking.')
						}
					else
						{
						foundMatch = 'Yes'
						}
				}
					if(foundMatch == 'Yes')
						{
							//alert('Set Org Details to index  '  + matchIndex )
								var sponsors = allSponsors.snapshotItem(matchIndex)
								
								 var sponsor = buildInstance.evaluate(".", sponsors, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
					// 		 alert('sponsor' + sponsor)
									var selectedSponsor = sponsor.singleNodeValue.cloneNode(true);
					// 		alert('selectedSponsor' + selectedSponsor)
														
								sponsorElementNode2.insertBefore(selectedSponsor,sponsorElementNode);	
								
							var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
							var parentElementNode = parElement.snapshotItem(investigatorIndex);
						// 				alert('parentElementNode' + parentElementNode)
							
							var sponsorElement = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:sponsoringOrganization", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
							var sponsorElementNode = sponsorElement.snapshotItem(sponsorIndex);
								// 		alert('sponsorElementNode' + sponsorElementNode)
								
							// 	alert('REMOVE Original Nodes')
								sponsorElementNode.parentNode.removeChild(sponsorElement.snapshotItem(1));		
								break;
						}
		} // End For Loop
};





function serviceProviderDetails() 
{
	var providerIndex = scratchInstance.getElementsByTagName("SecondaryPerformerIndex") [0].childNodes[0].nodeValue -1 ;
	//alert(  "Value of providerIndex is " + providerIndex);

	 var providerID = scratchInstance.getElementsByTagName("providerID") [0].childNodes[0].nodeValue ;
		//alert(  "Value of providerID is " + providerID);
	  
	  	var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var parentElementNode = parElement.snapshotItem(providerIndex);
		//alert(  "Value of parentElementNode is " + parentElementNode);
		
		var providerElement = buildInstance.evaluate("hl7-org_v3:serviceProvider", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var providerElementNode = providerElement.snapshotItem(0);	
		//alert(  "Value of providerElementNode is " + providerElementNode);
				
		var referenceElement = buildInstance.evaluate("hl7-org_v3:playingOrganization", providerElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var referenceElementNode = referenceElement.snapshotItem(0);
			 //alert(  "Value of referenceElementNode is " + referenceElementNode);
	
		 var allProviders = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer/hl7-org_v3:serviceProvider", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		 
		 var foundMatch = 'No'
		 var matchIndex = ''
		for ( var j=0 ; j < allProviders.snapshotLength; j++ )   
		{   
			var providers = allProviders.snapshotItem(j)
			
				var provider = buildInstance.evaluate("hl7-org_v3:playingOrganization/hl7-org_v3:id", providers, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
					//alert(provider + '== ' +providerID)
			if (provider == providerID)
				{
					//alert('Found match')
					matchIndex = j;
					if(matchIndex == providerIndex)
						{
						//alert('Found match but it is the current one  keep looking.')
						}
					else
						{
						foundMatch = 'Yes'
						}
				}
					if(foundMatch == 'Yes')
						{
							//alert('Set Provider Details to index  '  + matchIndex )
								var providers = allProviders.snapshotItem(matchIndex)
								
								 var provider = buildInstance.evaluate("hl7-org_v3:playingOrganization", providers, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
								//alert('provider' + provider)
								
								var selectedProvider = provider.singleNodeValue.cloneNode(true);
								//alert('selectedProvider' + selectedProvider)
														
								providerElementNode.insertBefore(selectedProvider,referenceElementNode);	
								
							var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
							var parentElementNode = parElement.snapshotItem(providerIndex);
										//alert('parentElementNode' + parentElementNode)
							
							var providerElement = buildInstance.evaluate("hl7-org_v3:serviceProvider/hl7-org_v3:playingOrganization", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
							var providerElementNode = providerElement.snapshotItem(0);
										//alert('providerElementNode' + providerElementNode)
								
								//alert('REMOVE Original Nodes')
								providerElementNode.parentNode.removeChild(providerElement.snapshotItem(1));		
								break;
						}
		} // End For Loop
};



  
function addNewPrimaryPerformerLicense() 
{
			var newElement= getNodesetTemplate("addPrimaryPerformerLicense", "asLicensedEntity");	 
			var indextoInsert = scratchInstance.getElementsByTagName("PrimaryPerformerIndex") [0].textContent -1;		//alert(' Investigator index to Insert     ' + indextoInsert);
			var licenseIndex = scratchInstance.getElementsByTagName("PrimaryPerformerLicenseIndex") [0].textContent ;		//alert(' License Index to insert     ' + licenseIndex);		
			var parentElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer/hl7-org_v3:investigator/hl7-org_v3:investigatorPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
			var parentElementNode =	 parentElement.snapshotItem(indextoInsert);
			parentElementNode.appendChild(newElement);
}	
	
function deletePrimaryPerformerLicense() 
{ 
			var PrimaryPerformerIndex = scratchInstance.getElementsByTagName("PrimaryPerformerIndex") [0].textContent -1;		//alert(' Investigator index to Insert     ' + indextoInsert);
			var licenseIndex = scratchInstance.getElementsByTagName("PrimaryPerformerLicenseIndex") [0].textContent -1;		
			var parentElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer/hl7-org_v3:investigator/hl7-org_v3:investigatorPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
			var primaryPerformer =	 parentElement.snapshotItem(PrimaryPerformerIndex);
			var licenses = buildInstance.evaluate("hl7-org_v3:asLicensedEntity", primaryPerformer, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var thisLicense =	 licenses.snapshotItem(licenseIndex);
			thisLicense.parentNode.removeChild(thisLicense)
}	
	
	
function removeNewPrimaryPerformerSite() 
{
	var primaryAssigned = 'No'
	 var PrimaryPerformerIndex = scratchInstance.getElementsByTagName("PrimaryPerformerIndex") [0].childNodes[0].nodeValue -1;
     var thisInvestigator = scratchInstance.getElementsByTagName("RemoveInvestigator") [0].childNodes[0].nodeValue;
	var nodesSnapshot = buildInstance.evaluate("//hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:primaryPerformer/hl7-org_v3:investigator/hl7-org_v3:id/@extension", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
		var nodesSnapshot2 = buildInstance.evaluate("//hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
		for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )   
			{   
			try
			   {
			  nodesSnapshot.snapshotItem(i).childNodes[0].nodeValue
			   }
			 catch(err)
			   {
			   if ( i < nodesSnapshot.snapshotLength-1) 
				   {
					continue;
				   }
				   else
				   {
					  break;
				  }
			   }
			
			   var siteInvestigator =   nodesSnapshot.snapshotItem(i).childNodes[0].nodeValue;
					if ( siteInvestigator == thisInvestigator)   
							{
								primaryAssigned = 'Yes'
							};	
			} ;

	if (primaryAssigned == 'Yes')
		{
			if (confirm ("Deleting the Investigator from the Study will delete the Investigator from all sites, do you wish to continue? "))
				{
					 scratchInstance.getElementsByTagName("ProceedRemoveInvestigator") [0].childNodes[0].nodeValue='1';
					 var thisInvestigator = scratchInstance.getElementsByTagName("RemoveInvestigator") [0].childNodes[0].nodeValue;
					 //alert('remove this investigator' + thisInvestigator);
						for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )   
							{   
							try
								   {
								  nodesSnapshot.snapshotItem(i).childNodes[0].nodeValue
								   }
								 catch(err)
								   {
								   if ( i < nodesSnapshot.snapshotLength-1) 
									   {
										continue;
									   }
									   else
									   {
										  break;
									  }
								   }
							   var siteInvestigator =   nodesSnapshot.snapshotItem(i).childNodes[0].nodeValue;
							  // alert(siteInvestigator +' == ' + thisInvestigator)
									if ( siteInvestigator == thisInvestigator)   
											{
											// alert('removed from site');
												var removeInvestigator = nodesSnapshot2.snapshotItem(i); 
												removeInvestigator.parentNode.removeChild(nodesSnapshot2.snapshotItem(i))
											};
							};  	
					var allInvestigators = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);		
					var theInvestigator =   allInvestigators.snapshotItem(PrimaryPerformerIndex);
					theInvestigator.parentNode.removeChild(theInvestigator)
					}
				// Do not remove the investigator
				else	
				{
					return;
				};					
		}			
	// Primary Not assigned to site, remove from study
	else
		{
			var allInvestigators = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);		
			var theInvestigator =   allInvestigators.snapshotItem(PrimaryPerformerIndex);
			theInvestigator.parentNode.removeChild(theInvestigator)		}
  };
  
  function secondaryPerformerRoleInsert() 
	{
		// alert( "Value of secondaryPerformerInsert is " + scratchInstance.getElementsByTagName("SecondaryPerformerIndex") [0].childNodes[0].nodeValue) ;
		var index=scratchInstance.getElementsByTagName("SecondaryPerformerIndex") [0].childNodes[0].nodeValue;

		var allSecondaryPerformer = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var secondaryPerformer = allSecondaryPerformer.snapshotItem(index-1);

		
		var serviceProviderCodeExist = buildInstance.evaluate("hl7-org_v3:serviceProvider/hl7-org_v3:code", secondaryPerformer, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;

			if (serviceProviderCodeExist == true)	
			{
				alert('Only one role can be added.')
				return;
			}
			else
			{
				var serviceProvider = buildInstance.evaluate("hl7-org_v3:serviceProvider", secondaryPerformer, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				var referenceElement = buildInstance.evaluate("hl7-org_v3:id", serviceProvider, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				 var newRole = getNodesetTemplate("addSecondaryRolePerformer", "code");
				serviceProvider.insertBefore(newRole,referenceElement.nextSibling);
			}
	};

  
    function secondaryPerformerRoleDelete() 
	{
		// alert( "Value of secondaryPerformerInsert is " + scratchInstance.getElementsByTagName("SecondaryPerformerIndex") [0].childNodes[0].nodeValue) ;
		var index=scratchInstance.getElementsByTagName("SecondaryPerformerIndex") [0].childNodes[0].nodeValue;
		var allSecondaryPerformer = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var secondaryPerformer = allSecondaryPerformer.snapshotItem(index-1);
		
		var serviceProviderCodeExist = buildInstance.evaluate("hl7-org_v3:serviceProvider/hl7-org_v3:code", secondaryPerformer, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
		
			if (serviceProviderCodeExist == true)	
			{
				var serviceProviderCode = buildInstance.evaluate("hl7-org_v3:serviceProvider/hl7-org_v3:code", secondaryPerformer, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				serviceProviderCode.parentNode.removeChild(serviceProviderCode)
			}

	};

function secondaryPerformerInsert() 
	{
		// alert( "Value of secondaryPerformerInsert is " + scratchInstance.getElementsByTagName("SecondaryPerformerIndex") [0].childNodes[0].nodeValue) ;
		var index=scratchInstance.getElementsByTagName("SecondaryPerformerIndex") [0].childNodes[0].nodeValue;
		var allSecondaryPerformer = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var countSecondaryPerformer = allSecondaryPerformer.snapshotLength;
		// alert ("Total SecondaryPerformer are : " + countSecondaryPerformer);
		if (countSecondaryPerformer ==0)
				   {
					 addSecondaryPerformer();
				   }
		  else
				{
				   addPositionalSecondaryPerformer(index);
				}         
	};


function addSecondaryPerformer() 
{
         var NewSecondaryPerformer = getNodesetTemplate("addSecondaryPerformer", "secondaryPerformer");
         var component1Count = countChildElements("component1");
         var component2Count = countChildElements("component2");
         var component3Count = countChildElements("component3");
         
          if (component1Count !=0)
            {
                        // alert("No providers Exist but component1 exist");     
						var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allComponent1Nodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allComponent1Nodes.snapshotItem(0);
						parentElement.insertBefore(NewSecondaryPerformer,referenceElement);
				   }
		   
		   else if (component2Count !=0)
            {
                         // alert("No component1 Exist but component2 exist");     
						var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allComponent2Nodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component2", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allComponent2Nodes.snapshotItem(0);
						parentElement.insertBefore(NewSecondaryPerformer,referenceElement);
				   }
				   
		   else if (component3Count !=0)
            {
                         // alert("No component2 Exist but component3 exist");     
						var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allComponent3Nodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component3", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allComponent3Nodes.snapshotItem(0);
						parentElement.insertBefore(NewSecondaryPerformer,referenceElement);
				   }			
				   
          else 
          {
				 // alert("Append before instantiation");     
				var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				var allInstantiationNodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:instantiation", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
				var referenceElement = allInstantiationNodes.snapshotItem(0);
				parentElement.insertBefore(NewSecondaryPerformer,referenceElement);
				}
		var index=scratchInstance.getElementsByTagName("SecondaryPerformerIndex") [0].childNodes[0].nodeValue;
		var allSecondaryPerformers = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var secondaryPerformer = allSecondaryPerformers.snapshotItem(index);
		
};


function addPositionalSecondaryPerformer(index) 
{
		  var NewSecondaryPerformer = getNodesetTemplate("addSecondaryPerformer", "secondaryPerformer");
		var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var referenceElement = allSecondaryPerformerNodes.snapshotItem(index-1);
		var elementToInsert= referenceElement.singleNodeValue;
		parentElement.insertBefore(NewSecondaryPerformer,referenceElement.nextSibling);
		
		var index=scratchInstance.getElementsByTagName("SecondaryPerformerIndex") [0].childNodes[0].nodeValue;
		var allSecondaryPerformers = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var secondaryPerformer = allSecondaryPerformers.snapshotItem(index);
};
 
 
function removeSecondaryPerformer() {
		var SecondaryPerformerIndex = scratchInstance.getElementsByTagName("SecondaryPerformerIndex") [0].childNodes[0].nodeValue -1;

		var nodesSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
		 var secondaryPerformer =   nodesSnapshot.snapshotItem(SecondaryPerformerIndex)

		var orgID = buildInstance.evaluate("hl7-org_v3:serviceProvider/hl7-org_v3:playingOrganization/hl7-org_v3:id", secondaryPerformer, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
		
		if(orgID != '')
		{
		var foundOthers = 'No'
		
			for ( var j=0 ; j < nodesSnapshot.snapshotLength; j++ )   
			{   
			//alert('j is equal to     ' + j )
			var checkThisPerformer =   nodesSnapshot.snapshotItem(j);
			var checkOrgID = buildInstance.evaluate("hl7-org_v3:serviceProvider/hl7-org_v3:playingOrganization/hl7-org_v3:id", checkThisPerformer, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
			
				if( orgID  == checkOrgID && j != SecondaryPerformerIndex)
				{
				foundOthers = 'Yes'
				}
			}
			
		if(foundOthers == 'Yes')
		{
		//alert('Go ahead and delete')
		secondaryPerformer.parentNode.removeChild(secondaryPerformer)
		}	
		
		else if (confirm ("Deleting the Provider from the Study will delete the Provider from all sites, do you wish to continue? "))
			{
				 var allSiteProviders = buildInstance.evaluate("//hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:secondaryPerformer/hl7-org_v3:serviceProvider/hl7-org_v3:playingOrganization", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
				  var allSiteProviders2 = buildInstance.evaluate("//hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
									for ( var i=0 ; i < allSiteProviders.snapshotLength; i++ )   
										{   
							
										   var siteProvider =   allSiteProviders.snapshotItem(i)
										   
										  var siteProvider = buildInstance.evaluate("hl7-org_v3:id", siteProvider, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
										 // alert(siteProvider +' == ' + orgID)
												if ( siteProvider == orgID)   
														{
														// alert('removed from site');
															var removeProvider = allSiteProviders2.snapshotItem(i); 
															removeProvider.parentNode.removeChild(removeProvider)
															
														};	
										}  ;   	
		secondaryPerformer.parentNode.removeChild(secondaryPerformer)
				}	
		else
		{
		
		}
		
									
		}
		else
		{
	//	alert('Go ahead and delete')
		secondaryPerformer.parentNode.removeChild(secondaryPerformer)
		}	
				
				
  };
 
 
 

function studyActivitiesSiteInsert() 
{
	//alert( "Value of studyActivitiesSiteInsert is " + scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue) ;
	var index=scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue;
	var allComponent1 = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var countComponent1 = allComponent1.snapshotLength;
	//alert ("Total Component1 are : " + countComponent1);
	if (countComponent1 ==0)
			   {
				 addComponent1();
			   }
	  else
			{
			   addPositionalComponent1(index);
			}         
}

function addComponent1() 
{
         var NewStudyActivitiesSite = getNodesetTemplate("addComponent1", "component1");
         var component2Count = countChildElements("component2");
         var component3Count = countChildElements("component3");		   
		  if (component2Count !=0)
            {
                        // alert("No component1 Exist but component2 exist");     
						var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allComponent2Nodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component2", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allComponent2Nodes.snapshotItem(0);
						parentElement.insertBefore(NewStudyActivitiesSite,referenceElement);
				   }
				   
		   else if (component3Count !=0)
            {
                        // alert("No component2 Exist but component3 exist");     
						var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
						var allComponent3Nodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component3", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = allComponent3Nodes.snapshotItem(0);
						parentElement.insertBefore(NewStudyActivitiesSite,referenceElement);
				   }			
				   
          else 
          {
				// alert("Append before Instantiation");     
				var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				var allInstantiationNodes =buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:instantiation", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
				var referenceElement = allInstantiationNodes.snapshotItem(0);
				parentElement.insertBefore(NewStudyActivitiesSite,referenceElement);
				}
};


function addPositionalComponent1(index) 
	{
			var NewStudyActivitiesSite = getNodesetTemplate("addComponent1", "component1");
			var parentElement = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
			var allComponent1Nodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			//alert('index value   ' + index)
			var referenceElement = allComponent1Nodes.snapshotItem(index-1);
			var elementToInsert= referenceElement.singleNodeValue;
			parentElement.insertBefore(NewStudyActivitiesSite,referenceElement.nextSibling);
	};
 
 
 function checkSiteIDForSpaces()
 {
  var SiteIdentifier = scratchInstance.getElementsByTagName("SiteIdentifier") [0].textContent;
  var spaces = spaceInString(SiteIdentifier)
  if (spaces == true)
  alert('Site Identifiers should not contain spaces.  Please remove all spaces.')

 }

 function SubjectFocusInAlert()
 {
  alert('Changing the ID can mess things up… so you probably shouldnt do it...')
}


function addNewSiteLocation() {
      var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].textContent-1;
			//alert(  "Value of studyActivitiesSiteInsert is " + index);
    var NewSiteLocation = getNodesetTemplate("addSiteLocation", "location");
    var countLocation=  countSiteChildElements("location", index);
    var countSubject2 =  countSiteChildElements("subject2", index);
    var countComponent2 =  countSiteChildElements("component2", index);
     var countComponent3 =  countSiteChildElements("component3", index);
     var countSubjectOf =  countSiteChildElements("SubjectOf", index);
     
	  if (countSubject2 !=0)
			   {
			//alert('secondary exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subject2", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(NewSiteLocation,referenceElement);			
			   }
			   
			else if (countComponent2 !=0)
			   { 
			//alert('component2 exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:component2", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(NewSiteLocation,referenceElement);			
			   }	   
			   
						 else if (countComponent3 !=0)  
			 {
			//alert('compnent3 exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:component3", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(NewSiteLocation,referenceElement);			
			   }	     
			   
			   
			 else if (countSubjectOf !=0)  
			 {
			//alert('compnent3 exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subjectOf", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(NewSiteLocation,referenceElement);			
			   }	     
			   

	  else
			{
			//alert('Append')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			
			var parentElementNode = parElement.snapshotItem(index);
			//alert(parentElementNode)
			parentElementNode.appendChild(NewSiteLocation);
			} 
}


function deleteSiteLocation() {
      var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].textContent-1;
      var LocationIndex = scratchInstance.getElementsByTagName("Location") [0].textContent -1;

      	 var component1 = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
      var component1Node = component1.snapshotItem(index);

		 var locations = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location", component1Node, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
      var location = locations.snapshotItem(LocationIndex);

      		location.parentNode.removeChild(location);
      }



function addNewPlaceInSite(calledFromImport, studyCellPlaceExtID) {
    var Location = scratchInstance.getElementsByTagName("Location") [0].textContent -1;
		// alert('Location    '  +  Location)
      var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].textContent - 1;
			 //alert('index    '  +  index)
    var NewPlaceInSite = getNodesetTemplate("addPlaceInSite", "locatedEntity");
    var studyCellPlaceExtID = studyCellPlaceExtID
    
    var component1 = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
      var component1Node = component1.snapshotItem(index);
       // alert('PLACE component1   '  +  component1Node);
      
    var parentNode = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location", component1Node, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
       // alert('PLACE parentNode   '  +  parentNode);

		// alert('calledFromImport  ' + calledFromImport);
      
    var parentElementNode = parentNode.snapshotItem(Location);
       // alert('PLACE parentElementNode   '  +  parentElementNode);
           
      var locationID = buildInstance.evaluate("hl7-org_v3:id", parentElementNode, nsResolver,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
	   // alert('locationID   ' + locationID)
            if (locationID  != "")
				{
				  var locatedEntity = buildInstance.evaluate("hl7-org_v3:locatedEntity", parentElementNode, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
					var countOfPlaces = locatedEntity.snapshotLength;
					// alert('There are this many places at the location   '  + countOfPlaces)
						 if (countOfPlaces < 1)
							 {
								   parentElementNode.appendChild(NewPlaceInSite);
									   var component1 = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
								  var component1Node = component1.snapshotItem(index);
								  
									   var parentNode = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location", component1Node, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
											   // alert('PLACE parentNode   '  +  parentNode);
										var parentElementNode = parentNode.snapshotItem(Location);
										
									 var locationID = buildInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:id", parentElementNode, nsResolver,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;

										var newPlaceID = locationID + '_' + 'place'
										if (calledFromImport == 'YES')
										{
										var newPlaceID =  studyCellPlaceExtID
										}
											  
										 var resetID = buildInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity/hl7-org_v3:locatedPlace/hl7-org_v3:id", parentElementNode, nsResolver,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
											// alert('PLACE resetID   '  +  resetID);
											resetID.setAttribute("extension", newPlaceID) ;
								}	
						else if (calledFromImport != 'YES')
							{
								alert('A location may only have one place defined.')
							};
				}
			else if (calledFromImport == 'YES' && locationID  == "")
						{
										 var locatedEntity = buildInstance.evaluate("hl7-org_v3:locatedEntity", parentElementNode, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
										var countOfPlaces = locatedEntity.snapshotLength;
										//alert('ELSE IF       There are this many places at the location   '  + countOfPlaces)
										 if (countOfPlaces < 1)
											 {
												   parentElementNode.appendChild(NewPlaceInSite);
													   var component1 = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
												  var component1Node = component1.snapshotItem(index);
												  
													   var parentNode = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location", component1Node, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
															 // alert('PLACE parentNode   '  +  parentNode);
														var parentElementNode = parentNode.snapshotItem(Location);
														
														var newPlaceID =  studyCellPlaceExtID
																									 var resetID = buildInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity/hl7-org_v3:locatedPlace/hl7-org_v3:id", parentElementNode, nsResolver,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
																resetID.setAttribute("extension", newPlaceID) ;
													}
							}	
			else
					{
					alert('Please enter a Location Identifier before adding a Place.')
					}
};

function deletePlaceInSite() {
    var LocationIndex = scratchInstance.getElementsByTagName("Location") [0].textContent -1;
      var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].textContent - 1;
	 var component1 = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
      var component1Node = component1.snapshotItem(index);
		
		 var locations = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location", component1Node, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
      var location = locations.snapshotItem(LocationIndex);
      
       var locatedEntity = buildInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity", location, nsResolver,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
      		locatedEntity.parentNode.removeChild(locatedEntity);
 }
			 

function addNewDataCollectionSite() 
{

	 // alert( "Value of studyActivitiesSiteInsert is " + scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue) ;
	 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
	 //alert(  "Value of studyActivitiesSiteInsert is " + index);
         var NewDataCollection = getNodesetTemplate("addDataCollectionSite", "component1");
         var component2Count =  countSiteChildElements("component2", index);
		  if (component2Count !=0)
            {
         // alert("component2 exists");    
            var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:component2", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(NewDataCollection,referenceElement);		
			}	   
          else 
          {
		//	alert("Append");     
			 var activitiesSiteIndex = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].textContent - 1;
			 var DataPath = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var path = DataPath.snapshotItem(activitiesSiteIndex);
			path.appendChild(NewDataCollection);
				}
};

    
function dataCollectionDeleteSite()
{
	var activitiesSiteIndex=scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue-1;
	var index=scratchInstance.getElementsByTagName("dataCollectionSiteIndex") [0].childNodes[0].nodeValue-1;
	
	 var sitePath= buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var path = sitePath.snapshotItem(activitiesSiteIndex);
	
	var allDataCollections = buildInstance.evaluate("hl7-org_v3:component1", path, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var dataCollection = allDataCollections.snapshotItem(index);
	dataCollection.parentNode.removeChild(dataCollection);		

}    
    
function addSubjectAccrualSite() {
 var activitiesSiteIndex = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].textContent - 1;
  var NewSubjectAccrual = getNodesetTemplate("addSubjectAccrualSite", "component2");
     var SubjectPath = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var path = SubjectPath.snapshotItem(activitiesSiteIndex);
    path.appendChild(NewSubjectAccrual);
}    
    
    
function subjectAccrualDeleteSite()
{
	var activitiesSiteIndex=scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue-1;
	var index=scratchInstance.getElementsByTagName("subjectAccrualSiteIndex") [0].childNodes[0].nodeValue-1;
	
	 var sitePath= buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var path = sitePath.snapshotItem(activitiesSiteIndex);
	
	var allSubjectAccruals = buildInstance.evaluate("hl7-org_v3:component2", path, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var subjectAccrual = allSubjectAccruals.snapshotItem(index);
	subjectAccrual.parentNode.removeChild(allSubjectAccruals.snapshotItem(index));		

}

function addNewSubject2() 
{

	 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
	 //alert(  "Value of studyActivitiesSiteInsert is " + index);
         var NewSubject2 = getNodesetTemplate("addSubject2", "subject2");
		var countComponent1 =  countSiteChildElements("component1", index);
		 var countComponent2 =  countSiteChildElements("component2", index);
		 var countSubjectOf =  countSiteChildElements("SubjectOf", index);

	  if (countComponent1 !=0)
			   {
			//alert('componenet1 exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(NewSubject2,referenceElement);			
			   }
			   
			else if (countComponent2 !=0)
			   { 
			//alert('component2 exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:component2", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(NewSubject2,referenceElement);			
			   }	   
			   
			   
			 else if (countSubjectOf !=0)  
			 {
			//alert('subjectOf exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subjectOf", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(NewSubject2,referenceElement);			
			   }	     
			   

	  else
			{
			//alert('Append')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			
			var parentElementNode = parElement.snapshotItem(index);
			//alert(parentElementNode)
			parentElementNode.appendChild(NewSubject2);
			} 
};



function deleteSubject2() {
	var siteIndex = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
	// alert(  "Value of studyActivitiesSiteInsert is " + siteIndex);
	var subject2Index = scratchInstance.getElementsByTagName("Subject2Index") [0].childNodes[0].nodeValue -1 ;
	    //alert(  "Value of subject2Index is " + subject2Index);
	var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var parentElementNode = parElement.snapshotItem(siteIndex);
		// alert(  "parentElementNode " + parentElementNode);
	var approvalElement = buildInstance.evaluate("hl7-org_v3:subject2", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var approvalElementNode = approvalElement.snapshotItem(subject2Index);
			// alert(  "approvalElementNode " + approvalElementNode);
		approvalElementNode.parentNode.removeChild(approvalElementNode);		
}



function addNewSubject2Verifier() 
{
	var siteIndex = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
	//alert(  "Value of studyActivitiesSiteInsert is " + siteIndex);
	 	var subject2Index = scratchInstance.getElementsByTagName("Subject2Index") [0].childNodes[0].nodeValue -1 ;
	//alert(  "Value of subject2Index is " + subject2Index);
	  var NewSubject2verifier = getNodesetTemplate("addSubject2verifier", "verifier");
	  
		var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var parentElementNode = parElement.snapshotItem(siteIndex);
		
		var approvalElement = buildInstance.evaluate("hl7-org_v3:subject2", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var approvalElementNode = approvalElement.snapshotItem(subject2Index);
		
		 var refElement = buildInstance.evaluate("hl7-org_v3:subjectProtectionApproval", approvalElementNode, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

		refElement.appendChild(NewSubject2verifier);
}


function deleteSubject2Verifier() {
	var siteIndex = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
	var subject2Index = scratchInstance.getElementsByTagName("Subject2Index") [0].childNodes[0].nodeValue -1 ;
	var Subject2VerifierIndex = scratchInstance.getElementsByTagName("Subject2VerifierIndex") [0].childNodes[0].nodeValue -1 ;
	
	var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var parentElementNode = parElement.snapshotItem(siteIndex);
		// alert(  "parentElementNode " + parentElementNode);
	var approvalElement = buildInstance.evaluate("hl7-org_v3:subject2", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var approvalElementNode = approvalElement.snapshotItem(subject2Index);
			// alert(  "approvalElementNode " + approvalElementNode);
			
			var verifierElement = buildInstance.evaluate("hl7-org_v3:subjectProtectionApproval/hl7-org_v3:verifier", approvalElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var verifierElementNode = verifierElement.snapshotItem(Subject2VerifierIndex);		
		
		verifierElementNode.parentNode.removeChild(verifierElementNode);		
}







function organizationDetails() 
{
	var siteIndex = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
//	alert(  "Value of studyActivitiesSiteInsert is " + siteIndex);
	 	var subject2Index = scratchInstance.getElementsByTagName("Subject2Index") [0].childNodes[0].nodeValue -1 ;
	//alert(  "Value of subject2Index is " + subject2Index);
	  	var Subject2VerifierIndex = scratchInstance.getElementsByTagName("Subject2VerifierIndex") [0].childNodes[0].nodeValue -1 ;
//	alert(  "Value of Subject2VerifierIndex is " + Subject2VerifierIndex);
	 var organizationID = scratchInstance.getElementsByTagName("organizationID") [0].childNodes[0].nodeValue ;
	// alert(  "Value of organizationID is " + organizationID);
	  
	 	var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var parentElementNode = parElement.snapshotItem(siteIndex);
		
		var approvalElement = buildInstance.evaluate("hl7-org_v3:subject2", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var approvalElementNode = approvalElement.snapshotItem(subject2Index);
				
		var verifierElement = buildInstance.evaluate("hl7-org_v3:subjectProtectionApproval/hl7-org_v3:verifier", approvalElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var verifierElementNode = verifierElement.snapshotItem(Subject2VerifierIndex);
		//alert(  "Value of verifierElementNode is " + verifierElementNode);
		
		var ethicalCommittee =buildInstance.evaluate("hl7-org_v3:ethicalCommittee", verifierElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var ethicalCommitteetNode = ethicalCommittee.snapshotItem(0);		
		//	alert('ethicalCommitteetNode' + ethicalCommitteetNode)	


	var commissioningOrganization =buildInstance.evaluate("hl7-org_v3:commissioningOrganization", ethicalCommitteetNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var referenceElement = commissioningOrganization.snapshotItem(0);		
	//	alert('referenceElement' + referenceElement)
		
		 var allsites= buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		for ( var si=0 ; si < allsites.snapshotLength;si++ )   
		{
			var thisSite = allsites.snapshotItem(si)
		
		 var allSubject2s= buildInstance.evaluate("hl7-org_v3:subject2/hl7-org_v3:subjectProtectionApproval", thisSite, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		for ( var s2=0 ; s2 < allSubject2s.snapshotLength;s2++ )   
		{   
			var thisApproval = allSubject2s.snapshotItem(s2)

		 var allVerifiers = buildInstance.evaluate("hl7-org_v3:verifier", thisApproval, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		 
		 var foundMatch = 'No'
		 var matchIndex = ''
		for ( var j=0 ; j < allVerifiers.snapshotLength; j++ )   
		{   
			var verifiers = allVerifiers.snapshotItem(j)
			
				var verifier = buildInstance.evaluate("hl7-org_v3:ethicalCommittee/hl7-org_v3:commissioningOrganization/hl7-org_v3:id", verifiers, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;				
		//	alert (verifier + ' verifier  =   organizationID   '  +  organizationID)
		//	alert (siteIndex + '   siteIndex  not =   si   '  + si)
		//	alert (subject2Index + '   subject2Index  not =   s2   '  + s2)
		//	alert (Subject2VerifierIndex + '   Subject2VerifierIndex  not =   j   '  + j)
			
			if (verifier == organizationID && (siteIndex != si || s2 != subject2Index || Subject2VerifierIndex != j))
				{
						foundMatch = 'Yes'
						matchIndex = j
				}
					if(foundMatch == 'Yes')
						{
							//alert('Set Org Details to index  '  + matchIndex )
								var verifiers = allVerifiers.snapshotItem(matchIndex)
								var verifier = buildInstance.evaluate("hl7-org_v3:ethicalCommittee/hl7-org_v3:commissioningOrganization", verifiers, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
								var selectedOrg = verifier.singleNodeValue.cloneNode(true);
								//alert('selectedOrg' + selectedOrg)
		
								ethicalCommitteetNode.insertBefore(selectedOrg,referenceElement);	
								
								var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
									var parentElementNode = parElement.snapshotItem(siteIndex);
									
									var approvalElement = buildInstance.evaluate("hl7-org_v3:subject2", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
									var approvalElementNode = approvalElement.snapshotItem(subject2Index);
									
									var approvalElement = buildInstance.evaluate("hl7-org_v3:subject2", parentElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
									var approvalElementNode = approvalElement.snapshotItem(subject2Index);
									
									var verifierElement = buildInstance.evaluate("hl7-org_v3:subjectProtectionApproval/hl7-org_v3:verifier", approvalElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
									var verifierElementNode = verifierElement.snapshotItem(Subject2VerifierIndex);
									
									var ethicalCommittee =buildInstance.evaluate("hl7-org_v3:ethicalCommittee", verifierElementNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
													var ethicalCommitteetNode = ethicalCommittee.snapshotItem(0);		
																			
									var commissioningOrganization =buildInstance.evaluate("hl7-org_v3:commissioningOrganization", ethicalCommitteetNode, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
									var commissioningOrganizationNode = commissioningOrganization.snapshotItem(1);	
									
								commissioningOrganizationNode.parentNode.removeChild(commissioningOrganization.snapshotItem(1));
								si = siteIndex.snapshotLength
								s2 = allSubject2s.snapshotLength
								break;
						}
		} // End For Loop 
}
}
}



function addInvestigatorsSelection() {
 var primaryPerformerPath = getUserSelectionPath();
 var NewUserSelection = getNodesetTemplate("addUserSelection", "selection");
    primaryPerformerPath.appendChild(NewUserSelection);
}

function getUserSelectionPath() {
 var firstPath = userSelectInstance.evaluate("/hl7-org_v3:data", userSelectInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    var path = firstPath.singleNodeValue;
    return path; 
    }
			
			
	function addNewPrimaryPerformerSite() 
{
	 // alert( "Value of studyActivitiesSiteInsert is " + scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue) ;
	 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
	 	 var SiteInvestigatorsIndex = scratchInstance.getElementsByTagName("SiteInvestigatorsIndex") [0].childNodes[0].nodeValue -1 ;
	//alert(  "Value of studyActivitiesSiteInsert is " + index);
	//alert(  "Value of SiteInvestigatorsIndex is " + SiteInvestigatorsIndex);
	
	 var NewPrimaryPerformer = getNodesetTemplate("addPrimaryPerformerSite", "primaryPerformer"); 
	var countSecondaryPerformer =  countSiteChildElements("secondaryPerformer", index);
	var countPrimaryPerformer =  sitePrimaryCount(index);
	//alert(' countPrimaryPerformer  ' +  countPrimaryPerformer)
	
	
	var primaryStudy = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
	if (primaryStudy == true)	
	{
	// alert ("Total countSecondaryPerformer are : " + countSecondaryPerformer);
	
	if (countPrimaryPerformer !=0)	
		{
		alert('Only one Primary Investigator can be added to a site.');	
		}
		
	else if (countSecondaryPerformer !=0)
			   {
			//alert('secondary exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("hl7-org_v3:secondaryPerformer", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(0);
			parentElement.insertBefore(NewPrimaryPerformer,referenceElement);			
			
			   }
	  else
			{
			//alert('before location')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes =buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);		
		   var referenceElement = allSecondaryPerformerNodes.snapshotItem(0);
			parentElement.insertBefore(NewPrimaryPerformer,referenceElement);	
			} 
			

	}
	else
	{
		alert('There are no Investigators defined.');	
	}        
};		




function deletePrimaryPerformerSite() 
{
	 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
	 var Investigatorindex = scratchInstance.getElementsByTagName("SiteInvestigatorsIndex") [0].childNodes[0].nodeValue -1 ;
	//alert(  "Value of studyActivitiesSiteInsert is " + index);
	//alert(  "Value of Investigatorindex is " + Investigatorindex);

			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allPrimaryPerformers = buildInstance.evaluate("hl7-org_v3:primaryPerformer", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			
				for ( var i=0 ; i < allPrimaryPerformers.snapshotLength; i++ )   
				{   
				var primaryPerformer =allPrimaryPerformers.snapshotItem(i);
				
				var thisCode = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:code/hl7-org_v3:originalText", primaryPerformer, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent;
				if(thisCode == 'PRIMARY')
				{
					//alert('Found Primary')
						primaryPerformer.parentNode.removeChild(primaryPerformer);
						return;
				}
				
				}  ;
	

}


function deletePrimaryPerformerSUBSite() 
{
	 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
	 var Investigatorindex = scratchInstance.getElementsByTagName("SiteSUBInvestigatorsIndex") [0].childNodes[0].nodeValue -1 ;
	//alert(  "Value of studyActivitiesSiteInsert is " + index);
//	alert(  "Value of Investigatorindex is " + Investigatorindex);

			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allPrimaryPerformers = buildInstance.evaluate("hl7-org_v3:primaryPerformer[hl7-org_v3:investigator/hl7-org_v3:code/hl7-org_v3:originalText='SUBINVESTIGATOR']", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	//		alert(  "allPrimaryPerformers " + allPrimaryPerformers);
			var count = allPrimaryPerformers.snapshotLength
		//		alert(  "allPrimaryPerformers count " + count);
				for ( var i=0 ; i < allPrimaryPerformers.snapshotLength; i++ )   
				{   
				var primaryPerformer =allPrimaryPerformers.snapshotItem(Investigatorindex);
				
						primaryPerformer.parentNode.removeChild(primaryPerformer);
						return;
				}


}


	function sitePrimaryCount(index) 
	{
			 var sitePath = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var path = sitePath.snapshotItem(index);
			
			 var primaryPath = buildInstance.evaluate("hl7-org_v3:primaryPerformer/hl7-org_v3:investigator[hl7-org_v3:code/hl7-org_v3:originalText='PRIMARY']", path, nsResolver,  XPathResult.BOOLEAN_TYPE, null).booleanValue;
			
		     if (primaryPath == true)
		     {
		     	//alert('Primary assigned');
				var i=1;
				return i;
			}
			else
			{
				//alert('No Primary');
				var i=0;
				return i;
			}
}


	function studyPrimaryCount() 
	{
			 var primary = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer[./hl7-org_v3:investigator/hl7-org_v3:code/hl7-org_v3:originalText='PRINCIPAL']", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

			var primaryCount =  primary.snapshotLength;
			if (primaryCount >= 1)
				{
				alert('The study may only have one Principal  Investigator.')	
				}
			else 
				{
				//Study Can have one primary
				}
}


	function addNewSubPerformerSite() 
{
	 // alert( "Value of studyActivitiesSiteInsert is " + scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue) ;
	 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
	// alert(  "Value of studyActivitiesSiteInsert is " + index);
	 var NewPrimaryPerformer = getNodesetTemplate("addSubPerformerSite", "primaryPerformer"); 
	var countSecondaryPerformer =  countSiteChildElements("secondaryPerformer", index);
	var countPrimaryPerformer =  countSiteChildElements("primaryPerformer", index);	
	// alert ("Total countSecondaryPerformer are : " + countSecondaryPerformer);
	var subStudy = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
	if (subStudy == true)	
	{	
		if (countSecondaryPerformer !=0)
			   {
			//alert('secondary exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("hl7-org_v3:secondaryPerformer", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(0);
			parentElement.insertBefore(NewPrimaryPerformer,referenceElement);			
			
			   }
	  else
			{
			//alert('before location')

			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes =buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);		
		   var referenceElement = allSecondaryPerformerNodes.snapshotItem(0);
			parentElement.insertBefore(NewPrimaryPerformer,referenceElement);				
			
			}     
	}
	else
	{
	alert('There are no Investigators defined.');		
	}		    
};		


function addNewSecondaryPerformerSite() {
	var secondaryPerformer = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
	
	if (secondaryPerformer == true)	
	{
		 var NewSecondaryPerformer = getNodesetTemplate("addSecondaryPerformerSite", "secondaryPerformer"); 
		var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1;
		  var providerIndex=scratchInstance.getElementsByTagName("SiteProvidersIndex") [0].childNodes[0].nodeValue;
		 // alert('providerIndex  ' + providerIndex)
		var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var parentElement = parElement.snapshotItem(index);
		
		var allSecondaryPerformerNodes =buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var referenceElement = allSecondaryPerformerNodes.snapshotItem(0);
		parentElement.insertBefore(NewSecondaryPerformer,referenceElement);	
		
	}
	else
		{
	alert('There are no Service Providers defined.');		
	}		
	
}

function deleteSecondaryPerformerSite() {

		  var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue-1 ;
		  var providerIndex=scratchInstance.getElementsByTagName("SiteProvidersIndex") [0].childNodes[0].nodeValue-1;
		  
		 var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var parentElement = parElement.snapshotItem(index);
		
		 var allPerformers = buildInstance.evaluate("hl7-org_v3:secondaryPerformer", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var thisPerformer = allPerformers.snapshotItem(providerIndex);
		
		thisPerformer.parentNode.removeChild(thisPerformer);
}



function removeSite() {
 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue - 1 ;
if(index >= 0)
{
	var sites = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var site = sites.snapshotItem(index);
	var siteID = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:id", site, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
	var humanElement = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPerson", site, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;	
	var animalElement = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject", site, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;	

	
	if ( humanElement == true  ||  animalElement == true)   
	{
		if (confirm ("Site " + siteID +" has subjects assigned to it, do you wish to delete this site? "))
		{
				site.parentNode.removeChild(site);
		}
		
		else
		{
			//alert('Do Not Remove')
		}
		
	}
	else
	{
	// Subjects are not assigned to site  Proceed with delete
	site.parentNode.removeChild(site);
	}
	}
}




function doesSiteExist() {
	var site = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;
	if (site == true)	
	{
	}	
	else
	{
	alert('Subjects can only be defined after a site is created.');
	}
}

function deleteCurrent(){

     var nodesSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
 var buildPath = nodesSnapshot.snapshotItem(); 
 alert(buildPath);
	for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )   
		{   
				buildPath.parentNode.removeChild(nodesSnapshot.snapshotItem(i))};
		}  ;


function addSelected(){
 var activitiesSiteIndex = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].textContent - 1;
 alert(activitiesSiteIndex);
 var firstPath = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
      var buildPath = firstPath.snapshotItem(activitiesSiteIndex); 
 
     var nodesSnapshot = userSelectInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:selection/hl7-org_v3:site/hl7-org_v3:primaryPerformer", userSelectInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
	for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )   
		{   
				buildPath.appendChild(nodesSnapshot.snapshotItem(i).cloneNode(true))};
		}  ;

function getInvestigatorPath() {
 var firstPath = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    var path = firstPath.singleNodeValue;
    return path; 
    };


function setUserSelectInstance() {
var nodesSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
 var buildPath = getUserSelectionPath();
	for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )   
	{   
			buildPath.appendChild(nodesSnapshot.snapshotItem(i))};
			alert(i);
	}  ;

	function addEUID() 
{

var NewID = getNodesetTemplate("addNewId", "id");
}


	function addNewSubjectPerson() 
{
	 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue - 1 ;
//	  alert(  "Value of studyActivitiesSiteInsert is " + index);
	  var NewSubjectPerson = getNodesetTemplate("addSubjectPerson", "subject1");
	var countPrimaryPerformer =  countSiteChildElements("primaryPerformer", index);
	var countSecondaryPerformer =  countSiteChildElements("secondaryPerformer", index);
	var studyID = buildInstance.evaluate("//hl7-org_v3:plannedStudy/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;
		if (studyID == "")
		{	
		 alert('Please enter a valid Study Identifier before adding subjects.')
		 return;
		 }
		 
		var max = maxPersonID()
		m = max+1
		var newSubjectID = studyID + '_' + siteID + '_' + m

				
		var sites = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
//alert('sites  '  +  sites)
	var site = sites.snapshotItem(index);
	
				var siteID = buildInstance.evaluate("hl7-org_v3:id", site, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;		
		//	alert(' siteID ' + siteID)
			
											var siteID = buildInstance.evaluate("hl7-org_v3:id", site, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;		
								if (siteID == "")
											{	
											 alert('Please enter a valid Site Identifier before adding subjects.')
											 return;
											 }
										

								var newSubjectID = studyID + '_' + siteID + '_' +m
				//	alert('newSubjectID        '    + newSubjectID)	
					
				var resetID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPerson/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
				
						resetID.setAttribute("extension", newSubjectID) ;
						
					var newEUID =  studyID + '_' + siteID + '_' + m
					//	alert('newEUID        '    + newEUID)	
													
					var resetEUID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
												
					resetEUID.setAttribute("extension", newEUID) ;
							 var subElement = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
				//		alert('subElement    ' + subElement )	
						 
						 var subjectElement = subElement.singleNodeValue.cloneNode(true);
					//		alert('subjectElement    ' + subjectElement );	
							
	if (countPrimaryPerformer !=0)
			   {
		//	 alert('Primary exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			 //alert('parentElement   '  + parentElement)
			var allSecondaryPerformerNodes = buildInstance.evaluate("hl7-org_v3:primaryPerformer", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(0);
					//	alert('referenceElement   '  + referenceElement)
			parentElement.insertBefore(subjectElement,referenceElement);			
			   }
	else if (countSecondaryPerformer !=0)
			   {
		//	 alert('secondary exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("hl7-org_v3:secondaryPerformer", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(0);
			parentElement.insertBefore(subjectElement,referenceElement);			
			   }
	  else
			{
				       //alert('before location')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes =buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);		
		   var referenceElement = allSecondaryPerformerNodes.snapshotItem(0);
			parentElement.insertBefore(subjectElement,referenceElement);	

			}         
			studyIdentifierExist()
};		

function addExistingSubjectPerson() {

 var repeat_component1 = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1;
 var euBeginDate = scratchInstance.getElementsByTagName("euBeginDate") [0].childNodes[0].nodeValue;
		 //alert('euBeginDate          '  + euBeginDate);
  var euBeginDateScratch = scratchInstance.getElementsByTagName("euBeginDateScratch") [0].childNodes[0].nodeValue;
		  //alert ('euBeginDateScratch      ' +  euBeginDateScratch);
  var euEndDateScratch = scratchInstance.getElementsByTagName("euEndDateScratch") [0].childNodes[0].nodeValue;  
			// alert ('euEndDateScratch      ' +  euEndDateScratch);
    var euStatusCodeScratch = scratchInstance.getElementsByTagName("euStatusCodeScratch") [0].childNodes[0].nodeValue;  
		// alert ('euStatusCodeScratch      ' +  euStatusCodeScratch);
  var SelectedSubject = scratchInstance.getElementsByTagName("SelectedSubject") [0].textContent.toLowerCase();
		 //alert('SelectedSubject          '  + SelectedSubject);
		 
		 var nodesSnapshotSites = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
			
			//alert('nodesSnapshotSites ' +"       " +nodesSnapshotSites.snapshotLength);

			for ( var j=0 ; j < nodesSnapshotSites.snapshotLength; j++ )
			{
				//alert('value of J     ' + j + '       Value of repeat_component1  ' + repeat_component1) 
				if ( j != repeat_component1)
				{
				var nonMatchingSite = nodesSnapshotSites.snapshotItem(j); 
					// 	alert('nonMatchingSite      '    + nonMatchingSite )
				var nodesSnapshot = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPerson/hl7-org_v3:id/@extension", nonMatchingSite, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
				
				//alert('nodesSnapshot ' + nodesSnapshot  +"       " + nodesSnapshot.snapshotLength );
				
				var nodesSnapshot2 = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subject1", nonMatchingSite, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
	  // alert('nodesSnapshot2      ' + nodesSnapshot2  +"       " + nodesSnapshot2.snapshotLength);



				for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )
					{
		try{
			   var existingSubject =   nodesSnapshot.snapshotItem(i).childNodes[0].nodeValue.toLowerCase();
			}
			catch(err)
				{

				}			   
			   
		//  alert(SelectedSubject +' == ' + existingSubject);
				if ( SelectedSubject == existingSubject)   
						{ 
						var matchingNode = nodesSnapshot2.snapshotItem(i); 
		// alert(matchingNode);
						var BeginDate = buildInstance.evaluate("hl7-org_v3:experimentalUnit/hl7-org_v3:effectiveTime/hl7-org_v3:low", matchingNode, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;					
	 //alert(BeginDate);									
						var EndDate = buildInstance.evaluate("hl7-org_v3:experimentalUnit/hl7-org_v3:effectiveTime/hl7-org_v3:high", matchingNode, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;		
				// alert(EndDate);						
						var StatusCode = buildInstance.evaluate("hl7-org_v3:experimentalUnit/hl7-org_v3:statusCode", matchingNode, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("code").nodeValue;	
					// alert(StatusCode);	
					 		
						scratchInstance.getElementsByTagName("euBeginDate") [0].childNodes[0].nodeValue=BeginDate;
						scratchInstance.getElementsByTagName("euEndDate") [0].childNodes[0].nodeValue=EndDate;
						scratchInstance.getElementsByTagName("euStatusCode") [0].childNodes[0].nodeValue=StatusCode;
							return;
						}
							else
						{

								scratchInstance.getElementsByTagName("euBeginDate") [0].childNodes[0].nodeValue=euBeginDateScratch;
								scratchInstance.getElementsByTagName("euEndDate") [0].childNodes[0].nodeValue=euEndDateScratch;
								scratchInstance.getElementsByTagName("euStatusCode") [0].childNodes[0].nodeValue=euStatusCodeScratch;
							//alert('noChange');							
						}
				}		

				}
				else
				{
				//alert('do nothing');
				}	
		}
		studyIdentifierExist()
}



function generateNonPersonSubjects(importQuantity, studyCellArm, subjectCounter, rootID) 
{
	//alert('generate  ' + importQuantity)
var quantity = importQuantity;
var subjectCounter = subjectCounter;
var rootID = rootID
var index=scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1;
var sites = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var site = sites.snapshotItem(index);
	var siteID = buildInstance.evaluate("hl7-org_v3:id", site, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
if (quantity > 0)
	{
						for ( var i=0 ; i < quantity; i++ )   
					{   
					var newSubjectID = rootID + '_' + subjectCounter + '______' + studyCellArm
						//	alert('newSubjectID        '    + newSubjectID)	
														
						var resetID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
						resetID.setAttribute("extension", newSubjectID) ;
												
						var newEUID = rootID + '_//////' + siteID + '__zzzzzz_' + subjectCounter														
						var resetEUID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;															
						resetEUID.setAttribute("extension", newEUID) ;
															
															
						var setQuantity = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:quantity", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
						setQuantity.setAttribute("value", "1") ;									
					
	 var subElement = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			//alert('subElement    ' + subElement )	
			 
			 var subjectElement = subElement.singleNodeValue.cloneNode(true);
				//alert('subjectElement    ' + subjectElement );	
	

			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		  
			var parentElement = parElement.snapshotItem(index);
			// alert('parentElement    ' + parentElement );

							var refElement = buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
							var referenceElement = refElement.singleNodeValue;	
								 // alert('referenceElement    ' + referenceElement );
										//	alert('i equals    ' + i );
												//alert('insert before location');
													parentElement.insertBefore(subjectElement,referenceElement);	
					subjectCounter++
								}
					} 	
			var newSubjectID = ""
			//alert('newSubjectID        '    + newSubjectID)	
										
		var resetID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
		resetID.setAttribute("extension", newSubjectID) ;		
}

function generateNonPersonSubjectsExists(passSubject, passSubjectEUID)
{
var passSubject = passSubject
var passSubjectEUID = passSubjectEUID
var index=scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1;
var sites = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var site = sites.snapshotItem(index);
	var siteID = buildInstance.evaluate("hl7-org_v3:id", site, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
	
					var newSubjectID = passSubject
						//	alert('newSubjectID        '    + newSubjectID)	
														
						var resetID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
						resetID.setAttribute("extension", newSubjectID) ;
							
						var subject =	passSubjectEUID.split('//////')	
						var subject2 =	passSubjectEUID.split('__zzzzzz')	
						var newEUID =  subject[0]  + siteID + subject2[1] 
						
																	
						var resetEUID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;															
						resetEUID.setAttribute("extension", newEUID) ;
															
															
						var setQuantity = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:quantity", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
						setQuantity.setAttribute("value", "1") ;									
					
	 var subElement = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			//alert('subElement    ' + subElement )	
			 
			 var subjectElement = subElement.singleNodeValue.cloneNode(true);
				//alert('subjectElement    ' + subjectElement );	
	

			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		  
			var parentElement = parElement.snapshotItem(index);
			// alert('parentElement    ' + parentElement );

							var refElement = buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
							var referenceElement = refElement.singleNodeValue;	
								 // alert('referenceElement    ' + referenceElement );
										//	alert('i equals    ' + i );
												//alert('insert before location');
													parentElement.insertBefore(subjectElement,referenceElement);	
													studyIdentifierExist()
}



function generateNonPersonSubjects2() 
{
var SelectedSite=scratchInstance.getElementsByTagName("SelectedSite") [0].childNodes[0].nodeValue ;
var quantity = scratchInstance.getElementsByTagName("SubjectQuantity") [0].childNodes[0].nodeValue -0;
var studyID = buildInstance.evaluate("//hl7-org_v3:plannedStudy/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;
if (studyID == "")
{	
 alert('Please enter a valid Study Identifier before adding subjects.')
 return;
 }
		if (SelectedSite == "0")
	{	
	 alert('Please select a site.')
	 return;
	 }			
	if (quantity > 0)
		{				   
			var siteAllSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);

					var m =  maxNonPersonID()

						for ( var j=0 ; j < siteAllSnapshot.snapshotLength; j++ )   
							{   
								var loopQuantity = 0
							   var siteSnapshot =   siteAllSnapshot.snapshotItem(j);
								// alert('siteSnapshot     ' + siteSnapshot )		   
								 
									var idSnapshot = buildInstance.evaluate("hl7-org_v3:id", siteSnapshot, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE , null).singleNodeValue.getAttributeNode("extension").nodeValue;	
				
										
									if (idSnapshot == SelectedSite)   
											{
								var index = j;
									var sites = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
								var site = sites.snapshotItem(index);
								
											var siteID = buildInstance.evaluate("hl7-org_v3:id", site, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;		
										// alert(' siteID ' + siteID)
										var siteID 
										
										var i = m + 1		
										var loopQuantity = 	quantity+i	
		
										for (; i < loopQuantity; i++ )   
														{   
														var newSubjectID = studyID + '_' +siteID + '_' + i
													//	alert('newSubjectID        '    + newSubjectID)	
														
													var resetID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
															resetID.setAttribute("extension", newSubjectID) ;
														var newEUID = studyID + '_' +  siteID + '_' + i
															//alert('newEUID        '    + newEUID)		
														var resetEUID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;					
														resetEUID.setAttribute("extension", newEUID) ;

														var setQuantity = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:quantity", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
													
													setQuantity.setAttribute("value", "1") ;	
								
												 var subElement = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
												//alert('subElement    ' + subElement )	
												 
												 var subjectElement = subElement.singleNodeValue.cloneNode(true);
													//alert('subjectElement    ' + subjectElement );	
										
												var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	  
												var parentElement = parElement.snapshotItem(index);
												 //alert('parentElement    ' + parentElement );
												 
											   var existingSubjectsAtSite = buildInstance.evaluate("hl7-org_v3:subject1", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	  
												var subjectAlreadyAtSite = "No"
												for ( var existing=0 ; existing < existingSubjectsAtSite.snapshotLength; existing++ )   
													 {
													 var existingSubjectAtSite = existingSubjectsAtSite.snapshotItem(existing);
													 //alert('existingSubjectAtSite    ' + existingSubjectAtSite );
													var existingSubject = buildInstance.evaluate("hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:id", existingSubjectAtSite, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;			  
												 
													  //alert(existingSubject  + ' = ' + newSubjectID )
													 if ( existingSubject == newSubjectID)
															 {
															// alert('Subject '+  newSubjectID  + ' already assigned to  ' + siteID)
															 subjectAlreadyAtSite = "Yes"
															};
														} // for Subjects already as site
														
														 if ( subjectAlreadyAtSite == 'No' )
																 {
																var refElement = buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
																var referenceElement = refElement.singleNodeValue;	
																	 // alert('referenceElement    ' + referenceElement );
																			//	alert('i equals    ' + i );
																					//alert('insert before location');
																						parentElement.insertBefore(subjectElement,referenceElement);	
																};
													};		 //for quantity loop
											};		 // if site was found		
										};		 // for all sites   			
	};				// if quantity is greater than 0
	studyIdentifierExist()
}

function generatePersonSubjectsExists(passSubject, passSubjectEUID)
{
var passSubject = passSubject
var passSubjectEUID = passSubjectEUID
var index=scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1;
var sites = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var site = sites.snapshotItem(index);
	var siteID = buildInstance.evaluate("hl7-org_v3:id", site, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
	
					var newSubjectID = passSubject
						//alert('newSubjectID        '    + newSubjectID)	
														
						var resetID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPerson/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
						resetID.setAttribute("extension", newSubjectID) ;
							
						var subject =	passSubjectEUID.split('//////')	
						var subject2 =	passSubjectEUID.split('__zzzzzz')	
						var newEUID =  subject[0]  + siteID + subject2[1] 
						//alert('newEUID  ' + newEUID)
																	
						var resetEUID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;															
						resetEUID.setAttribute("extension", newEUID) ;
															
	 var subElement = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			//alert('subElement    ' + subElement )	
			 
			 var subjectElement = subElement.singleNodeValue.cloneNode(true);
				//alert('subjectElement    ' + subjectElement );	
	

			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		  
			var parentElement = parElement.snapshotItem(index);
			// alert('parentElement    ' + parentElement );

							var refElement = buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
							var referenceElement = refElement.singleNodeValue;	
								 // alert('referenceElement    ' + referenceElement );
										//	alert('i equals    ' + i );
												//alert('insert before location');
													parentElement.insertBefore(subjectElement,referenceElement);	
													studyIdentifierExist()
}


function generatePersonSubjects() 
{
var SelectedSite=scratchInstance.getElementsByTagName("SelectedSite") [0].childNodes[0].nodeValue ;
 //alert('SelectedSite     ' + SelectedSite )
var quantity = scratchInstance.getElementsByTagName("SubjectQuantity") [0].childNodes[0].nodeValue -0;
				  // alert('quantity     ' + quantity )
var studyID = buildInstance.evaluate("//hl7-org_v3:plannedStudy/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;
	if (studyID == "")
	{	
	 alert('Please enter a valid Study Identifier before adding subjects.')
	 return;
	 }				  
	
	if (SelectedSite == "0")
	{	
	 alert('Please select a site.')
	 return;
	 }			
	 	  			  
	if (quantity > 0)
		{				   
			var siteAllSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);

					var m =  maxPersonID()
						for ( var j=0 ; j < siteAllSnapshot.snapshotLength; j++ )   
							{   
								var loopQuantity = 0
							   var siteSnapshot =   siteAllSnapshot.snapshotItem(j);
								// alert('siteSnapshot     ' + siteSnapshot )		   
								 
									var idSnapshot = buildInstance.evaluate("hl7-org_v3:id", siteSnapshot, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE , null).singleNodeValue.getAttributeNode("extension").nodeValue;	
										//var inList = SelectedSite.match(idSnapshot)
										
									if (idSnapshot == SelectedSite)   
											{
								var index = j;
									var sites = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
								//alert('sites  '  +  sites)
								var site = sites.snapshotItem(index);
								
											var siteID = buildInstance.evaluate("hl7-org_v3:id", site, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;		
										var siteID 
										

										var i = m + 1		
										var loopQuantity = 	quantity+i	
												for (; i < loopQuantity; i++ )   
														{   
														var newSubjectID = studyID + '_' +siteID + '_' + i
													//	alert('newSubjectID        '    + newSubjectID)	
														
													var resetID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPerson/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
													
															resetID.setAttribute("extension", newSubjectID) ;
															
														var newEUID =  studyID + '_' + siteID + '_' + i
														//	alert('newEUID        '    + newEUID)	
																						
														var resetEUID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
																					
														resetEUID.setAttribute("extension", newEUID) ;

														
																	 var subElement = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
																	//alert('subElement    ' + subElement )	
																	 
																	 var subjectElement = subElement.singleNodeValue.cloneNode(true);
																		//alert('subjectElement    ' + subjectElement );	
															
																	var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	  
																	var parentElement = parElement.snapshotItem(index);
																	 //alert('parentElement    ' + parentElement );
																	 
																	var existingSubjectsAtSite = buildInstance.evaluate("hl7-org_v3:subject1", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	  
																	
																	var subjectAlreadyAtSite = "No"
																	for ( var existing=0 ; existing < existingSubjectsAtSite.snapshotLength; existing++ )   
																		 {
																		 var existingSubjectAtSite = existingSubjectsAtSite.snapshotItem(existing);
																		 //alert('existingSubjectAtSite    ' + existingSubjectAtSite );
																	 	var existingSubject = buildInstance.evaluate("hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPerson/hl7-org_v3:id", existingSubjectAtSite, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;			  
																	 
																		  //alert(existingSubject  + ' = ' + newSubjectID )
																		 if ( existingSubject == newSubjectID)
																				 {
																				 alert('Subject '+  newSubjectID  + ' already assigned to  ' + siteID)
																				 subjectAlreadyAtSite = "Yes"
																				}
																		 	}
																		 	
																		 	 if ( subjectAlreadyAtSite == 'No' )
																		 	 {
																		 	 //alert('Add NEW subject' + newSubjectID)
																			var refElement = buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
																			var referenceElement = refElement.singleNodeValue;	
																				 // alert('referenceElement    ' + referenceElement );
																						//	alert('i equals    ' + i );
																								//alert('insert before location');
																				parentElement.insertBefore(subjectElement,referenceElement);	
																			}
																		
																	
																	}
														} 															 
										}  ;   			
	};	
	studyIdentifierExist()
}


function generatePersonSubjectsImport(importQuantity, studyCellArm, subjectCounter, rootID) 
{
	//alert('generate  ' + importQuantity)
var quantity = importQuantity;
var subjectCounter = subjectCounter;
var rootID = rootID
var index=scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1;
var sites = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var site = sites.snapshotItem(index);
	var siteID = buildInstance.evaluate("hl7-org_v3:id", site, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
if (quantity > 0)
	{
						for ( var i=0 ; i < quantity; i++ )   
					{   
					var newSubjectID = rootID + '_' + subjectCounter + '______' + studyCellArm
						//	alert('newSubjectID        '    + newSubjectID)	
														
						var resetID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPerson/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
						resetID.setAttribute("extension", newSubjectID) ;
												
						var newEUID = rootID + '_//////' + siteID + '__zzzzzz_' + subjectCounter														
						var resetEUID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;															
						resetEUID.setAttribute("extension", newEUID) ;
															
	 var subElement = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			//alert('subElement    ' + subElement )	
			 
			 var subjectElement = subElement.singleNodeValue.cloneNode(true);
				//alert('subjectElement    ' + subjectElement );	
	

			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		  
			var parentElement = parElement.snapshotItem(index);
			// alert('parentElement    ' + parentElement );

							var refElement = buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
							var referenceElement = refElement.singleNodeValue;	
								 // alert('referenceElement    ' + referenceElement );
										//	alert('i equals    ' + i );
												//alert('insert before location');
													parentElement.insertBefore(subjectElement,referenceElement);	
					subjectCounter++
								}
					} 	
			var newSubjectID = ""
			//alert('newSubjectID        '    + newSubjectID)	
										
		var resetID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultHuman/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPerson/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
		resetID.setAttribute("extension", newSubjectID) ;		
		studyIdentifierExist()
}


function deleteAllSubjectsSite() {
		if (confirm ("Do you wish to remove all subjects from this site? "))
			{
			 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
			// alert('index   '   +  index);
				var siteSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
				var nodesSnapshot = siteSnapshot.snapshotItem(index);
				//alert('nodesSnapshot   '   +  nodesSnapshot);
				var nodesSnapshot2 = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subject1", nodesSnapshot, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
			//alert('nodesSnapshot2   '   +  nodesSnapshot2);
									for ( var i=0 ; i < nodesSnapshot2.snapshotLength; i++ )   
										{   
										//	alert('value of i is   '   +  i);
										   var subjectNode =   nodesSnapshot2.snapshotItem(i);
										  // 	alert('subjectNode   '   +  subjectNode);
										   
															subjectNode.parentNode.removeChild(nodesSnapshot2.snapshotItem(i))
										};	
		
				}						
		else
				{
			// Do Nothing
				};
				studyIdentifierExist()
  };

		
function deleteSubjectAtSite() {

			 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
			// alert('index   '   +  index);
			var subjectIndex = scratchInstance.getElementsByTagName("personSubjectIndex") [0].childNodes[0].nodeValue -1 ;
			// alert('subjectIndex   '   +  subjectIndex);
			
				var siteSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
				var nodesSnapshot = siteSnapshot.snapshotItem(index);
				//alert('nodesSnapshot   '   +  nodesSnapshot);
				
				var nodesSnapshot2 = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subject1", nodesSnapshot, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
				var thisSubject = nodesSnapshot2.snapshotItem(subjectIndex);

			thisSubject.parentNode.removeChild(thisSubject)
studyIdentifierExist()
		
  };
  
function addNewSubjectNonPerson() 
{
	 //alert( "Value of studyActivitiesSiteInsert is " + scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue) ;
	 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
	//alert(  "Value of studyActivitiesSiteInsert is " + index);
	 var NewSubjectNonPerson = getNodesetTemplate("addSubjectNonPerson", "subject1");
	var countPrimaryPerformer =  countSiteChildElements("primaryPerformer", index);
	var countSecondaryPerformer =  countSiteChildElements("secondaryPerformer", index);
	var studyID = buildInstance.evaluate("//hl7-org_v3:plannedStudy/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;
		if (studyID == "")
		{	
		 alert('Please enter a valid Study Identifier before adding subjects.')
		 return;
		 }
		 
		var max = maxNonPersonID()
		m = max+1
		var newSubjectID = studyID + '_' +siteID + '_' + m
				//	alert('newSubjectID        '    + newSubjectID)	
				
				var sites = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	//alert('sites  '  +  sites)
	var site = sites.snapshotItem(index);
	
				var siteID = buildInstance.evaluate("hl7-org_v3:id", site, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;		
			//alert(' siteID ' + siteID)
			
											var siteID = buildInstance.evaluate("hl7-org_v3:id", site, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;		
														if (siteID == "")
											{	
											 alert('Please enter a valid Site Identifier before adding subjects.')
											 return;
											 }

			
		var resetID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
		resetID.setAttribute("extension", newSubjectID) ;
		var newEUID = studyID + '_' +  siteID + '_' + m
				//alert('newEUID        '    + newEUID)		
		var resetEUID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;					
		resetEUID.setAttribute("extension", newEUID) ;
		
		var setQuantity = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:quantity", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
		
		setQuantity.setAttribute("value", "1") ;	
		
		var subElement = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaults/hl7-org_v3:subject1", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		//alert('subElement    ' + subElement )	
		
		var subjectElement = subElement.singleNodeValue.cloneNode(true);

	if (countPrimaryPerformer !=0)
			   {
			// alert('Primary exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(subjectElement,referenceElement);			
			   }
	else if (countSecondaryPerformer !=0)
			   {
			 //alert('secondary exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(subjectElement,referenceElement);			
			   }
	  else
			{
			 //alert('before location')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes =buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);		
		   var referenceElement = allSecondaryPerformerNodes.snapshotItem(0);
			parentElement.insertBefore(subjectElement,referenceElement);	
			}         
studyIdentifierExist()
};		


function maxNonPersonID()
{
		var allSubjectsSnapshot = buildInstance.evaluate("//hl7-org_v3:subjectNonPersonLivingSubject", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);	
		var m=0;
		var thisID = 0;
		
		// Find the max subject ID
		for(var maxCount=0 ; maxCount < allSubjectsSnapshot.snapshotLength; maxCount++ )   
			{
				var checkThisID = allSubjectsSnapshot.snapshotItem(maxCount)
			var thisID = buildInstance.evaluate("hl7-org_v3:id", checkThisID, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE , null).singleNodeValue.getAttributeNode("extension").nodeValue;	
				var newID = thisID.split('_')
				if (m < newID[1] ) 
						m=newID[1]-0; 	
			}		
			return m;
}


function maxPersonID()
{
		var allSubjectsSnapshot = buildInstance.evaluate("//hl7-org_v3:subjectPerson", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);	
		var m=0;
		var thisID = 0;
		
		// Find the max subject ID
		for(var maxCount=0 ; maxCount < allSubjectsSnapshot.snapshotLength; maxCount++ )   
			{
				var checkThisID = allSubjectsSnapshot.snapshotItem(maxCount)
			var thisID = buildInstance.evaluate("hl7-org_v3:id", checkThisID, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE , null).singleNodeValue.getAttributeNode("extension").nodeValue;	
				var newID = thisID.split('_')
				if (m < newID[2] ) 
						m=newID[2]-0; 	
			}		
			return m;
}


		function spaceInString(my_string)
		{
		var find_space=my_string.indexOf(' ');
			if(find_space == -1)
				return false
				else
				return true
		}

function addNewSubjectProduct() 
{
	 //alert( "Value of studyActivitiesSiteInsert is " + scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue) ;
	 var index = scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue -1 ;
	//alert(  "Value of studyActivitiesSiteInsert is " + index);
	 var NewSubjectProduct = getNodesetTemplate("addSubjectProduct", "subject1");
	var countPrimaryPerformer =  countSiteChildElements("primaryPerformer", index);
	var countSecondaryPerformer =  countSiteChildElements("secondaryPerformer", index);
	if (countPrimaryPerformer !=0)
			   {
			// alert('Primary exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(NewSubjectProduct,referenceElement);			
			   }
	else if (countSecondaryPerformer !=0)
			   {
			 //alert('secondary exists')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:secondaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var referenceElement = allSecondaryPerformerNodes.snapshotItem(index);
			parentElement.insertBefore(NewSubjectProduct,referenceElement);			
			   }
	  else
			{
			 //alert('before location')
			var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			var parentElement = parElement.snapshotItem(index);
			var allSecondaryPerformerNodes =buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);		
		   var referenceElement = allSecondaryPerformerNodes.snapshotItem(0);
			parentElement.insertBefore(NewSubjectProduct,referenceElement);	
			}         
};		



function generateProducts() 
{
var SelectedSite=scratchInstance.getElementsByTagName("SelectedSite") [0].childNodes[0].nodeValue ;
 //alert('SelectedSite     ' + SelectedSite )

var quantity = scratchInstance.getElementsByTagName("SubjectQuantity") [0].childNodes[0].nodeValue -0;
				 //  alert('quantity     ' + quantity )
	if (quantity > 0)
		{				   
			var site = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
	 // alert('site     ' + site )

						for ( var j=0 ; j < site.snapshotLength; j++ )   
							{   
								  //alert('j is equal to     ' + j )
						   var siteSnapshot =   site.snapshotItem(j);
								//alert('siteSnapshot     ' + siteSnapshot )		   
								 
							var idSnapshot = buildInstance.evaluate("hl7-org_v3:id", siteSnapshot, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE , null).singleNodeValue.getAttributeNode("extension").nodeValue;	
								   // alert('idSnapshot     ' + idSnapshot )

												  //alert(SelectedSite +' == ' + idSnapshot)
									if ( SelectedSite == idSnapshot)   
											{
														// alert('site Found');
														// alert('index is    '  + j)
														var subjectID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultsProduct/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectProduct/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;		
	alert('subjectID        '    + subjectID)	
										var index = j;
										for ( var i=0 ; i < quantity; i++ )   
														{   

														
														var newSubjectID = subjectID + '_' + i
													//alert('newSubjectID        '    + newSubjectID)	
														
													var resetID = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultsProduct/hl7-org_v3:subject1/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectProduct/hl7-org_v3:id", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
													
															resetID.setAttribute("extension", newSubjectID) ;

														
												 var subElement = subjectsInstance.evaluate("/hl7-org_v3:data/hl7-org_v3:defaultsProduct/hl7-org_v3:subject1", subjectsInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
												//alert('subElement    ' + subElement )	
												 
												 var subjectElement = subElement.singleNodeValue.cloneNode(true);
													//alert('subjectElement    ' + subjectElement );	
										
												var parElement = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	  
												var parentElement = parElement.snapshotItem(index);
												 //alert('parentElement    ' + parentElement );
												 
												var refElement = buildInstance.evaluate("hl7-org_v3:location", parentElement, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
												var referenceElement = refElement.singleNodeValue;	
													 // alert('referenceElement    ' + referenceElement );
															//	alert('i equals    ' + i );
																	//alert('insert before location');
																		parentElement.insertBefore(subjectElement,referenceElement);	
																	}
														} 															 
										}  ;   			
	};	
}






function importSubjectPersonData() {

if (confirm ("Import Data? "))
	{
			var PersonIndex = scratchInstance.getElementsByTagName("SubjectPersonIndex") [0].childNodes[0].nodeValue;
			alert(PersonIndex);
			var PersonID= scratchInstance.getElementsByTagName("SubjectPersonID") [0].childNodes[0].nodeValue;
			alert(PersonID);
	};
	{
	}
  };
  
function investigatorScratch() {
alert("INVESTIGATOR SCRATCH");
}

function investigatorSelect() {
alert("INVESTIGATOR SELECT");
}

function investigatorDeselect() {
alert("DESELECT");
}








function getFirstPath() {
 var firstPath = buildInstance.evaluate("/hl7-org_v3:study", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    var path = firstPath.singleNodeValue;
    return path; 
    }


function getNodesetTemplate(repeat, section) {
     var nodeSets = templateInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:" + repeat + "/hl7-org_v3:" +  section, templateInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    return nodeSets.singleNodeValue.cloneNode(true);
}




    
 function countChildElements(child)

{
var componentcount = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:"+child , buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
return componentcount.snapshotLength;
}



function countSiteChildElements(child, index)
{
// alert('countSiteChildElements');
// alert(index);
// alert(child);
     var sitePath = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var path = sitePath.snapshotItem(index);
// alert('path    ' + path);
 
var childCount= path.getElementsByTagName(child);
// alert('childCount        '  + childCount.length);
return childCount.length;
}
    
    
function countInvestigatorChildElements(child, index)
{
 //alert('countInvestigatorChildElements');
 //alert(index);
//alert(child);
     var sitePath = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer/hl7-org_v3:investigator", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var path = sitePath.snapshotItem(index);
// alert('path    ' + path);
 
var childCount= path.getElementsByTagName(child);
// alert('childCount        '  + childCount.length);
return childCount.length;
}
    
    
    
    
function nsResolver(prefix) {
    var ns = {
        'xhtml' : 'http://www.w3.org/1999/xhtml',
        'hl7-org_v3' : 'urn:hl7-org:v3'
    };
    return ns[prefix] || null;
}

    








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

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

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


function setSaveInstance() {
    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 setExistingInstanceFileName() {
alert('setExistingInstanceFileName')
 var saveFilenameExisting = scratchInstance.getElementsByTagName("loadFilename")  [0].textContent;
 alert(saveFilenameExisting)
 saveFilenameExisting =  'C:\xforms\StudyParticipation\cell_template.xml'
  alert(saveFilenameExisting)
scratchInstance.getElementsByTagName("loadFilenameExisting")  [0].textContent = saveFilenameExisting ;
   var check = scratchInstance.getElementsByTagName("loadFilenameExisting") [0].textContent;
     alert('check   '  +  check)
}



function setExistingInstance() {
    var saveFilenameExisting = scratchInstance.getElementsByTagName("loadFilenameExisting") [0];
 alert('IN setExistingInstance    saveFilenameExisting   ' + saveFilenameExisting)
    document.getElementById("save_existing") .setAttribute("action", "file:///" + (saveFilenameExisting.textContent));

}




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


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


function studyIdentifierExist() {
var subjectExist = 'false'

subjectExist = buildInstance.evaluate("/hl7-org_v3:study[hl7-org_v3:component1/hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subject1]", buildInstance, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;	
	if( subjectExist == false)
	{
		scratchInstance.getElementsByTagName("SDFileOpened") [0].childNodes[0].nodeValue = 'No';	
	}
	else
	{
		scratchInstance.getElementsByTagName("SDFileOpened") [0].childNodes[0].nodeValue = 'Yes';	
	}
}


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


function importStudyData() {
	// Get Study ID Root and Extension from Design
		var studyID = sdInstance.evaluate("/hl7-org_v3:plannedStudy/hl7-org_v3:id", sdInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		//alert('studyID   '   + studyID)
		if ( studyID != null)
		{	
		var rootID = studyID.getAttributeNode("root").nodeValue;
		var extensionID = studyID.getAttributeNode("extension").nodeValue;
		var SPstudyID = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:instantiation/hl7-org_v3:plannedStudy/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
		var spProtocolID = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		


			if((studyID.getAttributeNode("root").nodeValue == SPstudyID.getAttributeNode("root").nodeValue) && SPstudyID.getAttribute('root') != '' )
			{
			// Set Study ID Root and Extension in Particpation
				SPstudyID.setAttribute("root", rootID);	
				SPstudyID.setAttribute("extension", extensionID);	
					if(spProtocolID.getAttributeNode("extension").nodeValue == '' )
					{
					spProtocolID.setAttribute("extension", extensionID);
					}
				}
			else if (SPstudyID.getAttribute('root') == '')
			{
				// Set Study ID Root and Extension in Particpation
				SPstudyID.setAttribute("root", rootID);	
				SPstudyID.setAttribute("extension", extensionID);	
									if(spProtocolID.getAttributeNode("extension").nodeValue == '' )
					{
					spProtocolID.setAttribute("extension", extensionID);
					}
			}
			else
			{
				alert('The Study Design Message being imported does not match the identifier below.  Please confirm that the correct file is being imported and remove the Study Design Identifier below if it is incorrect.') 
				return;
			}
				
				//Check Type of Study
				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
										{
										}
								}
			if (confirm ("Do you wish to import Planned Sites and Planned Subjects from the Study Design Message? "))
					{	
					var subjectCounter = 1
						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 element = 'false'
						var returnedSubjectCounter = importStudyMessageData(studyComponent1s, element, subjectCounter, rootID)
						 
						var studySubComponent1s = 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", sdInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var element = 'true'
						 importStudyMessageData(studySubComponent1s, element, returnedSubjectCounter, rootID)
						
			//remove Arms from subject IDs			
		var nodesSnapshot = buildInstance.evaluate("//hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
				for ( var idCount=0 ; idCount < nodesSnapshot.snapshotLength; idCount++ )
				{
				var myVar = nodesSnapshot.snapshotItem(idCount).getAttributeNode("extension").nodeValue;
				var subject =	myVar.split('______')
				var selectedSubject = subject[0]
				nodesSnapshot.snapshotItem(idCount).setAttribute("extension", selectedSubject) ;
				}			
				

				
				//Reset EU IDS
				var nodesSnapshot = buildInstance.evaluate("//hl7-org_v3:experimentalUnit/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
				for ( var euIDCount=0 ; euIDCount < nodesSnapshot.snapshotLength; euIDCount++ )
						{
						var myVarID = nodesSnapshot.snapshotItem(euIDCount).getAttributeNode("extension").nodeValue;
						var subject =	myVarID.split('//////')	
						  var studyAndSite  =    subject[0]  + subject[1] 
						var subject2 =	studyAndSite.split('__zzzzzz')	
						var finalSubjectID = subject2[0] + subject2[1]
						var newEUID =  finalSubjectID
						if (subject2[1] != undefined)
							{
							nodesSnapshot.snapshotItem(euIDCount).setAttribute("extension", newEUID) ;
							}
						 }
					
					
				//remove Arms from subject IDs			
				var nodesSnapshot = buildInstance.evaluate("//hl7-org_v3:subjectPerson/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
						for ( var idCount=0 ; idCount < nodesSnapshot.snapshotLength; idCount++ )
						{
						var myVar = nodesSnapshot.snapshotItem(idCount).getAttributeNode("extension").nodeValue;
						var subject =	myVar.split('______')
						var selectedSubject = subject[0]
						nodesSnapshot.snapshotItem(idCount).setAttribute("extension", selectedSubject) ;
						}									
						 
					}
			else
						{
						}
		}
		
		else
			{
			alert('Please open a valid Study Design message.');	
				scratchInstance.getElementsByTagName("SDFileOpened")[0].childNodes[0].nodeValue = 'No';	
							var valueOfSD =  scratchInstance.getElementsByTagName("SDFileOpened") [0].childNodes[0].nodeValue;	
			}
			
};


	
	function importStudyMessageData(studyComponent1s, element, subjectCounter, rootID)
	{
			// Get Study ID Sites and Subjects from Design		
			// Loop through Component1s
				for ( var i=0 ; i < studyComponent1s.snapshotLength; i++ )
				{
					var studyComponent1 = studyComponent1s.snapshotItem(i);
					var studyCellSubjects = 0			
					var studyCellArm = ""
					var studyCellLocationCode = ""
					var studyCellLocationExtID = ""
					var studyCellLocationNodes = ""
					var studyCellLocation = ""
					var studyCellLocationPlaceNodes = ""
					var studyCellPlaceExtID = ""
					var studyCellProviderExtID = ""
					var studyCellProviderCode = ""
									
							// All TPEDs for Component1
						var studyCellTPEDs = sdInstance.evaluate("hl7-org_v3:timePointEventDefinition", studyComponent1, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						for ( var j=0 ; j < studyCellTPEDs.snapshotLength; j++ )
							{
								var studyCellTPED = studyCellTPEDs.snapshotItem(j);
	
							try{
								// Study Site Location 
								var studyCellLocation = sdInstance.evaluate("hl7-org_v3:location", studyCellTPED, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
										// alert('Study Cell location '  +   studyCellLocation)
							}
							catch(err)	{ }		
							
							   // Study Site Location Information
							try{	   
							var studyCellLocationNodes = sdInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location", studyCellLocation, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue;				   
						
									var studyCellLocationExtID = sdInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:id", studyCellLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;

									var studyCellLocationCode = sdInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:code", studyCellLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("code").nodeValue;	
											//	alert(' The  study Cell Location Code    ' + studyCellLocationCode)	

								}
								catch(err)	{ }		
								
									//	alert('Check Location ID and Code')				
								if( studyCellLocationExtID == "" && studyCellLocationCode == "")
								{
									//alert('No Location ID or Code is Defined')				
									studyCellLocationNodes = "false"		 
									// alert('Does a location id or code exist?   ' + studyCellLocationNodes)		
								}
								
						  //Study Location Place Kind		
						  	try
							{
								var studyCellLocationPlaceNodes = sdInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity", studyCellLocation, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;	
								var studyCellPlaceExtID = sdInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity/hl7-org_v3:locatedPlaceKind/hl7-org_v3:id", studyCellLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;

									var studyCellPlaceCode = sdInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity/hl7-org_v3:locatedPlaceKind/hl7-org_v3:code", studyCellLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("code").nodeValue;	
									//		alert(' The  study Cell Place Code    ' + studyCellPlaceCode)	
								}
							catch(err)	{ }		
								//alert('Check Place ID and Code')				
								if( (studyCellPlaceExtID == "" && studyCellPlaceCode == "")  || studyCellLocationNodes == "false")
								{
									//alert('No Place ID or Code is Defined')				
									studyCellLocationPlaceNodes = "false"	
										//	alert('Does a PLACE id or code exist?   ' + studyCellLocationPlaceNodes)				
								}	
								
								
								
								//Study Service Provider (Site Id)
								try{
								var studyCellServiceProviderNodes = sdInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:serviceProviderOrganization", studyCellLocation, nsResolver, XPathResult.BOOLEAN_TYPE, null).booleanValue  ;
									var studyCellServiceProvider = sdInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:serviceProviderOrganization/hl7-org_v3:id", studyCellLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
																					
										var studyCellProviderExtID =	studyCellServiceProvider.getAttributeNode("extension").nodeValue;
												//alert('The Study Cell Provider ID is    ' + studyCellProviderExtID)
											
										var studyCellProviderCode = sdInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:serviceProviderOrganization/hl7-org_v3:code", studyCellLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("code").nodeValue;	
												// alert('The Study Cell Provider Code    ' + studyCellProviderCode)		
										}
									catch(err)	{ }							

								
									//Study Cell Arm
									if (element == 'true')
									{
										//alert('this is an element, need to load subjects from cell level')
										try{
										var studyCellArm = sdInstance.evaluate("../../hl7-org_v3:componentOf2/hl7-org_v3:armStub/hl7-org_v3:id", studyCellTPED, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
												 }
											catch(err)	{ }											
									}
									else{
										try{
										var studyCellArm = sdInstance.evaluate("hl7-org_v3:componentOf2/hl7-org_v3:armStub/hl7-org_v3:id", studyCellTPED, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
												 }
											catch(err)	{ }		
									}
				
	if ( studyCellLocation != null)
	{
							// Particpation Message Sites
								var allComponent1s = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
								var countComponent1 = allComponent1s.snapshotLength;
										// alert('count of Component1s in participation message         ' + countComponent1)
										var foundIndex = '0'
										var foundMatch = 'No'
										for ( var m=0 ; m < allComponent1s.snapshotLength; m++ )
											{
												// alert(' IN THE PARTICIPATION MESSAGE loop')
												var component1Snapshot = allComponent1s.snapshotItem(m);
												var participationSite = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:id", component1Snapshot, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
											
												var particpationLocationExtID =	participationSite.getAttributeNode("extension").nodeValue;
															// alert( studyCellProviderExtID + '  =   '  + particpationLocationExtID)
															if ( studyCellProviderExtID == particpationLocationExtID)	
																{
																	var foundIndex = m;
																	foundMatch = 'Yes'
																	 //alert(' Found Match In Particpation Message, Dont add site. Check to see if new location or new subjects  '  + foundIndex  );
																	
																	//Check Locations
																	//Participation Locations
																			var participationLocations= buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location", component1Snapshot, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
																			
																		var locsMatch = 'No'	
																		for ( var partLocs=0 ; partLocs < participationLocations.snapshotLength; partLocs++ )
																				{
																						var studyCellLocationsSnapshot = participationLocations.snapshotItem(partLocs);
																						var partLocationID = buildInstance.evaluate("hl7-org_v3:id", studyCellLocationsSnapshot, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
																	
																			// alert( partLocationID + '  =   '  + studyCellLocationExtID)
																			if ( partLocationID == studyCellLocationExtID)	
																				{	
																				var locsMatch = 'Yes'	
																						//	alert(' Same Locations')
																						var foundLocationIndex = partLocs
																				try{
																				var participationLocationPlace= buildInstance.evaluate("hl7-org_v3:locatedEntity/hl7-org_v3:locatedPlace", studyCellLocationsSnapshot, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
																				var partLocationPlaceID = buildInstance.evaluate("hl7-org_v3:id", participationLocationPlace, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
																				}
																						catch(err)	{ }		

																				if (studyCellLocationPlaceNodes != false)
																				{
																				
																							 scratchInstance.getElementsByTagName("Location") [0].childNodes[0].nodeValue = foundLocationIndex+1;
																										//	alert('ADD NEW PLACE')
																										addNewPlaceInSite('YES', studyCellPlaceExtID)
																							
																										var selectNewSite = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
																											// alert('newSite  '  +   newSite);
																										var newSite = selectNewSite.snapshotItem(m);
								
																										var selectNewLocation = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location", newSite, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
																										var newLocation = selectNewLocation.snapshotItem(foundLocationIndex);
																											//	alert('NEW LOCATION  ' + newLocation)
								
																								//	var newLocationPlace = buildInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity/hl7-org_v3:locatedPlace/hl7-org_v3:id", newLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
																												//alert('NEW LOCATION PLACE  ' + newLocationPlace)
																											//newLocationPlace.setAttribute("extension", studyCellPlaceExtID) 			
																							
																									var newLocationPlaceCode = buildInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity/hl7-org_v3:locatedPlace/hl7-org_v3:code", newLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
																									newLocationPlaceCode.setAttribute("code", studyCellPlaceCode) 			
																			 }
																				}
																		}; //end Location check Loop					

																			if ( locsMatch == 'No' && studyCellLocationNodes != 'false')	
																			{
																			// alert(' No matching Location. Insert New location.')
																			 var lastLocation = participationLocations.snapshotLength;
																			    // alert('lastLocation     ' + lastLocation)
																				//alert('Value of Last Location  ' + lastLocation)
																					scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue = foundIndex+1
																			addNewSiteLocation()
																			
																			var selectNewSite = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
																																						var newSite = selectNewSite.snapshotItem(m);			
																			// alert('newSite  '  +   newSite);
																				
																			var newLocation = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:id", newSite, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
																			var newLocationID = newLocation.snapshotItem(lastLocation);
																				// alert('new location  '  +   newLocationID);
																						newLocationID.setAttribute("extension", studyCellLocationExtID) 			
																		
																			var newLocationCode = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:code", newSite, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
																				var newLocation_Code = newLocationCode.snapshotItem(lastLocation);
																						// alert('new location  code '  +   newLocation_Code);
																				newLocation_Code.setAttribute("code", studyCellLocationCode) 	
																			 
																		 scratchInstance.getElementsByTagName("Location") [0].childNodes[0].nodeValue = lastLocation+1;
																																			 
																		 
																		 if(studyCellLocationPlaceNodes != false)
																				{
				
																				addNewPlaceInSite('YES', studyCellPlaceExtID)
																	
																				var selectNewSite = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
																					//alert('newSite  '  +   newSite);
																				var newSite = selectNewSite.snapshotItem(m);
		
																				var selectNewLocation = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location", newSite, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
																				var newLocation = selectNewLocation.snapshotItem(lastLocation);
																						//alert('NEW LOCATION  ' + newLocation)
		
																		//	var newLocationPlace = buildInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity/hl7-org_v3:locatedPlace/hl7-org_v3:id", newLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
																				//alert('NEW LOCATION PLACE  ' + newLocationPlace)
																				//	newLocationPlace.setAttribute("extension", studyCellPlaceExtID) 			
																	
																			var newLocationPlaceCode = buildInstance.evaluate("hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity/hl7-org_v3:locatedPlace/hl7-org_v3:code", newLocation, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
																			newLocationPlaceCode.setAttribute("code", studyCellPlaceCode) 			
																			 }
																			}
																			
																	//Check Subjects		
																	//alert('Check Subjects.')
																	var participationSubjects= buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:subject1", component1Snapshot, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
																	var subjectMatch = 'No'
																	
														if ( scratchInstance.getElementsByTagName("TypeOfStudy") [0].childNodes[0].nodeValue == 'Animal_Study')
															{
															
																	for ( var partSubjects=0 ; partSubjects < participationSubjects.snapshotLength; partSubjects++ )
																	{
																	var participationSubject = participationSubjects.snapshotItem(partSubjects);
																	var checkSubjectId= buildInstance.evaluate("hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:id", participationSubject, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
																	var subject =	checkSubjectId.split('______')
																	var selectedSubject = subject[1]
								
																			if (selectedSubject == studyCellArm)
																				{
																				subjectMatch = 'Yes'
																				}
																	};
																	
																	if (subjectMatch == 'Yes')
																		{
																		//alert('Subject Already Assigned to Site')
																		}
																	else
																		{
																			//alert('Subject NOT Assigned to Site... ADD to site')
																			var subjectQuantity = 0
																			if (element == 'true')
																					{	
																					try{
																				var studyCellSubjects = sdInstance.evaluate("../../hl7-org_v3:subject/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubjectKind/hl7-org_v3:quantity", studyCellTPED, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;	
																					}
																					catch(err)	{ }		
																					}
																			else
																				{
																					try{
																				var studyCellSubjects = sdInstance.evaluate("hl7-org_v3:subject/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubjectKind/hl7-org_v3:quantity", studyCellTPED, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;	
																					}
																					catch(err)	{ }		
																				}
											// Do subjects exist anywhere in Study Participation? If so, use the same ID
														var allSubjects= buildInstance.evaluate("//hl7-org_v3:experimentalUnit", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
														var passSubject = ""
														var passSubjectEUID = ""
														var foundExistingSubject = 'No'
														var s=0 
															for ( var subjects=0 ; subjects < allSubjects.snapshotLength; subjects++ )
																	{
																	var subjectExists = 'No'
																	var checkParticipationSubject = allSubjects.snapshotItem(subjects);
																	var checkSubjectAllID= buildInstance.evaluate("hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:id", checkParticipationSubject, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
																	var checkSubjectEUID= buildInstance.evaluate("hl7-org_v3:id", checkParticipationSubject, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
																	//alert('checkSubjectAllID ' + checkSubjectAllID)
																var subjectID =	checkSubjectAllID.split('______')
																var selectedSubjectID = subjectID[1]
																
															//alert('Are these the same ?  ' +  selectedSubjectID  +' = ' + studyCellArm)
																			if (selectedSubjectID == studyCellArm)
																				{
																				//alert('Subjects exist somewhere in Study Participation, use the ID that is already there.')
																				subjectExists = 'Yes'
																				foundExistingSubject = 'Yes'																						
																				var passSubject = checkSubjectAllID
																				var passSubjectEUID = checkSubjectEUID
																				}
																				
																		if (subjectExists == 'Yes')
																		{
																				//To keep from adding subjects multple times only add as many times as there is quantity
																					if ( s < studyCellSubjects  )
																					{
																						//alert('subjects exist, reuse id       ' + passSubject + passSubjectEUID)
																						generateNonPersonSubjectsExists(passSubject, passSubjectEUID)
																						s++
																						}
																		}				
																	};
																
																		if (foundExistingSubject != 'Yes')
																		{
																			//alert('subjects do not exist add to study' + studyCellSubjects +  studyCellArm +  subjectCounter +  rootID)
																			generateNonPersonSubjects(studyCellSubjects, studyCellArm, subjectCounter, rootID)
																			var subjectQuantity = studyCellSubjects-0
																				subjectCounter = (subjectCounter +	subjectQuantity)	
																		}
																		}
																		
																}	
																
															else if ( scratchInstance.getElementsByTagName("TypeOfStudy") [0].childNodes[0].nodeValue == 'Human_Study')			
																	{	
																for ( var partSubjects=0 ; partSubjects < participationSubjects.snapshotLength; partSubjects++ )
																	{
																	var participationSubject = participationSubjects.snapshotItem(partSubjects);
																	var checkSubjectId= buildInstance.evaluate("hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPerson/hl7-org_v3:id", participationSubject, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
																	var subject =	checkSubjectId.split('______')
																	var selectedSubject = subject[1]
								
																			if (selectedSubject == studyCellArm)
																				{
																				subjectMatch = 'Yes'
																				}
																	};
																	
																	if (subjectMatch == 'Yes')
																		{
																		//alert('Subject Already Assigned to Site')
																		}
																	else
																		{
																			//alert('Subject NOT Assigned to Site... ADD to site')
																			var subjectQuantity = 0
																			if (element == 'true')
																					{	
																					try{
																				var studyCellSubjects = sdInstance.evaluate("../../hl7-org_v3:subject/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPersonKind/hl7-org_v3:quantity", studyCellTPED, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;	
																					}
																					catch(err)	{ }		
																					}
																			else
																				{
																					try{
																				var studyCellSubjects = sdInstance.evaluate("hl7-org_v3:subject/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPersonKind/hl7-org_v3:quantity", studyCellTPED, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;	
																					}
																					catch(err)	{ }		
																				}
											// Do subjects exist anywhere in Study Participation? If so, use the same ID
														var allSubjects= buildInstance.evaluate("//hl7-org_v3:experimentalUnit", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
														var passSubject = ""
														var passSubjectEUID = ""
														var foundExistingSubject = 'No'
														var s=0 
															for ( var subjects=0 ; subjects < allSubjects.snapshotLength; subjects++ )
																	{
																	var subjectExists = 'No'
																	var checkParticipationSubject = allSubjects.snapshotItem(subjects);
																	var checkSubjectAllID= buildInstance.evaluate("hl7-org_v3:subjectPerson/hl7-org_v3:id", checkParticipationSubject, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
																	var checkSubjectEUID= buildInstance.evaluate("hl7-org_v3:id", checkParticipationSubject, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	

																var subjectID =	checkSubjectAllID.split('______')
																var selectedSubjectID = subjectID[1]
																
															//alert('Are these the same ?  ' +  selectedSubjectID  +' = ' + studyCellArm)
																			if (selectedSubjectID == studyCellArm)
																				{
																				//alert('Subjects exist somewhere in Study Participation, use the ID that is already there.')
																				subjectExists = 'Yes'
																				foundExistingSubject = 'Yes'																						
																				var passSubject = checkSubjectAllID
																				var passSubjectEUID = checkSubjectEUID
																				}
																				
																		if (subjectExists == 'Yes')
																		{
																				//To keep from adding subjects multple times only add as many times as there is quantity
																					if ( s < studyCellSubjects  )
																					{
																						//alert('subjects EXIST, REUSE id       ' + passSubject +  '    ' + passSubjectEUID)
																						generatePersonSubjectsExists(passSubject, passSubjectEUID)
																						s++
																						}
																		}				
																	}
																	
																		if (foundExistingSubject != 'Yes')
																		{
																			//alert('subjects do not exist add to study' + studyCellSubjects +  studyCellArm +  subjectCounter +  rootID)
																			generatePersonSubjectsImport(studyCellSubjects, studyCellArm, subjectCounter, rootID)
																			var subjectQuantity = studyCellSubjects-0
																				subjectCounter = (subjectCounter +	subjectQuantity)	
																		}
																	}				
																}
																
															}
															else
															{
															}	
																		
																} // end if 	studyCellProviderExtID == particpationLocationExtID
												} //end for loop in Participation message
												
												
														if	(foundMatch == 'No') 
																{
																var lastNode = allComponent1s.snapshotLength
																	//alert('NO match found. Insert new site.')
																scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue = lastNode
																studyActivitiesSiteInsert()
																
																var selectNewSite = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
															    var newSite = selectNewSite.snapshotItem(lastNode);
																		// alert('New site selected  '  + newSite)
	
																var newSiteID = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:id", newSite, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
																		//	alert('New site ID selected  '  + newSiteID)
																		// alert('This should be setting the particpation id to  ' + studyCellProviderExtID  )
																		
																newSiteID.setAttribute("extension", studyCellProviderExtID) 
																
																scratchInstance.getElementsByTagName("ActivitiesSiteIndex") [0].childNodes[0].nodeValue = lastNode+1;	
												
																var selectNewSite = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
																// alert	('selectNewSite  ' + selectNewSite)
															    var newSite = selectNewSite.snapshotItem(lastNode);		
															    
															    var selectNewLocations = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location", newSite, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
															//   alert	('selectNewLocations  ' + selectNewLocations)
															    var countLocations = selectNewLocations.snapshotLength;		
														//	   alert	('countLocations  ' + countLocations)
															      
																if (studyCellLocationNodes != 'false')
																{
																try{
																var newLocation = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:id", newSite, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
															//	alert('newLocation   ' + newLocation)
																			newLocation.setAttribute("extension", studyCellLocationExtID) 	
																	}
																	catch(err)	{ }	
														
																	
																	try{
																var newLocationCode = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:code", newSite, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
													newLocationCode.setAttribute("code", studyCellLocationCode) 			
																}
																	catch(err)	{ }	
													
															if (studyCellLocationPlaceNodes != false)
																{
													 scratchInstance.getElementsByTagName("Location") [0].childNodes[0].nodeValue = 1;
															addNewPlaceInSite('YES', studyCellPlaceExtID)
															
															var selectNewSite = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:component1", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
															    var newSite = selectNewSite.snapshotItem(lastNode);

															try{
															// var newLocationPlace = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity/hl7-org_v3:locatedPlace/hl7-org_v3:id", newSite, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
																		 //	newLocationPlace.setAttribute("extension", studyCellPlaceExtID) 			
																}
																catch(err)	{ }	
																
															try{	
														var newLocationPlaceCode = buildInstance.evaluate("hl7-org_v3:studyActivitiesAtSite/hl7-org_v3:location/hl7-org_v3:serviceDeliveryLocation/hl7-org_v3:location/hl7-org_v3:locatedEntity/hl7-org_v3:locatedPlace/hl7-org_v3:code", newSite, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
													newLocationPlaceCode.setAttribute("code", studyCellPlaceCode) 		
															}
															catch(err)	{ }		
															
															}
														}
															
														 if (studyCellLocationNodes == false && countLocations == 1)
																{	
																// alert('Location does not exist in design.  Delete first location')
																var selectNewLocation = selectNewLocations.snapshotItem(0)
																// alert('selectNewLocation' + selectNewLocation)
																selectNewLocation.parentNode.removeChild(selectNewLocations.snapshotItem(0))}
						
													// Study Subjects
													if ( scratchInstance.getElementsByTagName("TypeOfStudy") [0].childNodes[0].nodeValue == 'Animal_Study')
															{
																	if (element == 'true')
																	{	
																	try{
																		var studyCellSubjects = sdInstance.evaluate("../../hl7-org_v3:subject/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubjectKind/hl7-org_v3:quantity", studyCellTPED, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;
																	}
																	catch(err)	{ }			
																	}
															else
																{
																	try{
																		var studyCellSubjects = sdInstance.evaluate("hl7-org_v3:subject/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectNonPersonLivingSubjectKind/hl7-org_v3:quantity", studyCellTPED, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;
																	}			
																	catch(err)	{ }										
																}

														// Do subjects exist anywhere in Study Participation? If so, use the same ID
														var allSubjects= buildInstance.evaluate("//hl7-org_v3:experimentalUnit", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
														var passSubject = ""
														var passSubjectEUID = ""
														var foundExistingSubject = 'No'
														var s = 0
															for ( var subjects=0 ; subjects < allSubjects.snapshotLength; subjects++ )
																	{
																	var subjectExists = 'No'
																	var checkParticipationSubject = allSubjects.snapshotItem(subjects);
																	var checkSubjectAllID= buildInstance.evaluate("hl7-org_v3:subjectNonPersonLivingSubject/hl7-org_v3:id", checkParticipationSubject, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
																	var checkSubjectEUID= buildInstance.evaluate("hl7-org_v3:id", checkParticipationSubject, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
																	//alert('checkSubjectAllID ' + checkSubjectAllID)
																var subjectID =	checkSubjectAllID.split('______')
																var selectedSubjectID = subjectID[1]
																
															//alert('Are these the same ?  ' +  selectedSubjectID  +' = ' + studyCellArm)
																			if (selectedSubjectID == studyCellArm)
																				{
																				//alert('Subjects exist somewhere in Study Participation, use the ID that is already there.')
																				subjectExists = 'Yes'
																				foundExistingSubject = 'Yes'																						
																				var passSubject = checkSubjectAllID
																				var passSubjectEUID = checkSubjectEUID
																				}
																				
																		if (subjectExists == 'Yes')
																		{
																				//To keep from adding subjects multple times only add as many times as there is quantity
																					if ( s < studyCellSubjects )
																					{
																						//alert('subjects exist, reuse id       ' + passSubject + passSubjectEUID)
																						generateNonPersonSubjectsExists(passSubject, passSubjectEUID)
																						s++ 
																						}
																		}				
																	};
																
																		if (foundExistingSubject != 'Yes')
																		{
																			//alert('subjects do not exist add to study' + studyCellSubjects +  studyCellArm +  subjectCounter +  rootID)
																			generateNonPersonSubjects(studyCellSubjects, studyCellArm, subjectCounter, rootID)
																			var subjectQuantity = studyCellSubjects-0
																				subjectCounter = (subjectCounter +	subjectQuantity)	
																		}
															}
														else if ( scratchInstance.getElementsByTagName("TypeOfStudy") [0].childNodes[0].nodeValue == 'Human_Study')
														{
													if (element == 'true')
												{	
												try{
													var studyCellSubjects = sdInstance.evaluate("../../hl7-org_v3:subject/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPersonKind/hl7-org_v3:quantity", studyCellTPED, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;
												}
												catch(err)	{ }			
												}
										else
											{
												try{
													var studyCellSubjects = sdInstance.evaluate("hl7-org_v3:subject/hl7-org_v3:experimentalUnit/hl7-org_v3:subjectPersonKind/hl7-org_v3:quantity", studyCellTPED, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("value").nodeValue;
												}			
												catch(err)	{ }							
											}
														// Do subjects exist anywhere in Study Participation? If so, use the same ID
														var allSubjects= buildInstance.evaluate("//hl7-org_v3:experimentalUnit", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
														var passSubject = ""
														var passSubjectEUID = ""
														var foundExistingSubject = 'No'
														var s = 0
															for ( var subjects=0 ; subjects < allSubjects.snapshotLength; subjects++ )
																	{
																	var subjectExists = 'No'
																	var checkParticipationSubject = allSubjects.snapshotItem(subjects);
																	var checkSubjectAllID= buildInstance.evaluate("hl7-org_v3:subjectPerson/hl7-org_v3:id", checkParticipationSubject, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
																	var checkSubjectEUID= buildInstance.evaluate("hl7-org_v3:id", checkParticipationSubject, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
																	//alert('checkSubjectAllID ' + checkSubjectAllID)
																var subjectID =	checkSubjectAllID.split('______')
																var selectedSubjectID = subjectID[1]
																
															// alert('Are these the same ?  ' +  selectedSubjectID  +' = ' + studyCellArm)
																			if (selectedSubjectID == studyCellArm)
																				{
																				//alert('Subjects exist somewhere in Study Participation, use the ID that is already there.')
																				subjectExists = 'Yes'
																				foundExistingSubject = 'Yes'																						
																				var passSubject = checkSubjectAllID
																				var passSubjectEUID = checkSubjectEUID
																				}
																				
																		if (subjectExists == 'Yes')
																		{
																				//To keep from adding subjects multple times only add as many times as there is quantity
																					if ( s < studyCellSubjects )
																					{
																						//alert('subjects exist, reuse id       ' + passSubject + passSubjectEUID)
																						generatePersonSubjectsExists(passSubject, passSubjectEUID)
																						s++ 
																						}
																		}				
																	}		

																		if (foundExistingSubject != 'Yes')
																		{
																			//alert('subjects do not exist add to study' + studyCellSubjects +  studyCellArm +  subjectCounter +  rootID)
																			generatePersonSubjectsImport(studyCellSubjects, studyCellArm, subjectCounter, rootID)
																			var subjectQuantity = studyCellSubjects-0
																				subjectCounter = (subjectCounter +	subjectQuantity)	
																		}
												
		
														}; //subjectHuman
	} // bracket for ( studyCellLocation != null)

				} 

	}
				
				scratchInstance.getElementsByTagName("SDFileOpened") [0].childNodes[0].nodeValue = 'Yes';	
											var valueOfSD =  scratchInstance.getElementsByTagName("SDFileOpened") [0].childNodes[0].nodeValue;	
				setDeaultSaveName()
		return subjectCounter;		
		}




function setRoot() {

//Removed this function when OID IDs added
setEffectiveTimeNullFlavor()
/*
var openStudyRoot = scratchInstance.evaluate("/data/studyOpenID", scratchInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue
var rootID = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:id", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("root").nodeValue;

	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);
			var counter = nodesSnapshot.snapshotLength
			//Counter used to prevent setting the Planned Study ID to the Study Particpation Root ID
			for ( var i=0 ; i < counter-1; 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) ;
			}
			}
		}
	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);
			var counter = nodesSnapshot.snapshotLength
			for ( var i=0 ; i < counter-1; i++ )
			{
			var myVar = nodesSnapshot.snapshotItem(i).getAttributeNode("root").nodeValue;
			if (myVar == "" && myVar != '1.3.6.1.4.1.519.1')
				{
			var myVar = nodesSnapshot.snapshotItem(i).getAttributeNode("root").nodeValue;
			nodesSnapshot.snapshotItem(i).setAttribute("root", rootID) ;
				}
			else
				{

				}
			}
	}
 setEffectiveTimeNullFlavor()
 */
}


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.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.removeAttribute('value','')
						}
						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('value') && effectiveTime2.getAttribute('value') == '')
				     {
				      		effectiveTime2.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.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.removeAttribute('code','')
						}
						else{
							}
		}


//Set tel for all telecoms
var allTelecoms = buildInstance.evaluate("//./hl7-org_v3:telecom[1]", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
		for(var t=0 ; t < allTelecoms.snapshotLength; t++ )   
		{
			var  telecom =  allTelecoms.snapshotItem(t)
				     if (telecom.hasAttribute('value'))
				     {
						 var telecomValue  = telecom.getAttribute('value')
						 var telecomPresent =  telecomValue.substr(0,5)
				       if (telecomPresent == 'tel:+')
							{	}	else
							{
							 var newTelecomValue =  'tel:+' + telecomValue;
							telecom.setAttribute('value',newTelecomValue)
							}			       
						}
						else{
							}
		}


//Set mailto: for all telecoms
var allTelecoms2 = buildInstance.evaluate("//hl7-org_v3:primaryPerformer/hl7-org_v3:investigator/hl7-org_v3:investigatorPerson/hl7-org_v3:telecom[2]", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
		for(var m=0 ; m < allTelecoms2.snapshotLength; m++ )   
		{
			var  telecom2 =  allTelecoms2.snapshotItem(m)
				     if (telecom2.hasAttribute('value'))
				     {
						 var telecomValue2  = telecom2.getAttribute('value')
						 var telecomPresent2 =  telecomValue2.substr(0,7)
				       if (telecomPresent2 == 'mailto:+')
							{	}	else
							{
							 var newTelecomValue2 =  'mailto:' + telecomValue2;
							telecom2.setAttribute('value',newTelecomValue2)
							}			       
						}
						else{
							}
		}

//Added 4/2012		
//Set Planned Study IDs Same as Study IDs
	var sp_sdtmID = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:id[@root='2.16.840.1.113883.4.548.2']", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
	var sd_sdtmID = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:instantiation/hl7-org_v3:plannedStudy/hl7-org_v3:id[@root='2.16.840.1.113883.4.548.2']", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
		sd_sdtmID.setAttribute("extension", sp_sdtmID) ;
	
	var sp_nctID = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:id[@root='2.16.840.1.113883.1077']", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;	
    var sd_nctID = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:instantiation/hl7-org_v3:plannedStudy/hl7-org_v3:id[@root='2.16.840.1.113883.1077']", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  if (sp_nctID	!= '')
   {
	
		sd_nctID.setAttribute("extension", sp_nctID) ;
	}
	else
	{
	var sp_nctID_element = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:id[@root='2.16.840.1.113883.1077']", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;	
		sp_nctID_element.removeAttribute('extension','')
		sd_nctID.removeAttribute('extension','')

	}


// Added 4/2012 IDs with DUNS, remove extension
			var idsSnapshot = buildInstance.evaluate("//hl7-org_v3:id[@root='1.3.6.1.4.1.519.1']", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
			for ( var i=0 ; i < idsSnapshot.snapshotLength; i++ )
			{

			var extVal = idsSnapshot.snapshotItem(i).getAttributeNode("extension").nodeValue;
			var dunsID = idsSnapshot.snapshotItem(i);

				if (extVal ==  '')
				{
				dunsID.removeAttribute('extension');
				}
				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('value'))
				     {
				       
										}
						else{
						  effectiveTimeLow.setAttribute('value','')
							}
				

				var effectiveTimeHigh = buildInstance.evaluate("hl7-org_v3:high", effectiveTime, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
				     if (effectiveTimeHigh.hasAttribute('value'))
				     {
				        }
						else{
						 effectiveTimeHigh.setAttribute('value','')
							}
			}
			
	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('value'))
				     {
				        
						}
						else{
						 effectiveTime2.setAttribute('value','')
							}		
			}
			
		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'))
				     {
				       
										}
						else{
						  effectiveTime3.setAttribute('value','')
							}		
			}
					
	//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'))
				     {
						}
						else{
						statusCode.setAttribute('code','')
							}
		}		

//Set tel for all telecoms
var allTelecoms = buildInstance.evaluate("//./hl7-org_v3:telecom[1]", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
		for(var t=0 ; t < allTelecoms.snapshotLength; t++ )   
		{
			var  telecom =  allTelecoms.snapshotItem(t)
				     if (telecom.hasAttribute('value'))
				     {
						 var telecomValue  = telecom.getAttribute('value')
						 var newTelecomValue =  telecomValue.substr(5,50)
						telecom.setAttribute('value',newTelecomValue)
							       
						}
						else{
							}
		}


//Set mailto: for all telecoms
var allTelecoms2 = buildInstance.evaluate("//hl7-org_v3:primaryPerformer/hl7-org_v3:investigator/hl7-org_v3:investigatorPerson/hl7-org_v3:telecom[2]", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
		for(var m=0 ; m < allTelecoms2.snapshotLength; m++ )   
		{
			var  telecom2 =  allTelecoms2.snapshotItem(m)
				     if (telecom2.hasAttribute('value'))
				     {
						 var telecomValue2  = telecom2.getAttribute('value')
						 var newTelecomValue2 =  telecomValue2.substr(7,100)
						telecom2.setAttribute('value',newTelecomValue2)       
						}
						else{
							}
		}


// Added 4/2012 Add extension for Study IDs if not present

	var sd_sdtmID = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:id[@root='2.16.840.1.113883.1077']", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;		
    var sd_nctID = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:instantiation/hl7-org_v3:plannedStudy/hl7-org_v3:id[@root='2.16.840.1.113883.1077']", buildInstance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		
   if (sd_sdtmID.hasAttribute('extension'))
	  {
	  }
	  else
	  {
			sd_sdtmID.setAttribute('extension','')       	  
	  }
	  
	  
// Added 4/2012 Add extension for DUNS numbers
			var idsSnapshot = buildInstance.evaluate("//hl7-org_v3:id[@root='1.3.6.1.4.1.519.1']", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
			for ( var i=0 ; i < idsSnapshot.snapshotLength; i++ )
			{
	
			   if (idsSnapshot.snapshotItem(i).hasAttribute('extension')== true)
				  {
				  }
				  else
				  {
						idsSnapshot.snapshotItem(i).setAttribute('extension','')       	  
				  }
			 }
	  
	  
	  
	  
	  
	  
}






function viewStylesheet()
{
  var mainDocument = document.implementation.createDocument("", "stylesheetdisplay", null);
  var fragment= studyParticipationProcessor.transformToFragment(buildInstance, mainDocument);
var thisNode = document.getElementById("stylesheet1572");

    if (thisNode.childNodes.length == 0) 
    {

        thisNode.appendChild(html);
        
    } 
    else 
		{
			thisNode.replaceChild(fragment, thisNode.firstChild);
		}

}


function viewPrintableStylesheet()
{
    
    var mainDocument = document.implementation.createDocument("", "stylesheetdisplay", null);
    var fragment= studyParticipationProcessor.transformToFragment(buildInstance, mainDocument);
    var thisNode = document.getElementById("stylesheet1572");
    
    if (thisNode.childNodes.length == 0) 
    {
        thisNode.appendChild(html);
    } 
    else 
    {
	thisNode.replaceChild(fragment, thisNode.firstChild);
    }
    
    
    var url =  'file://' + scratchInstance.getElementsByTagName("loadFilename") [0].childNodes[0].nodeValue;	
    var printContent = document.getElementById("stylesheet1572");

    var printContent = document.getElementById("stylesheet1572");
    var windowUrl = 'about:blank';
    var uniqueName = new Date();
    var windowName = 'Print' + uniqueName.getTime();
    
    var printWindow = window.open(windowUrl, windowName, 'left=50000,top=50000,width=0,height=0');
    
    printWindow.document.write(printContent.innerHTML);
    printWindow.document.close();
    printWindow.alert('Click OK to choose a printer.');
    printWindow.focus();
 printWindow.print();
    printWindow.close();
    
//    var 1572print = window.open (url,'1572win');
 //   1572print.document.write(
    
    


}

function createStyleSheetInstance()
{
	var selectedInvestigator =  scratchInstance.getElementsByTagName("form1572Investigator") [0].childNodes[0].nodeValue;	
	var allInvestigators = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer", buildInstance, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null);
	
	// Empty the preview1572Instance 
	var preview1572Instance = model.getInstanceDocument("1572_instance");
	var study = preview1572Instance.getElementsByTagName("study")[0];  
			if ( study.hasChildNodes() )
			{
				while ( study.childNodes.length >= 1 )
				{
					study.removeChild(study.firstChild );       
				} 
			}

	// Insert path
	var thisPath =  preview1572Instance.evaluate("/hl7-org_v3:study", preview1572Instance, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
	
	// Find the selected investigator in the Build Instance and add to the preview1572Instance
		for ( var i=0 ; i < allInvestigators.snapshotLength; i++ )
				{
						var investigator = allInvestigators.snapshotItem(i)
						var nodesSnapshot = buildInstance.evaluate("hl7-org_v3:investigator/hl7-org_v3:id", investigator, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.getAttributeNode("extension").nodeValue;
						
						if(selectedInvestigator == nodesSnapshot)
						{
							var thisInvestigator =	investigator.cloneNode(true);
							 thisPath.appendChild(thisInvestigator);
						}
					
				}
}


function S4() 
{    return (((1+Math.random())*0x10000)|0).toString(16).substring(1); } 

function guid() 
{    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); } 



function investigatorDoc(){

 var investigatorDocPath = scratchInstance.getElementsByTagName("investigatorDoc") [0].childNodes[0].nodeValue
 var investigatorDoc = investigatorDocPath.replace(/^.*[\\\/]/, '') 
 var index = scratchInstance.getElementsByTagName("PrimaryPerformerIndex") [0].textContent - 1;
 var NewDocument = getNodesetTemplate("addDocument", "subjectOf");
  
 var primaryPerformerSnapshot = buildInstance.evaluate("/hl7-org_v3:study/hl7-org_v3:primaryPerformer/hl7-org_v3:investigator", buildInstance, nsResolver,  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    
 var primaryPerformer = primaryPerformerSnapshot.snapshotItem(index);      	  
 primaryPerformer.appendChild(NewDocument);
      	        	
 var documentNode = buildInstance.evaluate("hl7-org_v3:subjectOf/hl7-org_v3:document/hl7-org_v3:text/hl7-org_v3:reference", primaryPerformer, nsResolver,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
      
documentNode.setAttribute("value", investigatorDoc) ;
	};

