var editable = false;
var reviewId;
var workflowId = 0;
var superUser = false;

//
// Start loading data: create-non-research-request
$(function() {
	var urlvars = getUrlVars();
	
	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 
	reviewId = parseInt(urlvars['revid'], 10); // get the reviewId from the url param list
	workflowId = parseInt(urlvars['wid'], 10); // get the workflowId from the url param list

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

	$( "#startDate" ).datepicker().on('changeDate',function(){$(this).datepicker('hide');});
	$( "#endDate" ).datepicker().on('changeDate',function(){$(this).datepicker('hide');});
	$( "#startDateData" ).datepicker().on('changeDate',function(){$(this).datepicker('hide');});
	$( "#endDateData" ).datepicker().on('changeDate',function(){$(this).datepicker('hide');});	
//TODO: not currently exposing the IRB expiration date for non-research requests
//	$( "#irbExpDate" ).datepicker().on('changeDate',function(){$(this).datepicker('hide'); verifyIRBExpirationDate(); });	//verify the IRB expiration date

	//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);

    // participantModal modal shown event listener to set default field focus
    $('#participantModal').on('shown', function() {
    	$('#name').focus();
    });

	// 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%');
//				progressIncrease('40%');
				
				isDebug = data.debug;				
                
				superUser = data.superUser;	//is this the super-user group                
			}

		}
	});

	//
	// 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) {
					//
					//go back to the dashboard
					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) {
			
			if( data != undefined && data != null) {
				
				$('div.well h6.study-name').html(data.officialName);
			
				//$('div.tab-study-name').attr('tracking-num-content',data.trackingNumber);
				$('div.well h6.tracking-number').html(data.trackingNumber);
					
				//TODO: we don't yet expose the IRB# and expiration date
				$('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);
			
				$('form.createNewProject input#programOffice').val(data.programOffice);
				$('form.createNewProject textarea#justification').val(data.justification);
			
			
				//
				// get and set the editable flag
				editable = data.editable;
				if( superUser == true )	//the super-user can view everything, but cannot edit
					editable = false;
			}//end if
			
			
//TODO: should this go at the end of all of the initialization calls?			
//			progressIncrease('60%');
			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) {
			if(data != null && data != undefined) {

				//$('div.tab-study-name').attr('tracking-num-content',data.trackingNumber);
				$('div.well h6.tracking-number').html(data.trackingNumber);
				
				//
				// display the amendment info if this is an amendment
				displayAmendmentInfo( data );				
				

				//
				// get and set the editable flag (amendment might be editable even if the request is not)
				editable = data.editable;
				if( superUser == true )	//the super-user can view everything, but cannot edit
					editable = false;
			}//end if
			
////TODO: should this go at the end of all of the initialization calls?			
//			progressIncrease('100%');
////			$('#wizard').addClass('in');
//			$('#preload').fadeOut();				
		}
	});	
	
	
	$("div.container a#history").click(function() {		
		document.location='./history.html?id='+activityId+'&rid='+requestId+'&revid='+reviewId+'&wid='+workflowId;
	});

	$("div.container a#communication").click(function() {				
		document.location='./communication.html?id='+activityId+'&rid='+requestId+'&revid='+reviewId+'&wid='+workflowId;
	});
	
	
	// 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"});

