var editable = false;

//
// Start loading data: create-new-project
$(function() {
	var urlvars = getUrlVars();
	
//TODO: need to fix these parameters -- not sure if we want to use requestId or activityId or what?	
	requestId = parseInt(urlvars['rid'], 10); // get the rid from the url param list, which is the requestId 
	activityId = parseInt(urlvars['id'], 10); // get the id from the url param list, which is the activityId 

	var activityIdMap = {"activityId":activityId};
	var requestIdMap = {"requestId":requestId};
	var userIdMap = {"userId":userId};

	$( "#dateOfBirth" ).datepicker().on('changeDate',function(){$(this).datepicker('hide');});
	$( "#irbExpDate" ).datepicker().on('changeDate',function(){$(this).datepicker('hide');});

	//alert("activityId = " + activityId + ", requestId = " + requestId);
		
	//variables for the findPersons ajax call	
	var selectedPersonName = "";
	var selectedPersonUsername = X";
		
	// need to know where we are for Save Draft to work	
	var currSaveIndex = 0;	//starting at the 1st page of the wizard	
	updateSaveDraftMethod(-1, 0);

	// grab setup info from server
	$.ajax({
		url:'../dart/setup.json',
		type:'GET',
		async:false,
		contentType:'application/json',
		dataType:'json',
		success:function(data,textStatus,three) {
			if(textStatus==="success"){
				$('header a.active').html(data.userFullName);
				userId = data.userId;
				userIdMap['userId'] = data.userId;
				progressIncrease('60%');
			}

		}
	});

	//
	// submitting the request
	$('div.tab-study-name').on('click', 'a#submit', function(e) {
		e.preventDefault();
		$(this).hide();
		$('.submitTheRequest .progress').show();
		var submitRequest = function(){
			$.ajax({
				url:'../dart/submitRequest.json',
				type:'POST',
				async:false,
				contentType:'application/json',
				dataType:'json',
				data:JSON.stringify(requestIdMap),
				success:function(data,textStatus,three) {
					window.location = "dashboard.html#newrequest";
				}
			});
		}
		//short delay to allow UI (.progress) to catch up before submitting (IE bug fix)
		window.setTimeout(submitRequest, 100);
	}); 

	
	
	// populate the user request info
	$.ajax({
		url:'../dart/getActivityInfo.json',
		type:'POST',
		contentType:'application/json',
		async:false,
		dataType:'json',
		data:JSON.stringify(requestIdMap),
		success:function(data,textStatus,three) {
			$('div.tab-study-name').attr('tracking-num-content',data.trackingNumber);
			$('div.well h6.study-name').html(data.officialName);
					
			$('form.createNewProject input#shortName').val(data.shortName);
			$('form.createNewProject input#irbNumber').val(data.iRBApprovalNumber);
			$('form.createNewProject input#irbExpDate').val(data.iRBExpirationDate);
			$('form.createNewProject input#startDate').val(data.activityStartDate);
			$('form.createNewProject input#endDate').val(data.activityEndDate);
			
			//
			// get and set the editable flag
			editable = data.editable;
			
			progressIncrease('100%');
			$('#wizard').addClass('in');
			$('#preload').fadeOut();
		}
	});
	
	// populate the user request info (display the updated tracking# if this is an amendment)
	$.ajax({
		url:'../dart/getRequest.json',
		type:'POST',
		contentType:'application/json',
		async:false,
		dataType:'json',
		data:JSON.stringify(requestIdMap),
		success:function(data,textStatus,three) {
			$('div.tab-study-name').attr('tracking-num-content',data.trackingNumber);
		}
	});	
	
	
	$("div.container a#history").click(function() {		
		document.location='./history.html?id='+activityId+'&rid='+requestId;
	});

	$("div.container a#communication").click(function() {				
		document.location='./communication.html?id='+activityId+'&rid='+requestId;
	});
	
	
	// populate location options
	$.ajax({
		url:'../dart/getAllLocations.json',
		type:'POST',
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(requestIdMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success"){
								
				// populate the combo box on the participants page
				var locationOptions = Mustache.render($(".locationOptionsTemplate").html(),data);
				$("div.participant-select-location .input-medium").append(locationOptions).chosen({no_results_text: "No locations matched"});
				
				// populate the combo box on the data sources page
				locationOptions = Mustache.render($(".projectLocationsTemplate").html(),data);
				$("form.dataSources select#location").html(locationOptions)
			}
			else {
				//TODO: error handling
			}
		}
	});
	
//testing -- try making this call synchronous? (we were occasionally not getting all of the primaryInfo
	// populate primary info data
	$.ajax({
		url:'../dart/getPrimaryInfo.json',
		type:'POST',
		contentType:'application/json',
		async:false,	
		dataType:'json',
		data:JSON.stringify(requestIdMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success"){
				primaryInfo = data;
				if(primaryInfo.locations.length>0){
					
					populateParticipantTable(primaryInfo);	//display the participant info in the table
					
					populatePrimaryInfoTable(primaryInfo);
				}
			}
		}
	});

	
	/************************* File Upload ****************/
	$('div.locationDocuments').on('click', 'a#uploadDocumentLink', function(e){
		
		//add the docid to the modal before opening it
		var docid = $(this).attr('data-id');		
		$('#uploadDocumentModal input#docid').val( docid );
	});
		
	$('div.participantDocuments').on('click', 'a#uploadDocumentLink', function(e){
		
		//add the docid to the modal before opening it
		var docid = $(this).attr('data-id');		
		$('#uploadDocumentModal input#docid').val( docid );
	});
	
	