//TODO: not using the data sources location combo box
//TODO: if we ever put the Data Source location back in, we need to update the Mustache template for the locationId and location name
//				// 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
			}
		}
	});
	
	// 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 != null && primaryInfo != undefined ) {
                	
					if (primaryInfo.locations != null && primaryInfo.locations != undefined && primaryInfo.locations.length > 0) {
					
						populateParticipantTable(primaryInfo);	//display the participant info in the table
					
						//populatePrimaryInfoTable(primaryInfo);	//for Operations workflow, not displaying the primary locations and principal investigator
					}
				}
			}
		}
	});
	

	if( editable == false ) {	//if the request is not editable, retrieve the documents for display (only once)
		
		// populate the document info (data sources affects the required documents)
		listDocumentsByRequest( requestId, false );
	}//end else			
	
	
	//disable the page elements if this request is not currently editable
	disableAllUIControls();
	/************************ end initialize ***************/
	
	
	/************************* 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/,	
//?  autoUpload: false,
	//file upload
    $('#uploadDocumentModal input#fileField').fileupload({
    	url:'../dart/uploadDocument.json',
    	type: 'POST',
        dataType: 'text',	//IE9 tries to open/save a JSON response on file upload
        forceIframeTransport: true,	//same response on all browsers
        singleFileUploads: true,
        multipart: true,
        paramName: 'fileField',
//        progressInterval: 25,
//        bitrateInterval: 25,
        fileInput: null,	//turn off the listener
//      acceptFileTypes: /(\.|\/)(pdf|docx?)$/i,
//        fileInput: $(this),
//        change: function (e, data) {
//            $.each(data.files, function (index, file) {
//                alert('Selected file: ' + file.name);
//            });
//        },	//end change
        progress: function (e, data) {
            //alert("progress . . . ");

            var progress = parseInt(data.loaded / data.total * 100, 10);
            var progressPercentage = progress + '%';
            //alert("progressPercentage = " + progressPercentage);
            progressIncrease(progressPercentage);

            //progressIncrease('60%');
        },
        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;

                //only browsers with support for the File API report the type (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

                if (validFileType) {
                    $('#uploadDocumentModal').modal('hide'); //hide the modal (valid file type)

                    data.submit(); //upload the file
                } //end if

            });
        }, //end add
        submit: function (e, data) {
            //alert("submit @fileupload (do nothing for now)");

            //indicate file upload progress
            $('#preload').fadeIn();
            progressIncrease('20%');

            //testing -- don't submit the data yet
            //        	return false;
        },
        done: function (e, data) {
            //alert("done @fileupload");

            var success = false;

            if ((data != undefined && data != null) && (data.textStatus != undefined && data.textStatus != null)) {

                //TODO: if we get something other than "success" back, we probably want to display an error message	        	
                if (data.textStatus === "success") {

                    if ((data != undefined && data != null) && (data.result != undefined && data.result != null)) {

                        //JSON response works in browsers that support XHR transport -> NOT IE9, so switching to text return type			
                        //if( data.result.message.text !== "OK" ) {
                        //if (data.result !== "OK") {
                        if( data.result.indexOf("Error") != -1 ) {
                            alert(data.result); //if we got an error result, output it
                            success = false;
                        } else {
                            success = true;

                            try {
	                            var newDocId = parseInt( data.result );
	                            listDocumentById(newDocId);	//display the newly uploaded document
                            } catch(err) {
                            }
                        }
                    }
                } //end if success

            } else {
                alert("Error uploading the file.");
            }


/* testing -- instead of reloading all of the documents, only reload the newly uploaded one            
            if (success) {
                //	        	//show spinner
                //	        	$('.bwizard-buttons .save a').hide();
                //	            $('.bwizard-buttons #saveLoader').removeClass('hide');	        	
                //	        	var refreshFileList = function(){

                // populate the document info
                listDocumentsByRequest(requestId, false);


                //		    		//hide spinner
                //		    		$('.bwizard-buttons .save a').show();
                //		    	    $('.bwizard-buttons #saveLoader').addClass('hide');
                //		    	}//end refreshFileList	        	
                //		    	//short delay to allow UI (spinner) to catch up before saving (IE bug fix)
                //		    	window.setTimeout(refreshFileList, 100);
            } //end if -- success
/* testing -- instead of reloading all of the documents, only reload the newly uploaded one */

            
            //clear out the selected file
            var fileControl = $('#uploadDocumentModal input#fileField');
            reset(fileControl);


            //indicate file upload progress
            progressIncrease('100%');
            $('#preload').fadeOut();
        } //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 ****************/
	//initialize the modal
	$('.participant-info').on('click','button[href=#participantModal]',function(e){	//regular button
		e.preventDefault();
		
		//
		// clear the modal of the last search info (to match the selected search results)
		clearModalOfSearchResults();
		
		//$('div#participantModal input#name').focus();
	});
	
	$('.participant-info').on('click','a[href=#participantModal]',function(e){	//pencil icon
		e.preventDefault();
		
		//
		// clear the modal of the last search info (to match the selected search results)
		clearModalOfSearchResults();
		
		//$('div#participantModal input#name').focus();
	});
	
	
	//hook the findNow button on the 'Find People' (participant) modal
	$('.modal-body').on('click','button#findNow',function(e){
		e.preventDefault();
		
		//alert("clicked the find button!");
		
		$('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};
		
		//if we have no search string, don't bother to query the server	
		if(personToFindVal === "") {
			alert("Please enter a participant last name to find.");
		} else {

			$('#searchProgress').show();	//search progress bar


			//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) {
					if(textStatus==="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)						
													
							//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


							if(data.persons.length > 0) {
//TODO: make the instructions the same width as the table
//								var tableWidth = $('div#participantModal table#sortTable').width();
//								//$('div#participantModal div#resultTable .alert').removeClass('controls');
//								$('div#participantModal div#resultTable .alert').width( tableWidth );
//								//$('div#participantModal div#resultTable .alert').addClass('controls');
//								alert("tableWidth = " + tableWidth + ", css(width) = " + $('div#participantModal table#sortTable').css('width'));
//								alert("alert width = " + $('div#participantModal div#resultTable .alert').width() + ", css(width) = " + $('div#participantModal div#resultTable .alert').css('width'));
								
								$('div#participantModal div#resultTable .alert').fadeIn();	//show the instructions for selecting a participant								
							}//end if

						}//end if
					} else {
						//TODO: handle an error response
					}
				}
			});
			
			
			$('#searchProgress').fadeOut();	//search progress bar
			
		}//end else
	});
	
	
	//clicked a row in the 'Find People' results table
	$('div#participantModal table').on('click','tr', function(e){
		e.preventDefault();
		
		var selectedRow = $(this);
		
		//get the selected username
		selectedPersonName = $(this).find("td#fullName").text();
		selectedPersonUsername = X(this).find("td#username").text();

		displaySelectedParticipantName();	//display the selected name on the page
	});


	//clicked the cancel button -> no participant selected
	$('.modal-footer').on('click','button#cancel',function(e){		
		e.preventDefault();
		
		clearParticipantNameDisplay();	//clear the selected participant name		
	});


	//create the link out of the selected participant name and display it on the page
	var displaySelectedParticipantName = function(){

		//display the selected participant
		var selectedPersonLink = Mustache.render($('.selectParticipantTemplate').html(),selectedPersonName);	//display the participant name
		$('.displayTable td.primary-investigator').html( selectedPersonLink );	//display the selected name on the page

		$('.displayTable td.primary-investigator').show();	//show the selected participant link
		$('#findPeopleButtonCell').hide();	//hide the "Find People" button
	};
	
	
	//Clear out the variables holding the selected person info and update the UI
	var clearParticipantNameDisplay = function(){
		
		selectedPersonName = "";
		selectedPersonUsername = X";
		
		$('.displayTable td.primary-investigator').hide();	//hide the selected participant link
		$('#findPeopleButtonCell').show();	//show the "Find People" button		
	};
	
	//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 locationCell = thisRow.find('.location-name');
		var locationName = locationCell.text();
		var locationId = locationCell.attr('data-id');
		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 name
	        var investigators = primaryInfo.investigators[locationId];	//key off of the locationId

		if( investigators != undefined ) {
			var participants = investigators.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 + ", checkedVal = " + checkedVal);
						
						participants[pIndex].checked = checkedVal;
					}//end if
				}//end for
			}//end if
		}//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 locationCell = thisRow.find('.location-name');
		var locationName = locationCell.text();
		var locationId = locationCell.attr('data-id');
		var participantName = thisRow.find('.participant').text();	//participant name (display)

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

		//update the checkbox value for this participant name
		var investigators = primaryInfo.investigators[locationId];	//key off of the locationId

		if( investigators != undefined ) {
			var participants = investigators.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 + ", dataAccessCheckedVal = " + dataAccessCheckedVal);
						
						participants[pIndex].dataAccessChecked = dataAccessCheckedVal;
					}//end if
				}//end for
			}//end if
		}//end if
		
		//alert("primaryInfo after = " + JSON.stringify(primaryInfo));
	});

	
	
	//Add new data row to table
	$('.displayTable').on('click','.add',function(e){
		e.preventDefault();
		
		//can only modify if the request is in an editable state
		if( editable == true ) {

			
			//Add row
			var name = selectedPersonName;
			var username = XelectedPersonUsername;
	
			//var location = $("div.participant-select-location").find(".input-medium").val();	//location name
			var locationChosenBox = $("div.participant-select-location").find(".input-medium");
			var locationName = locationChosenBox.val();	//location name            
			var selectedLocationId = locationChosenBox.find('option:selected').attr('data-id');	//location ID
			//alert("selectedLocationId = " + selectedLocationId);
			
			//
			//require a person and a location before adding the participant
			if( name === "" || name === null ) {
				alert("Please select a participant.");
				return;
			}
			if (locationName === "" || locationName === null) {
				alert("Please select a participant location.");
				return;
			}//end if
			
	
			//
			//only add this participant if unique	
			var participantExists = isDuplicateParticipantUsername( primaryInfo, username );
			//alert("participant:  " + username + " @ " + locationName + ", exists = " + participantExists);
			
			if( participantExists ) {	//only add a new participant
				alert("Please select a unique participant.");
				return;
			}//end if
			
	
			var newLocation = false;
			if (getLocInfoById(selectedLocationId) === null) {	//new location
				newLocation = true;
			}
			
			
			
			//keeping 2 different values for the checkboxes (notifications, data access)
			var checked = "";
			var checkedVal = ($('.displayTable .controls').find('.notify').is(":checked"));	//get the controls row checkbox values
			if( checkedVal )
				checked = "checked";
	
			var dataAccessChecked = "";
			var dataAccessCheckedVal = ($('.displayTable .controls').find('.data-access').is(":checked"));
			if( dataAccessCheckedVal )
				dataAccessChecked = "checked";					
	
	
	//for Operations workflow, do not default to the checkboxes being checked for the principal investigator
	//			//
	//			//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, locationName, selectedLocationId, checked, dataAccessChecked);
		
			
		
			//send the new row to primaryInfo object
			if( newLocation ) {	//new location
				
				//if this is the only location, default to primary site
				var isPrimary = false;
//for Operations workflow, no primary site (for now, just default to the primary site)
				if(primaryInfo.locations.length === 0) {	
					isPrimary = true;
				}
				primaryInfo.locations.push({ "primary": isPrimary, "location": locationName, "locationId": selectedLocationId, "primaryInvestigator": name, "primaryInvestigatorUserId": username });
				primaryInfo.investigators[selectedLocationId] = { "participants": [{ "name": name, "username": username, "checked": checkedVal, "dataAccessChecked": dataAccessCheckedVal}] };
	
			} else {
				
				//assumed that if it is not a new location then it can only be a new person
				primaryInfo.investigators[selectedLocationId].participants.push({ "name": name, "username": username, "checked": checkedVal, "dataAccessChecked": dataAccessCheckedVal });
			}//end else
			
			
			//refresh the primaryInfo table when adding a new participant (even if this is just a new person, and not a new location)
			//populatePrimaryInfoTable(primaryInfo);	//for Operations workflow, not displaying the primary locations and principal investigator
		
			
			//clear old data
			$("div.participant-select-location").find(".input-medium").val("").trigger('liszt:updated');
			clearParticipantNameDisplay();	//clear the selected participant name

		}//end if -- editable
	});

	//Remove data row from table
	$('.displayTable').on('click','.delete',function(e){
		e.preventDefault();
		
		//can only modify if the request is in an editable state
		if( editable == true ) {

			var thisRow = $(this).parents('tr');
			var locationCell = thisRow.find('.location-name');
			var locationName = locationCell.text();
			var locationId = locationCell.attr('data-id');
			
			var participant = thisRow.find('.participant').text();	//participant name (display)
			var locationData = getLocInfoById(locationId);
	
			
			//remove name from investigator's list
			primaryInfo.investigators[locationId].participants = removeParticipantFromArray(participant, primaryInfo.investigators[locationId].participants);
	
			//check if we should also remove a primary location
			if (primaryInfo.investigators[locationId].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 (locationId == val.locationId && primaryInfo.locations[i].primary == true) {	//primary site?  (match the locationId)
						deletingPrimarySite = true;	//about to delete the primary site
					}//end if
				});
						
				delete primaryInfo.investigators[locationId];
				primaryInfo.locations.splice(locationData.i,1);
	
	//for Operations workflow, no primary site
	//			//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
							
			} else {
				//if we just deleted the primaryInvestigator, default to the 1st remaining participant
				if(participant===locationData.primaryInvestigator){
					var newPrimaryInvestigatorName = primaryInfo.investigators[locationId].participants[0].name;
					var newPrimaryInvestigatorUsername = XrimaryInfo.investigators[locationId].participants[0].username;

					
					primaryInfo.locations[locationData.i].primaryInvestigator = newPrimaryInvestigatorName;
					primaryInfo.locations[locationData.i].primaryInvestigatorUserId = newPrimaryInvestigatorUsername;
				
					//for Operations workflow, do not default to the checkboxes being checked for the principal investigator				
					//if we change the primary investigator, default to both checkboxes being checked (for the new primary investigator)
					//updatePrimaryInvestigatorCheckboxValues(primaryInfo.investigators[locationId].participants, newPrimaryInvestigatorName, newPrimaryInvestigatorUsername, locationName, locationId);
				}
			}
	
	//for Operations workflow, not displaying the primary locations and principal investigator
	//		//refresh the primaryInfo table when deleting a participant				
	//		populatePrimaryInfoTable(primaryInfo);	//update the display
	//		if(primaryInfo.locations.length===0){	//no sites left, so update the CSS
	//			$('.primary-info').css('opacity',.3);
	//			$('.primary-info .alert').hide();
	//		}
			
			thisRow.fadeOut('fast',function(){$(this).remove();});
			
			//
			//show the Add controls -- for Operations, allow only one participant
			$("div.participant-info .controls").removeClass('hide');			
		}//end if -- editable
	});

	//Change Primary Location
	$('.primary-info').on('click','td.primary-location i',function(e){

		//can only modify if the request is in an editable state
		if( editable == true ) {

			//var location = $(this).parents('tr').find('td.location-name').text();
			var locationCell =  $(this).parents('tr').find('td.location-name');
			var locationName = locationCell.text();  
			var locationId = locationCell.attr('data-id');            

			$('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( locationId == val.locationId ) {	//match the locationId
					primaryInfo.locations[i].primary = true;
				} else {
					primaryInfo.locations[i].primary = false;
				}
			});

		}//end if -- editable
	});

	//Change Primary Investigator
	$('.primary-info').on('click','.edit-primary-investigator',function(e){
		e.preventDefault();
		
		//can only modify if the request is in an editable state
		if( editable == true ) {
		
			var selected = $(this);
			
			var locationCell = selected.parents('tr').find('td.location-name');
			var locationName = locationCell.text();  
			var locationId = locationCell.attr('data-id');
            
			var locationData = getLocInfoById(locationId);

			var participants = primaryInfo.investigators[locationId];
			
			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;
				
				//for Operations workflow, do not default to the checkboxes being checked for the principal investigator
				//if we change the primary investigator, default to both checkboxes being checked (for the new primary investigator)			
				//updatePrimaryInvestigatorCheckboxValues(participants.participants, name, username, locationName, locationId);
				
				//populatePrimaryInfoTable(primaryInfo);	//for Operations workflow, not displaying the primary locations and principal investigator
			});
	
	//for Operations workflow, not displaying the primary locations and principal investigator
	//		$('.piSelect').on('blur',function(e){	//loss of focus on the drop-down
	//			//alert("blur!!!!");
	//			//TODO: trigger the close button event here? (function, below)
	//		});
	//		
	//		$('.primary-info').on('click','.primary-investigator button.close',function(e){	//clicked the close button
	//			populatePrimaryInfoTable(primaryInfo);
	//		});
			
		}//end if -- editable
	});


	//retrieve the JSON for this location, based on the given location name
	var getLocInfo = function(locationName){
		var locationData = null;	//default to null
		$.each(primaryInfo.locations, function(i,val){
			//alert(i + ": " + val.location);
			
			if(locationName === val.location){
				locationData = primaryInfo.locations[i];				
				locationData["i"] = i;
			}
		});
		return locationData;
	};

	//retrieve the JSON for this location, based on the given locationId
	var getLocInfoById = function (locationId) {
		var locationData = null; //default to null
		$.each(primaryInfo.locations, function (i, val) {
			//alert(i + ": " + val.location + ", " + val.locationId);

			if (locationId == val.locationId) {	//match the locationId
				//alert("found the location id:  " + locationId + ", index = " + i);
            	
				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) {

//TODO: for now, using static checkbox values (will probably want to update the model, eventually)
//					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);
					
					// populate the activity data sources info
					$.ajax({
						url:'../dart/getRequestDataSources.json',
						type:'POST',
						contentType:'application/json',
						data:JSON.stringify(requestIdMap),
						dataType:'json',
						async:false,
						success:function(data,textStatus,three) {
							if(textStatus==="success" ) {
								
//TODO: we don't currently expose hipaa for the Operations workflow
//								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');
//								}
//
//TODO: we don't currently expose start and end date for the Operations workflow								
//								$('form.dataSources input#startDateData').val(data.startDate);
//								$('form.dataSources input#endDateData').val(data.endDate);
//
//TODO: we don't currently expose geographic location for the Operations workflow
//								// geographic location
//								$("form.dataSources select#location").val(data.locationName);
								
								
								//local server location
								setSelectedDataSourceLocation( data );								
								
								//selected data source options
								setSelectedDataSources( data );
								
								//set UX tie between basic and priviledged checkboxes
								setBasicPrivilegedFunctionalTie( data );
							}
						}
					});
				}
			}
		}
	});

	
//TODO: only retrieve the list of documents just before moving to the Documents tab? (we only allow linear movement through the wizard)
//	// populate the document info (trying synchronous to see if this will solve the document issues with primaryInfo)
//	listDocumentsByRequest( requestId, false );	//synchronous

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


//displays the amendment narrative if this is an amendment
displayAmendmentInfo = function( data ) {
	
	if( data != undefined && data != null) {

		//amendment tracking#:  yyyy-mm-#-type-A#
		if( data.amendment == true || (data.trackingNumber != undefined && data.trackingNumber != null && (data.trackingNumber.indexOf("-A") > -1)) ) {	//amendment

			//
			//show/hide the amendment narrative
			var amendNarrative = Mustache.render($(".amendNarrativeTemplate").html(),data.amendmentNarrative);
			$('div.tab-study-name div.narrative').html(amendNarrative);
			
			$('div.tab-study-name div.narrative').show();	//amendment			
		} else {
			$('div.tab-study-name div.narrative').hide();	//NOP InIa endment			
		}
	}//end if	
};


//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;
	});
};

//not using the primaryInfoTable for Operations requests
//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) {

		for (idx in primaryInfo.locations) {		
			var loc = primaryInfo.locations[idx];
			var locationName = loc.location;	//location name
			var locationId = loc.locationId;
			
			
			if(loc.primaryInvestigator === null) {
				loc.primaryInvestigator = "TEST";							
			}//end if
			
			
			var investigators = primaryInfo.investigators[locationId];	//key off of the locationId
			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++ ) {
						
//						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, locationId, 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, locationId, checkedVal, dataAccessCheckedVal) {
		
	var data = {
		"name":name,
		"username":username,
		"location":locationName,
		"locationId": locationId,
		"checked":checkedVal,
		"dataAccessChecked":dataAccessCheckedVal
	};
	var newRow = Mustache.render($(".newRowTemplate").html(),data);
	
	$('.displayTable .controls').before(newRow);
	$('.displayTable tr.hide').fadeIn().removeClass('hide');
	
	
	//
	//hide the Add controls -- for Operations, allow only one participant
	$("div.participant-info .controls").addClass('hide');	
};


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

			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) {

        for (var pIndex = 0; pIndex < participants.length; pIndex++) {

        	var currUsername = Xarticipants[pIndex].username.toUpperCase().trim();
        	var usernameToCompare = participantUsername.toUpperCase().trim();
        	
        	if (currUsername =XX usernameToCompare) {	//match the participant by username
                return true;
            } //end if

        } //end for
    } //end if

    return false;
};