//TODO: if we filter by file type here, the listener probably needs to be turned on first	
//	Additional Options for the UI version:  autoUpload	
//  acceptFileTypes: /(\.|\/)(pdf|docx?)$/i,
//  acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
//  previewFileTypes: /none/,	
	//file upload
    $('#uploadDocumentModal input#fileField').fileupload({
    	url:'../dart/uploadDocument.json',
    	type: 'POST',
        dataType: 'json',
        multipart: true,
        paramName: 'fileField',
//        acceptFileTypes: /(\.|\/)(pdf|docx?)$/i,
        fileInput: null,	//turn off the listener
        add: function (e, data) {
        	//alert("add @fileupload (submit)");
        	
	        $.each(data.files, function (index, file) {
	        	//alert('Selected file: ' + file.name);
	        	//alert('Selected file (type): ' + file.type);
	       
	            //
	            //verify the file type (pdf, doc, docx) -> rtf type == "application/msword"
	            var fileNamePieces = file.name.split(".");
	            var fileExt = fileNamePieces[fileNamePieces.length - 1];	//get the last .
	            //alert("fileExt = " + fileExt);
	            
	            var validFileType = true;
	            
//testing -- file.type does NOT work in IE (might want to just use the fileExt value)
	            if( (file.type != undefined && file.type !== "application/pdf" && file.type !== "application/msword" && file.type !== "application/vnd.openxmlformats-officedocument.wordprocessingml.document") ||
	            	(fileExt.toLowerCase() !== "pdf" && fileExt.toLowerCase() !== "doc" && fileExt.toLowerCase() !== "docx") ) {
	            	
	            	alert("Invalid file type.  Please select a PDF or Microsoft Word document to upload.");
	            	validFileType = false;	            	
	            }//end if

//TODO: if this is not a valid file type, don't close the modal? -> could change the modal action and just hide the modal with a valid file type	            
	            //alert("validFileType = " + validFileType);
	            if( validFileType ) {
	            	//$('#uploadDocumentModal').hide();
	            	
	            	data.submit();	//upload the file
	            }//end if
	        });
	    },	//end add
        done: function (e, data) {
        	//alert("done @fileupload");        	        	
	        //alert("data.textStatus = " + data.textStatus);	//"success" if good
        	
        	var success = false;
	        if( (data != undefined && data != null) && (data.result != undefined && data.result != null) ) {
	        	//alert("result = " + JSON.stringify(data.result));
	        	
	        	//if we got an error result, output it
	        	if( data.result.message.text !== "OK" ) {
	        		alert( data.result.message.text );
	        		success = false;
	        	} else {
	        		success = true;
	        	}
	        }

//TODO: show file upload progress?

	        if( success ) {
//TODO: might want to just refresh this document row, instead of all documents
//TODO: if we change this to only update one row at a time, we'll need to update the templates and the javascript that displays the checkmark	        	
	        	// populate the document info
	        	listDocumentsByRequest( requestId, false );
        	}//end if


//TODO: test clearing the filename in IE	        
	        //clear out the selected file
	        if((data != undefined && data != null) && (data.files != undefined && data.files != null)) {
		        data.files.splice(0, data.files.length);	//clear out the selected file (local)
	        }//end if
	        $('#uploadDocumentModal input#fileField').val("");	//this should work for Firefox?
	        $('#uploadDocumentModal input#fileField').replaceWith($(this).clone( true ));	//keep the listeners
	        
//	        function clearInput($source) {
//	            var $form = $('<form>')
//	            var $targ = $source.clone().appendTo($form)
//	            $form[0].reset()
//	            $source.replaceWith($targ)
//	        }	        
	        
//	        $('#btnAddNew').click(function(event) {
//	            $("#flIcon").replaceWith("<input type='file' id='flIcon'/>").html();
//	        });​	        
	        
        }//end done
    });

    
    //clicked the File Upload submit button
	$('div#uploadDocumentModal').on('click', 'button#submit', function(e){
		e.preventDefault();	//do not perform the form submit
		
		try {
			//alert("clicked the file upload submit button!");			
			
// Callback for the submit event of each file upload:
// submit: function (e, data) {}, // .bind('fileuploadsubmit', func);    			
			
			$('#uploadDocumentModal input#fileField').fileupload('add', {
		        fileInput: $('#uploadDocumentModal input#fileField')
		    });
			
		} catch(err) {
			//alert("Exception: " + err);
		}		
	});
    
	
	/************************* Find Persons ****************/
	//hook the findNow button on the 'Find People' (participant) modal
	$('.modal-body').on('click','button#findNow',function(e){
		e.preventDefault();

		$('div#participantModal div#resultTable .alert').hide();
		$('div#participantModal div#resultTable').addClass('hide');	//hide the results table
		
		var personToFindVal = $('div#participantModal input#name').val();				
		var personToFindMap = {"key":personToFindVal};
		
		//alert("searching for: " + JSON.stringify(personToFindMap));
		
		//search for this person in AD
		$.ajax({
			url:'../dart/findPersons.json',
			type:'POST',
			async:false,
			contentType:'application/json',
			dataType:'json',
			data:JSON.stringify(personToFindMap),
			success:function(data,textStatus,three) {
				//alert("got a response!");
				
				if(textStatus==="success"){
//					alert("success!");
					
					if(data.persons != null) {

//TODO: if there are no search results, display something on the UI
//TODO: don't add this person if their full name starts with vha? (then it isn't actually a person)						
						
						if(data.persons.length > 0) {
							$('div#participantModal div#resultTable .alert').fadeIn();	//show the instructions for selecting a participant							
						}
						
						//display the search results (currently: full name, username)
						var personSearchResults = Mustache.render($(".findPersonOptionsTemplate").html(),data);						
						$('div#participantModal table tbody').html(personSearchResults);
						
						//$('div#participantModal div#resultTable').fadeIn().removeClass('hide');	//show the results table
						$('div#participantModal div#resultTable').removeClass('hide');	//show the results table
					}//end if
				} else {
					//TODO: handle an error response
				}
			}
		});
	});
	
	
	//clicked a row in the 'Find People' results table
	$('div#participantModal table').on('click','tr', function(event){
		event.preventDefault();
		
		var selectedRow = $(this);
		
		//get the selected username
		selectedPersonName = $(this).find("td#fullName").text();
		selectedPersonUsername = X(this).find("td#username").text();

//		$('.displayTable input#participantName').val( selectedPersonName );	//display the selected name on the page
		$('.displayTable td#participantName').text( selectedPersonName );	//display the selected name on the page
		
		//
		// clear the modal of the last search info
		clearModalOfSearchResults();
	});
	
	