//returns true if this username is found at ANY location
isDuplicateParticipantUsername = XXXXXXXXX primaryInfo, username ) {
		
	if(primaryInfo != undefined && primaryInfo != null) {

		for (idx in primaryInfo.locations) {
			var loc = primaryInfo.locations[idx];
			//var locationName = loc.location;	//location name
			var locationId = loc.locationId;			
			
			var investigators = primaryInfo.investigators[locationId];	//key off of the locationId
			if(investigators != undefined) {

				var foundParticipant = isParticipantUsernameAtLocation( investigators.participants, username );
				if( foundParticipant )	//this participant is already in the primaryInfo
					return true;

			}//end if
		}//end for -- locations
	}//end if

	return false;
};


//the principalInvestigator defaults to notifications and data access (update the primaryInfo and the checkboxes)
updatePrimaryInvestigatorCheckboxValues = function (locationParticipants, participantName, participantUsername, locationName, locationId) {

    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.toUpperCase().trim() === participantUsername.toUpperCase().trim()) {	//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
    } //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 currLocationCell = $(this).find("td.location-name");
        var currLocationName = currLocationCell.text();
        var currLocationId = currLocationCell.attr('data-id');

        if (currParticipantName.toUpperCase().trim() === participantName.toUpperCase().trim() && currLocationId == locationId) {	//match locationId
            $(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;
}

$(function(){
	$('#shortName').focus();
});

//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 movingToNextPage = (ui.nextIndex > ui.index);	//which direction are we moving?
	var resultCode = saveWizardPage( ui.index, movingToNextPage );
	
	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['activityStartDate'] = $('form.createNewProject input#startDate').val();
	aiMap['activityEndDate'] = $('form.createNewProject input#endDate').val();
	aiMap['programOffice'] = $('form.createNewProject input#programOffice').val();
	aiMap['justification'] = $('form.createNewProject textarea#justification').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) {
	// 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;	//remove the extra index info

//for Operations workflow, do not default to the checkboxes being checked for the principal investigator
//		//primaryInvestigator defaults to true on both the notifications and data access
//		var investigators = newPrimaryInfo.investigators[loc.locationId];	//key off of the locationId
//
//		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
		
	// 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 );					
			}
		}
	});
} 


updateDocumentInfo = function( documentRowData, documentHeadId ) {

	if( documentInfo != null && documentInfo != undefined ) {

		//check the location documents
	    for (idx in documentInfo.locations) {
	        var loc = documentInfo.locations[idx];
	
	        var documents = loc.documents;
	        if (documents != undefined) {
		        for (var docIndex = 0; docIndex < documents.length; docIndex++) {
                    if (documents[docIndex].headId === documentHeadId) {

                    	documents[docIndex] = documentRowData;	//store this new row in the overall JSON structure
                    	return;
                    }
		        }
	        }
	    }//end for

		//check the participant documents
	    for (idx in documentInfo.participants) {
	        var loc = documentInfo.participants[idx];
	
	        var documents = loc.documents;
	        if (documents != undefined) {
		        for (var docIndex = 0; docIndex < documents.length; docIndex++) {
                    if (documents[docIndex].headId === documentHeadId) {

                    	documents[docIndex] = documentRowData;	//store this new row in the overall JSON structure
                    	return;
                    }
		        }
	        }
	    }//end for

	}//end if
}

//returns true if the specified section of documents have all been uploaded
allDocsUploaded = function( isLocationDoc ) {
	
	if( documentInfo != null && documentInfo != undefined ) {

		if( isLocationDoc === true ) {	//check the location documents
			
		    for (idx in documentInfo.locations) {
		        var loc = documentInfo.locations[idx];
		
		        var documents = loc.documents;
		        if (documents != undefined) {
			        for (var docIndex = 0; docIndex < documents.length; docIndex++) {
	                    if (documents[docIndex].uploaded === false) {
	                    	return false;
	                    }
			        }
		        }
		    }//end for
		    
		} else {	//check the participant documents
			
		    for (idx in documentInfo.participants) {
		        var loc = documentInfo.participants[idx];
		
		        var documents = loc.documents;
		        if (documents != undefined) {
			        for (var docIndex = 0; docIndex < documents.length; docIndex++) {
	                    if (documents[docIndex].uploaded === false) {
	                    	return false;
	                    }
			        }
		        }
		    }//end for
		    
		}//end else

	}//end if	
	
	return true;
}