//	//clicked the "Choose Participant" button
//	$('.modal-footer').on('click','button#chooseParticipant',function(e){
//		event.preventDefault();
//		
////		alert("clicked the choose participant button, selectedPersonName = " + selectedPersonName);
//	});	
	
	
	//clicked the cancel button -> no participant selected
	$('.modal-footer').on('click','button#cancel',function(e){
		event.preventDefault();
		
		clearParticipantNameDisplay();	//clear the selected participant name
	});
		
	
	//Clear out the variables holding the selected person info and update the UI
	var clearParticipantNameDisplay = function(){
		
		selectedPersonName = "";
		selectedPersonUsername = X";
		
//		$('.displayTable input#participantName').val( selectedPersonName );	//display the selected name on the page		
		$('.displayTable td#participantName').text( selectedPersonName );	//display the selected name on the page
	};
	
	//clear the modal of the last search info
	var clearModalOfSearchResults = function(){
		
		//
		// hide the results list
		$('div#participantModal div#resultTable .alert').hide();
		$('div#participantModal div#resultTable').addClass('hide');	//hide the results table
		
		//
		// clear the search name box
		$('div#participantModal input#name').val( '' );	//display the selected name on the page
	};

	/******************* Checkboxes *******************/
	//if the user clicks the checkbox (in the added primaryInfo), we should update the primaryInfo for this row
	$('.displayTable').on('click','tr#newRow input[name=notify]',function(e){

		var thisRow = $(this).parents('tr');
		var locationName = thisRow.find('.location-name').text();
		var participantName = thisRow.find('.participant').text();	//participant name (display)

		var checkedVal = $(this).is(":checked");
		
//		alert("clicked the notify checkbox!, locationName = " + locationName + ", participantName = " + participantName + ", checkedVal = " + checkedVal);
//		alert("primaryInfo before = " + JSON.stringify(primaryInfo));

		//update the checkbox value for this participant (by name) 
		var investigators = primaryInfo.investigators[locationName];
		//alert("investigators = " + JSON.stringify(investigators));

		if( investigators != undefined ) {
			var participants = investigators.participants;
			//alert("participants before = " + JSON.stringify(participants));
			
			if( participants  != undefined ) {
								
				for( pIndex = 0; pIndex < participants.length; pIndex++ ) {
					
					if(participants[pIndex].name === participantName) {
						
						//alert("found it!  primaryInfo participant = " + participants[pIndex].name + ", participantName = " + participantName);
						
						participants[pIndex].checked = checkedVal;
					}//end if
				}//end for
			}//end if
			
			//alert("participants after = " + JSON.stringify(participants));			
		}//end if
		
		//alert("primaryInfo after = " + JSON.stringify(primaryInfo));
	});	