//get the document for this documentId (display the newly uploaded document)
listDocumentById = function (documentHeadId) {

    var documentIdMap = { "documentId": documentHeadId };

    // populate the document info
    $.ajax({
        url: '../dart/listDocumentById.json',
        type: 'POST',
        async: false,
        contentType: 'application/json',
		dataType:'json',
        data: JSON.stringify(documentIdMap),
        success: function (data, textStatus, three) {
            if (textStatus === "success") {

                //only allow document uploads if this request is editable and if the document is editable (returned by the Controller)
                if (data != undefined && data != null) {
//                    data['editable'] = editable;	//editable logic determined by the Controller
                    
                    //super-user cannot edit the request (including upload)
                    if( superUser == true ) {
                    	data['editable'] = false;
                    }//end if
                } //end if


                //alert("uploaded document info:  " + JSON.stringify(data));
                
                //display the newly uploaded document
                var docRowBody = Mustache.render($(".newDocumentRowTemplate").html(), data);
                var uploadedDocRow = $('#' + documentHeadId);
                uploadedDocRow.html(docRowBody);

                var isLocationDoc = uploadedDocRow.hasClass('location');	//which section is this document in? location vs. participant
                
                //update the stored JSON -- have all documents been uploaded yet?
                updateDocumentInfo( data, documentHeadId );	
                var uploaded = allDocsUploaded( isLocationDoc );
                if( uploaded ) {
                	
                	//determine if all of the documents are uploaded (display the checkmark)
	                try {
	                	var currParent = uploadedDocRow.closest('div[class="accordion-group"]');	//get the parent	                	
	                	if( currParent != null && currParent != undefined ) {
	                		currParent.find('i.icon-ok-sign').removeClass('hide');	//show the check-box
	                	}//end if
	                } catch( err ) {
	                	//alert("Error:  " + err);
	                }
	                
                }//end if uploaded
            }//end if success

            //TODO: display something if we get an error back from the server?  (Error retrieving documents)

        } //end success
    });
}

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

	var requestIdMap = {"requestId":requestId};	
	
	//alert("editable:  " + editable);
	
	// 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" ) {
				
				//only allow document uploads if this request is editable and if the document is editable (returned by the Controller)
				if( data != undefined && data != null ) {
//					data['editable'] = editable;	//editable logic determined by the Controller
                    
					//super-user cannot edit the request (including upload)
					if( superUser == true ) {
						data['editable'] = false;
					}//end if
				}//end if				
				
								
				//required documents
				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
				
				//
				//on expand/collapse, update the caret icon
				initExpandCollapseIconActions();				
                
				//save the document JSON
				documentInfo = data;
			}
			
//TODO: display something if we get an error back from the server?  (Error retrieving documents)
						
		}//end success
	});
}