//TODO: might want to combine the body of this with the event handler for the other checkbox
	//if the user clicks the checkbox (in the added primaryInfo), we should update the primaryInfo for this row	
	$('.displayTable').on('click','tr#newRow input[name=data-access]',function(e){

		var thisRow = $(this).parents('tr');
		var locationName = thisRow.find('.location-name').text();
		var participantName = thisRow.find('.participant').text();	//participant name (display)

		var dataAccessCheckedVal = $(this).is(":checked");
		
//		alert("clicked the notify checkbox!, locationName = " + locationName + ", participantName = " + participantName + ", dataAccessCheckedVal = " + dataAccessCheckedVal);
//		alert("primaryInfo before = " + JSON.stringify(primaryInfo));

		//update the checkbox value for this participant (by name) 
		var investigators = primaryInfo.investigators[locationName];
		//alert("investigators = " + JSON.stringify(investigators));

		if( investigators != undefined ) {
			var participants = investigators.participants;
			//alert("participants before = " + JSON.stringify(participants));
			
			if( participants  != undefined ) {
								
				for( pIndex = 0; pIndex < participants.length; pIndex++ ) {
					
					if(participants[pIndex].name === participantName) {
						
						//alert("found it!  primaryInfo participant = " + participants[pIndex].name + ", participantName = " + participantName);
						
						participants[pIndex].dataAccessChecked = dataAccessCheckedVal;
					}//end if
				}//end for
			}//end if
			
			//alert("participants after = " + JSON.stringify(participants));			
		}//end if
		
		//alert("primaryInfo after = " + JSON.stringify(primaryInfo));
	});

	
	
	//Add new data row to table
	$('.displayTable').on('click','.add',function(e){
		e.preventDefault();
		
		//Add row
//		var name = $('.displayTable').find('.name').val();
		var name = selectedPersonName;
		var username = XelectedPersonUsername;

//		var location = $('.displayTable').find('.location').val();		
//		var location = $("div.participant-select-location .input-medium").val();
		var location = $("div.participant-select-location").find(".input-medium").val();
				
		
		//
		//require a person and a location before adding the participant
		if( name === "" || name === null ) {
			alert("Please select a participant.");
			return;
		}
		if( location === "" || location === null ) {
			alert("Please select a participant location.");
			return;
		}//end if
		

		//
		//only add this participant if unique for this location	
		var newLocation = false;
		var participantExists = false;
		if(getLocInfo(location) === null) {	//new location
			newLocation = true;
			participantExists = false;	//can't yet exist at a new location
		} else {
			participantExists = isParticipantUsernameAtLocation( primaryInfo.investigators[location].participants, username );			
		}//end else
		//alert("participant:  " + username + " @ " + location + ", exists = " + participantExists);
		
		
		if( !participantExists ) {	//only add a new participant

			//keeping 2 different values for the checkboxes (notifications, data access)
			var checked = "";
//			($('.displayTable').find('.notify').is(":checked")) ? checked = "checked" : checked = "";
			var checkedVal = ($('.displayTable').find('.notify').is(":checked"));
			if( checkedVal )
				checked = "checked";

			var dataAccessChecked = "";
//			($('.displayTable').find('.data-access').is(":checked")) ? dataAccessChecked = "checked" : dataAccessChecked = "";
			var dataAccessCheckedVal = ($('.displayTable').find('.data-access').is(":checked"));
			if( dataAccessCheckedVal )
				dataAccessChecked = "checked";					

			
			//
			//primary investigator defaults to both checkboxes being checked
			if( newLocation ) {
				checkedVal = true;
				checked = "checked";
				
				dataAccessCheckedVal = true;
				dataAccessChecked = "checked";					
			}//end if			

			
			
			//
			//create a row for this data and add it to the table
			createAndAddRowToDisplayTable(name, username, location, checked, dataAccessChecked);
		
			
		
			//send the new row to primaryInfo object
	//		if(getLocInfo(location)===null){	//new location
			if( newLocation ) {	//new location
				
				//if this is the only location, default to primary site
				var isPrimary = false;
				if(primaryInfo.locations.length === 0) {	
					isPrimary = true;
				}
				primaryInfo.locations.push({"primary":isPrimary,"location":location,"primaryInvestigator":name,"primaryInvestigatorUserId":username});
				primaryInfo.investigators[location] = {"participants":[{"name":name,"username":username,"checked":checkedVal,"dataAccessChecked":dataAccessCheckedVal}]};
	
				populatePrimaryInfoTable(primaryInfo);
			} else {
				
				//assumed that if it is not a new location then it can only be a new person
				primaryInfo.investigators[location].participants.push({"name":name,"username":username,"checked":checkedVal,"dataAccessChecked":dataAccessCheckedVal});
			}//end if
		}//end if
	
		
		//clear old data
//		$('.displayTable').find('.name').val("");
//		$('.displayTable').find('.location').val("").trigger('liszt:updated');
		$("div.participant-select-location").find(".input-medium").val("").trigger('liszt:updated');
		clearParticipantNameDisplay();	//clear the selected participant name
	});

	//Remove data row from table
	$('.displayTable').on('click','.delete',function(e){
		e.preventDefault();
		
		var thisRow = $(this).parents('tr');
		var location = thisRow.find('.location-name').text();
		var participant = thisRow.find('.participant').text();	//participant name (display)
		var locationData = getLocInfo(location);

		//alert("participant = " + participant);
		
		//remove name from investigator's list
		primaryInfo.investigators[location].participants = removeParticipantFromArray(participant,primaryInfo.investigators[location].participants);
//		primaryInfo.investigators[location].participants = removeFromArray(participant,primaryInfo.investigators[location].participants);

		//check if we should also remove a primary location
		if(primaryInfo.investigators[location].participants.length===0){	//no more participants at this site
			
			//are we deleting the primary site?
			var deletingPrimarySite = false;
			$.each(primaryInfo.locations,function(i,val){
				if(location === val.location && primaryInfo.locations[i].primary == true) {
					deletingPrimarySite = true;	//about to delete the primary site
				}//end if
			});
					
			delete primaryInfo.investigators[location];
			primaryInfo.locations.splice(locationData.i,1);

			//if we just deleted the primary site, set the 1st site in the list to primary
			if(deletingPrimarySite) {
				if(primaryInfo.locations.length > 0) {
					primaryInfo.locations[0].primary = true;
				}//end if
			}//end if
						
			populatePrimaryInfoTable(primaryInfo);	//update the display
			if(primaryInfo.locations.length===0){
				$('.primary-info').css('opacity',.3);
				$('.primary-info .alert').hide();
			}
		} else {
			//if we just deleted the primaryInvestigator, default to the 1st remaining participant
			if(participant===locationData.primaryInvestigator){
				var newPrimaryInvestigatorName = primaryInfo.investigators[location].participants[0].name;
				var newPrimaryInvestigatorUsername = XrimaryInfo.investigators[location].participants[0].username;
				
				primaryInfo.locations[locationData.i].primaryInvestigator = newPrimaryInvestigatorName;
				primaryInfo.locations[locationData.i].primaryInvestigatorUserId = newPrimaryInvestigatorUsername;
			
				//if we change the primary investigator, default to both checkboxes being checked (for the new primary investigator)
				updatePrimaryInvestigatorCheckboxValues( primaryInfo.investigators[location].participants, newPrimaryInvestigatorName, newPrimaryInvestigatorUsername, location );
				
				populatePrimaryInfoTable(primaryInfo);
			}
		}
		thisRow.fadeOut('fast',function(){$(this).remove();});
	});

	//Change Primary Location
	$('.primary-info').on('click','td.primary-location i',function(e){				
		var location = $(this).parents('tr').find('td.location-name').text();
		$('td.primary-location i').removeClass('icon-star').addClass('icon-star-empty');
		$(this).removeClass('icon-star-empty').addClass('icon-star');
		$.each(primaryInfo.locations,function(i,val){
			if(location === val.location){
				primaryInfo.locations[i].primary = true;
			} else {
				primaryInfo.locations[i].primary = false;
			}
		});
	});

	//Change Primary Investigator
	$('.primary-info').on('click','.edit-primary-investigator',function(e){
		e.preventDefault();
		
		var selected = $(this);
		var location = selected.parents('tr').find('td.location-name').text();
		var locationData = getLocInfo(location);
		var participants = primaryInfo.investigators[location];
		var piOptions = Mustache.render($('.piOptionsTemplate').html(),participants);	//display the participant name
		var curPI = 'option[value="'+locationData.primaryInvestigator+'"]';
		piOptions = $(piOptions).find(curPI).attr("selected",true).end();
		selected.parents('tr').find('.primary-investigator').html(piOptions).find('select').on('change',function(e){
			
			var name = $(e.target).val();
			var username = getUsername( participants.participants, name );	//get the username that corresponds to this name

			locationData.primaryInvestigator = name;
			locationData.primaryInvestigatorUserId = username;
			//alert("participant: name = " + name + ", username = X + locationData.primaryInvestigatorUserId);
			
			//if we change the primary investigator, default to both checkboxes being checked (for the new primary investigator)			
			updatePrimaryInvestigatorCheckboxValues( participants.participants, name, username, location );
			
			populatePrimaryInfoTable(primaryInfo);
		});
		$('.primary-info').on('click','.primary-investigator button.close',function(e){
			populatePrimaryInfoTable(primaryInfo);
		});
	});


	var getLocInfo = function(location){
		var locationData = null;	//default to null
		$.each(primaryInfo.locations, function(i,val){
			//alert(i + ": " + val.location);
			
			if(location === val.location){
				locationData = primaryInfo.locations[i];				
				locationData["i"] = i;
			}
		});
		return locationData;
	};

	
	// populate the data source table
	$.ajax({
		url:'../dart/getAllDataSources.json',
		type:'POST',
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(userIdMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success" ){
				var rlist = data.dataSources;
				if (rlist.length > 0) {
					var tableBody = Mustache.render($(".dataSourceRowTemplate").html(),data);
					$('form.dataSources div.dataSourcesList').html(tableBody);
					
//TODO: do we use this source name options list?
					// figure out the list of distinct data source names
					var sourceNameList = [];
					var distinctNameList = [];
					for (var i in rlist) {
						var nValue = rlist[i].name;
						if ($.inArray(nValue, distinctNameList) == -1) {
							distinctNameList.push(nValue);
							var obj = {"name":nValue};
							sourceNameList.push(obj);
						}
					}
					
					var sourceObj = {"sources":sourceNameList};
					var optionsList = Mustache.render($(".dsNameOptionTemplate").html(),sourceObj);
					$('form.dataSources select#dataSource').html(optionsList);
					
					// TODO- pass the request id, not the activitiy ID
					// populate the activity data sources info
					$.ajax({
						url:'../dart/getRequestDataSources.json',
						type:'POST',
						contentType:'application/json',
						dataType:'json',
						data:JSON.stringify(requestIdMap),
						success:function(data,textStatus,three) {
							if(textStatus==="success" ) {
								
								if (data.hipaaAuth) {
									$('form.dataSources input#HIPAAAuthorization1').attr('checked','checked');
									$('form.dataSources input#HIPAAAuthorization2').removeAttr('checked');
								}
								else {
									$('form.dataSources input#HIPAAAuthorization1').removeAttr('checked');
									$('form.dataSources input#HIPAAAuthorization2').attr('checked','checked');
								}
								
								if (data.hipaaWaiver) {
									$('form.dataSources input#HIPAAWaiver1').attr('checked','checked');
									$('form.dataSources input#HIPAAWaiver2').removeAttr('checked');
								}
								else {
									$('form.dataSources input#HIPAAWaiver1').removeAttr('checked');
									$('form.dataSources input#HIPAAWaiver2').attr('checked','checked');
								}

								if (data.localServer) {
									$('form.dataSources input.dataLocation1').removeAttr('checked');
									$('form.dataSources input.dataLocation2').attr('checked','checked');
									$('form.dataSources input.dataLocation3').val(data.localServerLocation);
								}
								else {
									$('form.dataSources input.dataLocation3').val('');
									$('form.dataSources input.dataLocation2').removeAttr('checked');
									$('form.dataSources input.dataLocation1').attr('checked','checked');
								}
								
								$('form.dataSources input#startDateData').val(data.startDate);
								$('form.dataSources input#endDateData').val(data.endDate);
								
								// geographic location
								$("form.dataSources select#location").val(data.locationName);
								
								var rlist2 = data.dataSources;
								if (rlist2.length > 0) {
									for (var i in rlist2) {
										var dsId2 = rlist2[i];										
										// find the data source row and check it's checkbox
										$('.dataSourcesList input[name='+dsId2+']').attr('checked','checked');
									}
								}
							}
						}
					});
				}
			}
		}
	});

	
	// populate the document info (trying synchronous to see if this will solve the document issues with primaryInfo)
	listDocumentsByRequest( requestId, false );	//synchronous

	
	var applyPrimaryInvestigator = function(e,pi){
	};

	
	removeFromArray = function(value, arr) {
		return $.grep(arr, function(elem, index) {
			return elem !== value;
		});
	};
 
});


//removes the participant from the investigators array, by participant name
removeParticipantFromArray = function(value, arr) {
	return $.grep(arr, function(elem, index) {
		if(elem != null && elem.name != null) {
			return elem.name !== value;
		}
		
		return null;
	});
};


populatePrimaryInfoTable = function(primaryInfo){
	var newPrimary = Mustache.render($(".newPrimaryTemplate").html(),primaryInfo);
	$('.primary-info table tbody').html(newPrimary);
	if(primaryInfo.locations.length>0){
		$('.primary-info :checked').siblings().first().removeClass('icon-star-empty').addClass('icon-star');
		$('.primary-info').css('opacity',1);
		$('.primary-info .alert').fadeIn();
	}
};


//Displays the primaryInfo participant data in the participant table
populateParticipantTable = function( primaryInfo ){
	
	if(primaryInfo != undefined && primaryInfo != null) {

		//alert("have some primaryInfo!");
		//alert("primaryInfo.locations = " + JSON.stringify(primaryInfo.locations));
		
		for (idx in primaryInfo.locations) {		
			var loc = primaryInfo.locations[idx];
			var locationName = loc.location;	//location name
			//alert("locationName = " + locationName);
			
			//alert("loc = " + JSON.stringify(loc));
			
//TODO: get the name that corresponds to this userId (don't necessarily have that info from the DB) ->  (get the fullName that corresponds to this userId)
//testing -- getting null for the name?  We should probably be storing this somewhere (we could query from ActiveDirectory if necessary)
			if(loc.primaryInvestigator === null) {
				loc.primaryInvestigator = "TEST";							
			}//end if
			
			
			var investigators = primaryInfo.investigators[locationName];
			if(investigators != undefined) {

				var participants = investigators.participants;
				if(participants != undefined) {
				
					//alert("have some participants! length = " + participants.length);
					//alert("participants: " + JSON.stringify(participants));
					
					for( var pIndex = 0; pIndex < participants.length; pIndex++ ) {
						
//TODO: get the name that corresponds to this userId (don't necessarily have that info from the DB)
//testing -- getting null for the name?  We should probably be storing this somewhere (we could query from ActiveDirectory if necessary)
						if(participants[pIndex].name === null) {
							participants[pIndex].name = "TEST";
						}
						
						//
						//create a row for this data and add it to the table
						var name = participants[pIndex].name;
						var username = Xarticipants[pIndex].username;
						var checked = (participants[pIndex].checked) ? "checked" : "";
						var dataAccessChecked = (participants[pIndex].dataAccessChecked) ? "checked" : "";
						
						createAndAddRowToDisplayTable(name, username, locationName, checked, dataAccessChecked);
					}//end for
				}//end if
			}//end for
		}//end for
	}//end if
};