var getSelectedDataSourceLocation = function() {
	
	var dataLoc = new Object();		

	var dataSourceDest1 = $('form.dataSources .dataSourceDestinations input.dataLocation1').is(':checked');
	var dataSourceDest2 = $('form.dataSources .dataSourceDestinations input.dataLocation2').is(':checked');
//	alert("dataSourceDest1 = " + dataSourceDest1 + ", dataSourceDest2 = " + dataSourceDest2);
	
	
	dataLoc['dataMart'] = dataSourceDest1;
	dataLoc['localServer'] = dataSourceDest2;
	
//	var dataSourceDest3 = $('form.dataSources .dataSourceDestinations input.dataLocation3').val();
//	dataLoc['localServerLocation'] = dataSourceDest3;	
	
	var localServerLocation = $('form.dataSources input#facilityName').val();
	var localServerAddress = $('form.dataSources input#address').val();
	var localServerBuilding = $('form.dataSources input#building').val();
	var localServerRoomNumber = $('form.dataSources input#roomNumber').val();

	dataLoc['localServerLocation'] = localServerLocation;	//facility name
	dataLoc['localServerAddress'] = localServerAddress;
	dataLoc['localServerBuilding'] = localServerBuilding;
	dataLoc['localServerRoomNumber'] = localServerRoomNumber;
	
//	alert("dataLoc = " + JSON.stringify(dataLoc));
	return dataLoc;
};


var setSelectedDataSourceLocation = function( data ) {
	
	if( data != null && data != undefined ) {
		
		if (data.localServer) {			
			$('form.dataSources input.dataLocation1').removeAttr('checked');
			$('form.dataSources input.dataLocation2').attr('checked','checked');			
		}
		else {
			$('form.dataSources input.dataLocation2').removeAttr('checked');
			$('form.dataSources input.dataLocation1').attr('checked','checked');

//			$('form.dataSources input#facilityName').val('');
//			$('form.dataSources input#address').val('');
//			$('form.dataSources input#building').val('');
//			$('form.dataSources input#roomNumber').val('');
		}

		//display the location info
		$('form.dataSources input#facilityName').val( data.localServerLocation );
		$('form.dataSources input#address').val( data.localServerAddress );
		$('form.dataSources input#building').val( data.localServerBuilding );
		$('form.dataSources input#roomNumber').val( data.localServerRoomNumber );
		
		showServerLocation( data.localServer );	//show/hide the location
	}//end if	
};


/*Data Location*/
jQuery("input[name=dataLocation]").change(function(){
      
      if ($(this).val() == "localServerLocation") {
    	  jQuery("#serverLocation").slideDown()
      }
      else {
    	  jQuery("#serverLocation").slideUp();
      }                                                            
});


var getSelectedDataSourceIDList = function() {
	
	var dataSources = [];
	
//TODO: for now, using static checkbox values (will probably want to update the model, eventually
//	$('.dataSourcesList input:checked').each(function() {
//		$this = $(this);
//		var id = $this.attr('data-id');
//		dataSources.push(parseInt(id,10));
//	});

	$('form.dataSources input[type=checkbox]:checked').each(function() {
		$this = $(this);
		var id = $this.attr('data-id');

		if( id != null && id != undefined ) {
			var dataSourceId = parseInt(id,10);
			if ($.inArray(dataSourceId, dataSources) == -1) {	//only keep unique ID values
				dataSources.push(dataSourceId);
			}
		}//end if
	});
	
	//alert("dataSources = " + JSON.stringify(dataSources));
	
	return dataSources;
};


//disable the data sources that correspond to workflows that are not currently editable
//disable the data sources that have already been approved (do not allow the user to remove previously approved data sources)
var disableDataSources = function( dataSourcesList ) {

	if (dataSourcesList != undefined && dataSourcesList != null) {
	
		    var rlistDS = dataSourcesList;
		    if (rlistDS.length > 0) {
		        for (var i in rlistDS) {
		            var dsId2 = rlistDS[i];
		
		            // find the data source row and check its checkbox
		            $('form.dataSources input[name=' + dsId2 + ']').attr('disabled', 'disabled');
		        }
		    } //end if
	
	}//end if
};

var setSelectedDataSources = function( data ) {
	
	if( data != undefined && data != null ) {
		
		//mark the selected data sources
		if( data.dataSources != undefined && data.dataSources != null ) {
		
			var rlist2 = data.dataSources;
			if (rlist2.length > 0) {
				for (var i in rlist2) {
					var dsId2 = rlist2[i];										
					
					// find the data source row and check its checkbox
	//				$('.dataSourcesList input[name='+dsId2+']').attr('checked','checked');
					$('form.dataSources input[name='+dsId2+']').attr('checked','checked');
				}
			}//end if
		}//end if

//TODO: not currently supporting multi-workflow for Operations Requests		
//	    //
//	    //disable the data sources that correspond to workflows that are not currently editable
//	    if (data.lockedDataSources != undefined && data.lockedDataSources != null) {
//	    	disableDataSources( data.lockedDataSources );
//	    }//end if    
	    
	    //
	    //disable the data sources that have already been approved (do not allow the user to remove previously approved data sources)
	    if (data.approvedDataSources != undefined && data.approvedDataSources != null) {
	    	disableDataSources( data.approvedDataSources );
	    }//end if
		
	}//end if -- data
};