//Creates a row out of the specified values and adds this new row to the participants table
createAndAddRowToDisplayTable = function(name, username, locationName, checkedVal, dataAccessCheckedVal) {
		
	var data = {
		"name":name,
		"username":username,
		"location":locationName,
		"checked":checkedVal,
		"dataAccessChecked":dataAccessCheckedVal
	};
	var newRow = Mustache.render($(".newRowTempate").html(),data);
	
//	alert("name = " + name + ", location = " + locationName + ", checked = " + checkedVal + ", dataAccessChecked = " + dataAccessCheckedVal);
//	alert("newRow = " + newRow);	
	
	$('.displayTable .controls').before(newRow);
	$('.displayTable tr.hide').fadeIn().removeClass('hide');	
};


//Returns the username that corresponds to this name (in the list of participants)
getUsername = function(participants, participantName) {
	
	if( participants != undefined ) {
		
//		alert("participants = " + JSON.stringify(participants));
		
		for( var pIndex = 0; pIndex < participants.length; pIndex++ ) {

//			alert("pIndex = " + pIndex);
//			alert("participants[pIndex].name = " + participants[pIndex].name);
			
			if(participants[pIndex].name === participantName) {	//match the participant by name
				return (participants[pIndex].username);
			}//end if
			
		}//end for
	}//end if
	
	return "";
};


//returns true if this username is found at this location
isParticipantUsernameAtLocation = function(participants, participantUsername) {
		
	if( participants != undefined ) {
		
//			alert("participants = " + JSON.stringify(participants));
		
		for( var pIndex = 0; pIndex < participants.length; pIndex++ ) {

//				alert("pIndex = " + pIndex);
//				alert("participants[pIndex].name = " + participants[pIndex].name);
			
			if(participants[pIndex].username =XX participantUsername) {	//match the participant by username
				return true;
			}//end if
			
		}//end for
	}//end if
	
	return false;
};


//the principalInvestigator defaults to notifications and data access (update the primaryInfo and the checkboxes)
updatePrimaryInvestigatorCheckboxValues = function( locationParticipants, participantName, participantUsername, locationName ) {
	
	if( locationParticipants!= null && locationParticipants != undefined ) {
		
//		alert("locationParticipants = " + JSON.stringify(locationParticipants));
		
		for( var pIndex = 0; pIndex < locationParticipants.length; pIndex++ ) {

//			alert("pIndex = " + pIndex);
//			alert("locationParticipants[pIndex].name = " + locationParticipants[pIndex].name);
			
			if(locationParticipants[pIndex].username =XX participantUsername) {	//match the participant by username

				//primaryInvestigator defaults to true on both the notifications and data access
				locationParticipants[pIndex].dataAccessChecked = true;
				locationParticipants[pIndex].checked = true;				
			}//end if
			
		}//end for
		
//		alert("updated participant info:  " + JSON.stringify(locationParticipants));
	}//end if


	//update the participants table
	$('.displayTable tr#newRow').each(function() {
		
		//find this participant at this location
		var currParticipantName = $(this).find("td.participant").text();
		var currLocationName = $(this).find("td.location-name").text();

		//alert("current row:  participant = " + currParticipantName + ", location = " + currLocationName);

		if( currParticipantName === participantName && currLocationName === locationName ) {
			//alert("Found it!");
			
			$(this).find('input[name=notify]').attr('checked','checked');	//set the checkbox value
			$(this).find('input[name=data-access]').attr('checked','checked');			
		}//end if
	});
};


//Read a page's GET URL variables and return them as an associative array.
getUrlVars = function()
{
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++)
  {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
  }
  return vars;
}


//called from the bwizard to validate page changes when next or back are clicked
wizardValidating = function(e, ui) {
	// ui.index is the index of the visible panel starting from 0
	// e is the javascript event that (eventually) caused this function all.  The event is cancellable with its returnValue property.

	//alert("index = " + ui.index + ", nextIndex = " + ui.nextIndex);		
	
	//
	//save before moving to the next/prev page
	var resultCode = saveWizardPage( ui.index );
	
	updateSaveDraftMethod(ui.index, ui.nextIndex);	//show/hide the Save Draft button and update the page index
}


////Allow the wizard panel headings to be clickable (move the page within the wizard, calls the wizardValidating function)
//$('#wizard').on('click', 'li#Information', function(e){
//	//alert("clicked the Information heading");
//	$('#wizard').bwizard("show", 0);
//});
//$('#wizard').on('click', 'li#Participants', function(e){
//	//alert("clicked the Participants heading");
//	$('#wizard').bwizard("show", 1);
//});
//$('#wizard').on('click', 'li#Data', function(e){
//	//alert("clicked the Data heading");
//	$('#wizard').bwizard("show", 2);
//});
//$('#wizard').on('click', 'li#Documents', function(e){
//	//alert("clicked the Documents heading");
//	$('#wizard').bwizard("show", 3);
//});
//$('#wizard').on('click', 'li#Submit', function(e){
//	//alert("clicked the Submit heading");
//
//	$('#wizard').bwizard("show", 4);
//});


// as bwizard does not provide a built-in function to track "where" in the wizard we are, or from which direction we're getting there
// we need to manually identify and maintain these values...
updateSaveDraftMethod = function(currIndex, nextIndex) {

	//
	//remember where we are moving to for "Save as Draft" (once that button is rendered, we're at the next page)
	currSaveIndex = nextIndex;
	
	//
	//show/hide the save button, based on which page we're moving to: nextIndex
	if(currIndex == -1 || nextIndex == 0) {	//at the first page of the wizard
		$('.save').show(); // show everything
	}	
	else if(nextIndex == 1) {
		$('.save').show(); // show everything
	}
	else if (nextIndex == 2) {
		$('.save').show(); // show everything
	}	
	else if (nextIndex == 3) {		
		$('.save').show(); // show everything
	}
	else if (nextIndex == 4) {		
		$('.save').hide(); // show nothing
	}	
}

saveProjectInformation = function(requestId) {
	// populate the user request info
	var aiMap = {"requestId":requestId};
	
	aiMap['shortName'] = $('form.createNewProject input#shortName').val().trim();			// trim whitespace
	aiMap['iRBApprovalNumber'] = $('form.createNewProject input#irbNumber').val().trim();	// trim whitespace
	aiMap['iRBExpirationDate'] = $('form.createNewProject input#irbExpDate').val();
	aiMap['activityStartDate'] = $('form.createNewProject input#startDate').val();
	aiMap['activityEndDate'] = $('form.createNewProject input#endDate').val();
	// we don't allow modifying these values here even if they are passed to the server
	aiMap['officialName'] = '';
	aiMap['draft'] = true;
	aiMap['type'] = '';

	// actually, I want this to be synchronous
	$.ajax({
		url:'../dart/saveActivityInfo.json',
		type:'POST',
		async:false,
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(aiMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success") {
				if (data.message.text !=="OK") {
					//alert(data.message.text);
					return -1;
				}

				return 0;
			}
			else {
				alert('error');
				return -1;
			}
		}
	});
}

saveParticipantInformation = function(reqestId) {
	// TODO- save participant info
	var piMap = {"requestId":requestId};
	
	// make a deep copy of the primary info to manipulate before sending to the server
	var newPrimaryInfo = jQuery.extend(true, {}, primaryInfo);
	piMap['primaryInfo'] = newPrimaryInfo;

	// remove any 'i' property in the location map
	for (idx in newPrimaryInfo.locations) {		
		var loc = newPrimaryInfo.locations[idx];		
		delete loc.i;		

		
		//primaryInvestigator defaults to true on both the notifications and data access
		var investigators = newPrimaryInfo.investigators[loc.location];
		//alert("investigators = " + JSON.stringify(investigators));

		if( investigators != undefined ) {
			var participants = investigators.participants;
			//alert("participants before = " + JSON.stringify(participants));
			//alert("primaryInvestigator for location: " + loc.location + " = " + loc.primaryInvestigatorUserId);			
			
			if( participants  != undefined ) {
				for( var pIndex = 0; pIndex < participants.length; pIndex++ ) {
					
					if(participants[pIndex].username =XX loc.primaryInvestigatorUserId) {
						
						//primaryInvestigator defaults to true on both the notifications and data access
						participants[pIndex].dataAccessChecked = true;
						participants[pIndex].checked = true;				
					}//end if						
					
				}//end for
			}//end if
			
			//alert("participants after = " + JSON.stringify(participants));			
		}//end if
	}//end for
		
//testing -- try making this call synchronous? (we were occasionally not getting all of the primaryInfo		
	// actually, I want this to be synchronous
	$.ajax({
		url:'../dart/savePrimaryInfo.json',
		type:'POST',
		async:false,
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(piMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success"){

//Note:  we are not currently allowing non-linear movement through the wizard, so this call is extra
//testing -- if the user changed the primaryInfo, this might affect the required documents (might want to move this to the validating function -> where are we moving next?)
//					// populate the document info (primaryInfo affects the required documents)
//					listDocumentsByRequest( requestId, false );					
			}
		}
	});
} 