saveDataSourcesInformation = function(requestId, movingToNextPage) {

//TODO: we don't currently expose hipaa, start/end date, for the Operations workflow
	// 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 selection = $('form.dataSources select#location').find(':selected');  
	var locationName = selection.val();

	
	//local server location
	var dataLoc = getSelectedDataSourceLocation();


	//get the list of selected data source ID values (currently static)
	var dataSources = getSelectedDataSourceIDList();
	//alert("dataSources = " + JSON.stringify(dataSources));

	

//TODO: update the JSON for the Operations workflow?  Or just pass null for the values that we don't expose?
	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['realSSNIdentifier'] = false;	//not used for Operations workflow
	d2['scrambledSSNIdentifier'] = false;
	d2['phiDataIdentifier'] = false;
	
	d2['dataMart'] = dataLoc.dataMart;	//flag values
	d2['localServer'] = dataLoc.localServer;	
	
	d2['localServerLocation'] = dataLoc.localServerLocation;
	d2['localServerAddress'] = dataLoc.localServerAddress;
	d2['localServerBuilding'] = dataLoc.localServerBuilding;
	d2['localServerRoomNumber'] = dataLoc.localServerRoomNumber;
	
	d2['movingToDocsPage'] = movingToNextPage;	//moving to documents page?
	
	
	$.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" ) {
				
				if( movingToNextPage ) {	//only get the documents if we're moving to the Documents page
					
					// populate the document info (data sources affects the required documents)
					listDocumentsByRequest( requestId, false );
					
				}//end if				
			}
		}
	});
		
return 0;	
}


//disables all of the UI input controls if the request is not in an editable state
var disableAllUIControls = function() {
	
	//can only modify if the request is in an editable state
	if( editable == false ) {

		$('div.tab-study-name').each(function() {
			$(this).find('*').attr('disabled', true);
		});

		$('a[href=#participantModal]').attr('data-toggle', '');	//don't launch the Find Participant modal
		
		$("div.participant-select-location").attr('disabled', true).trigger("liszt:updated");	//disable the location chosen box
	}
}


//saves the current page info (used for Save Draft and when the wizard moves to the next/prev page)
saveWizardPage = function (pageIndex, movingToNextPage) {

    //show spinner
    //	$('.bwizard-buttons .save button').hide();	//updated to match show(), below
    //	$('.bwizard-buttons #saveLoader > img:not([alt])').attr('alt', 'Saving').removeClass('hide');

    $('.bwizard-buttons .save button').hide();
    $('.bwizard-buttons #saveLoader').removeClass('hide');

    var resultCode = 0;
    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, movingToNextPage);

    } else if (pageIndex == 3) {
        //alert("4. @ docs - nothing to do, requestId = " + requestId);

        //validate the request if we're moving forward to the submit page
        if (movingToNextPage) {
            resultCode = validateInputData(requestId);
        } //end if
    }

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

    return resultCode;
};

validateInputData = function (requestId) {

    var resultCode = 0;
    var requestIdMap = { "requestId": requestId };

    
    //if this is not the super-user, hide the super-user message container
    if( superUser == false ) {
    	$('#superUserMsgContainer').hide();
    }
    
    
    $.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();

                    if (data.errors[0].indexOf("wrong state") !== -1) {	//request in wrong state
                        var errorMsgBody = Mustache.render($(".wrongStateMsgTemplate").html(), data);
                        $('#submitMsgContainer').html(errorMsgBody);
                    } else {                    	
                        var errorMsgBody = Mustache.render($(".errorMsgTemplate").html(), data);
                        $('#submitMsgContainer').html(errorMsgBody);
                    } //end else
                    
                } else {

               		if( superUser == false || data.initiated == true ) {	//have not yet submitted this request
                			
	                    var successMsgBody = Mustache.render($(".successMsgTemplate").html(), data);
	                    //$('div.tab-study-name div.alert-container').html(successMsgBody);
	                    $('#submitMsgContainer').html(successMsgBody);
	                    $('.submitTheRequest').show();
	                    
                	} else {
	                    //
	                    //hide the validating progress bar (and the whole containing div)
	                    $('#submitMsgContainer').hide();
                	}
                }
                
                //
                //display the super-user specific messages
                if( superUser == true ) {
                    //display the state of the request
                    var superUserMsgTemplate = Mustache.render($(".superUserMsgTemplate").html(), data);
                    $('#superUserMsgContainer').html(superUserMsgTemplate);
                }                
            }
        }
    });

    //
    //the super-user can view requests, but cannot edit them
    if( superUser == true ) {
    	$('.submitTheRequest').hide();
    }    
    
    return resultCode;
}

//
// 1.	Basic Read can be selected by itself.  
// 2.	Privileged read can only be selected along with Basic read.
// If a user selects Privileged read, let's have the interface auto-select Basic read.  
// If they deselect basic read, the interface will deselect privileged read.
var setBasicPrivilegedFunctionalTie = function( data ) {
	//
	//TODO:  pull these from the data, not from some hard coded ether...
	var dsId1 = 1003;
	var dsId2 = 1004;
	
	if( data != null && data != undefined ) {
		
		// select priviledged, force basic
		$('form.dataSources input[name='+dsId2+']').click(function() {
			if($(this).is(":checked")) 
		    {
				$('form.dataSources input[name='+dsId1+']').attr('checked', true);
		    }
		});
				
		$('form.dataSources input[name='+dsId1+']').click(function() {
			if($("input:checkbox:not(:checked)")) 
		    {
				$('form.dataSources input[name='+dsId2+']').attr('checked',false);
		    }
		});
		
		
		
		
	}//end if	
};

//Save Draft wizard button	 	
$('html#requestor .bwizard-buttons').append('<li role="button" class="save"><button href="#" class="pull-right" type="button">Save Draft</button></li><img id="saveLoader" src="images/loader.gif" class="pull-right hide" alt="Saving">');
$('html#requestor .bwizard-buttons').on('click','.save button',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, false );	//saving only the current page (not moving to the next page)
});