//get the documents by requestId
listDocumentsByRequest = function(requestId, asyncVal) {

	//alert("requestId = " + requestId);
	var requestIdMap = {"requestId":requestId};	
	
	// populate the document info
	$.ajax({
		url:'../dart/listDocumentsByRequest.json',
		type:'POST',
		async:asyncVal,
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(requestIdMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success" ) {
				
//TODO: once we have the appropriate username info back from AD, we will NOT need this function
//temporarily using the username "TEST" if the participant name is null or empty
				if( data != null) {
					updateDocParticipantName( data.participants );
				}

				
				var accordionBody = Mustache.render($(".documentLocationsTemplate").html(),data);
				$('div.tab-study-name div#accordion2 .locationDocuments').html(accordionBody);
				
				accordionBody = Mustache.render($(".documentParticipantsTemplate").html(),data);
				$('div.tab-study-name div#accordion2 .participantDocuments').html(accordionBody);
				
				// TODO- populate rows with electronic documents
				
			}
		}
	});
}


//TODO: once we have the appropriate username info back from AD, we will NOT need this function
//temporarily using the username "TEST" if the participant name is null or empty
updateDocParticipantName = function( participants ) {
	
	if(participants != undefined && participants != null) {
		
		for (idx in participants) {		
			var currParticipant = participants[idx];
			
			if(currParticipant.name === null || currParticipant.name === "") {
				currParticipant.name = "TEST";
			}
		}//end for
	}//end if
}



saveDataSourcesInformation = function(requestId) {

	// save the project data source selections
	var hipaaConsent = $('form.dataSources input#HIPAAAuthorization1').is(':checked');
	var hipaaWaiver = $('form.dataSources input#HIPAAWaiver1').is(':checked');
	var startDate = $('form.dataSources input#startDateData').val();
	var endDate = $('form.dataSources input#endDateData').val();
	var dataSourceDest1 = $('form.dataSources .dataSourceDestinations input.dataLocation1').is(':checked');
	var dataSourceDest2 = $('form.dataSources .dataSourceDestinations input.dataLocation2').is(':checked');
	var dataSourceDest3 = $('form.dataSources .dataSourceDestinations input.dataLocation3').val();
	
	var selection = $('form.dataSources select#location').find(':selected');  
	var locationName = selection.val();
	var dataSources = [];
	
	$('.dataSourcesList input:checked').each(function() {
		$this = $(this);
		var id = $this.attr('data-id');
		dataSources.push(parseInt(id,10));
	});
	
	var d2 = new Object();
	d2['userId'] = 5;
	d2['requestId'] = requestId;
	d2['hipaaAuth'] = hipaaConsent;
	d2['hipaaWaiver'] = hipaaWaiver;
	d2['locationName'] = locationName;
	d2['startDate'] = startDate;
	d2['endDate'] = endDate;
	d2['dataSources'] = dataSources;
	d2['dataMart'] = dataSourceDest1;
	d2['localServer'] = dataSourceDest2;
	d2['localServerLocation'] = dataSourceDest3;
	
	$.ajax({
		url:'../dart/saveRequestDataSources.json',
		type:'POST',
		async:false,
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(d2),
		success:function(data,textStatus,three) {
			if(textStatus==="success" ) {
				
				// populate the document info (data sources affects the required documents)
				listDocumentsByRequest( requestId, false );
				
			}
		}
	});
		
return 0;	
}


//saves the current page info (used for Save Draft and when the wizard moves to the next/prev page)
saveWizardPage = function(pageIndex) {
	
	//show spinner
	$('.bwizard-buttons .save a').hide();
    $('.bwizard-buttons #saveLoader').removeClass('hide');

	var resultCode = 0;
	var saveStuff = function(){
		if (pageIndex == 0 && editable) {
			//alert("1. @ saveProjectInformation, requestId = " + requestId);
			resultCode = saveProjectInformation(requestId);
		} else if (pageIndex == 1 && editable) {
			//alert("2. @ saveParticipantInformation, requestId = " + requestId);
			resultCode = saveParticipantInformation(requestId);
		} else if (pageIndex == 2 && editable) {
			//alert("3. @ saveDataSourcesInformation, requestId = " + requestId);
			resultCode = saveDataSourcesInformation(requestId);
		} else if (pageIndex == 3) {
			//alert("4. @ docs - nothing to do, requestId = " + requestId);
			//moving to submit page
			resultCode = validateInputData(requestId); 
		}

		//hide spinner
		$('.bwizard-buttons .save a').show();
	    $('.bwizard-buttons #saveLoader').addClass('hide');
	}
	//short delay to allow UI (spinner) to catch up before saving (IE bug fix)
	window.setTimeout(saveStuff, 100);

	return resultCode;
}


validateInputData = function(requestId) {

	var resultCode = 0;
	var requestIdMap = {"requestId":requestId};
	
	$.ajax({
		url:'../dart/validateRequest.json',
		type:'POST',
		async:false,
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(requestIdMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success" ) {				
				if (data.errors.length !==0) {
					$('.submitTheRequest').hide();
					var errorMsgBody = Mustache.render($(".errorMsgTemplate").html(),data);
					$('div.tab-study-name div.alert-container').html(errorMsgBody);					
				} else {
					var successMsgBody = Mustache.render($(".successMsgTemplate").html(),data);
					$('div.tab-study-name div.alert-container').html(successMsgBody);
					$('.submitTheRequest').show();
				}
			}
		}
	});
	
	return resultCode;
}

//Save Draft wizard button	 	
$('html#requestor .bwizard-buttons').append('<li role="button" class="save"><a href="#" class="pull-right"><span class="saveText">Save Draft</span></a></li><img id="saveLoader" src="images/loader.gif" class="pull-right hide" alt="Saving">');
$('html#requestor .bwizard-buttons').on('click','.save a',function(e){
//	alert("not doing something");
//	e.preventDefault();
		
//TODO: could just get the index directly from the wizard (rather than storing in an intermediate variable)
	//
	//determine which save function to call, based on which page we're currently on: currSaveIndex
	var resultCode = saveWizardPage( currSaveIndex );	
});

