var reviewId;
var workflowId = 0;
var initialReview = null;
var finalReview = null;
var ndsAdmin = false;
var superUser = false;
var jsonUrl = null;
var validateUrl = null;
var validateMap = null;
var groupName = "";
var moveToTabIndex = 0;
var clip = null;
var useClipPlugin = false;
//var changeOpen = false;
//var denyOpen = false;

// 
// Start review-project main
$(function() {
	var urlvars = getUrlVars();
	var rvMap = null;
	
	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};
	var reviewIdMap = {"reviewId":reviewId};


	//move to the specified tab in the wizard after the review has loaded (history/communication)
	getTabToMoveTo( location );


	//$( "#startDate" ).datepicker();
	//$( "#endDate" ).datepicker();
	//$( "#irbExpDate" ).datepicker();
	//$( "#startDateData" ).datepicker();
	//$( "#endDateData" ).datepicker();	

		
	// 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;
				ndsAdmin = data.ndsAdmin;
				progressIncrease('60%');
				
				superUser = data.superUser;	//is this the super-user group
				
				//
				// get group name for display (from server)
				groupName = data.groups[0];

				//
				//add the group name to the Decision header (no longer using the modal)
				var decisionGroupMap = {'groupName' : groupName};
				decisionGroupMap['superUser'] = superUser;				
				var decisionGroupBody = Mustache.render($(".decisionPageHeaderTemplate").html(),decisionGroupMap);
				//alert("decisionGroupBody = " + decisionGroupBody);
				$('#decisionPageHeader').html(decisionGroupBody);
				
//				$('div#decision #modalGroup').html(groupName);	
				$('div#decision #modalGroupMsg').html(groupName);

				
				isDebug = data.debug;
			}
		}
	});

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

			$('form.createNewProject input#shortName').val(data.shortName);
			
//TODO: we don't yet expose the IRB# and expiration date?
//			$('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);
			
			
			progressIncrease('100%');
			$('#wizard').addClass('in');
			$('#preload').fadeOut();
		}
	});
		

	$("div.container a#history").click(function() {		
		document.location='../history.html?id='+activityId+'&rid='+requestId+'&revid='+reviewId+'&rev=true'+'&wid='+workflowId;
	});

	$("div.container a#communication").click(function() {				
		document.location='../communication.html?id='+activityId+'&rid='+requestId+'&revid='+reviewId+'&rev=true'+'&wid='+workflowId;
	});
	
	
	// populate the user request info
	$.ajax({
		url:'../../dart/getRequest.json',
		type:'POST',
		contentType:'application/json',
		async:false,
		dataType:'json',
		data:JSON.stringify(requestIdMap),
		success:function(data,textStatus,three) {
			
			//
			// display the amendment info if this is an amendment
			displayAmendmentInfo( data );
			
			
			//
			// populating the local copies
			initialReview = data.initialReview;			
			finalReview = data.finalReview;

			
			if( superUser ) {	//is this the super-user group?
				
				jsonUrl = '../../dart/selectReviews.json';	//display the selected reviews (read-only)
				
				if( initialReview ) {					
					validateUrl = '../../dart/validateInitialNDSReview.json';
					validateMap = {"requestId":requestId};
					validateMap['workflowId'] = workflowId;
					
				} else { // final NDS review
					validateUrl = '../../dart/validateFinalNDSReview.json';
					validateMap = {"requestId":requestId};
					validateMap['workflowId'] = workflowId;
				}				
			} else {	//not a super-user
			
				if( ndsAdmin ) {
					
					if (initialReview) {	//initial NDS review
						jsonUrl = '../../dart/selectReviews.json';
						$('#approve').html('Complete Initial Review');
						
						validateUrl = '../../dart/validateInitialNDSReview.json';
						validateMap = {"requestId":requestId};
						validateMap['workflowId'] = workflowId;

					} else { // final NDS review
						jsonUrl = '../../dart/approveRequest.json';	//approve the overall request
						$('#approve').html('Approve');
						rvMap = {"requestId":requestId};
						rvMap['workflowId'] = workflowId;
						
						validateUrl = '../../dart/validateFinalNDSReview.json';
						validateMap = {"requestId":requestId};
						validateMap['workflowId'] = workflowId;
					}
					
				} else if( reviewId != 0 ) { //intermediate review group
//TODO: this shouldn't be a valid case (no intermediate reviews for an Operations request)					
					jsonUrl = '../../dart/approveReview.json';
					$('#approve').html('Approve');
					rvMap = {"reviewId":reviewId};
					rvMap['workflowId'] = workflowId;
					
					validateUrl = '../../dart/validateReview.json';	//validate the intermediate review
					validateMap = {"reviewId":reviewId};
					validateMap['workflowId'] = workflowId;
					
				} else { // final NDS review (extra -- this is just to catch if the reviewId == 0)
					jsonUrl = '../../dart/approveRequest.json';	//approve the overall request
					$('#approve').html('Approve');
					rvMap = {"requestId":requestId};
					rvMap['workflowId'] = workflowId;
					
					validateUrl = '../../dart/validateFinalNDSReview.json';
					validateMap = {"requestId":requestId};
					validateMap['workflowId'] = workflowId;
				}					
				
			}//end else -- not superUser

			
			//get the status for this workflow (from the reviewer's perspective)
			$('form.createNewProject input#status').val(data.status);
//			if( data != null && data != undefined ) {
//				if( data.workflowStatusList != null && data.workflowStatusList != undefined && data.workflowStatusList.length > 0 ) {
//					$('form.createNewProject input#status').val(data.workflowStatusList[0].status);	
//				}//end if
//			}//end if
		}
	});
	
	// 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);	//populate the participant table
					
					//populatePrimaryInfoTable(primaryInfo);	//for Operations workflow, not displaying the primary site and principal investigator
				}
			}
		}
	});

	// 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);
				
					$.ajax({
						url:'../../dart/getRequestDataSources.json',
						type:'POST',
						contentType:'application/json',
						dataType:'json',
						data:JSON.stringify(requestIdMap),
						async:false,
						success:function(data,textStatus,three) {
							if(textStatus==="success" ) {								

//TODO: we don't currently expose hipaa for the Operations workflow
//								if (data.hipaaAuth) {									
//									$('.hipaaAuth').html("Yes");									
//								}
//								else {
//									$('.hipaaAuth').html("No");
//								}
//								
//								if (data.hipaaWaiver) {
//									$('.hipaaWaiver').html("Yes");
//								}
//								else {
//									$('.hipaaWaiver').html("No");
//								}

//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 input#location').val(data.locationName);


								//local server location
								setSelectedDataSourceLocation( data );

								//selected data source options
								setSelectedDataSources( data.dataSources );
								
							}//end if
						}
					});
				}
			}
		}
	});

	
	//move to the specified tab in the wizard after the review has loaded (history/communication)
	moveToTab( moveToTabIndex );
	/************************ end initialize ***************/

	
	/************************* File Upload ****************/
	$('div.adminLocationDocuments').on('click', 'a#uploadDocumentLink', function(e){

		//add the docid to the modal before opening it
		var docid = $(this).attr('data-id');
		//alert("clicked on the document: adding the docid: " + docid);
		
		$('#uploadDocumentModal input#docid').val( docid );
	});
		
	$('div.adminParticipantDocuments').on('click', 'a#uploadDocumentLink', function(e){

		//add the docid to the modal before opening it
		var docid = $(this).attr('data-id');
		//alert("clicked on the participant document: adding the docid: " + docid);		
		
		$('#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,
        singleFileUploads: true,
        multipart: true,
        paramName: 'fileField',
        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

	            //alert("validFileType = " + validFileType);
	            if( validFileType ) {
	            	$('#uploadDocumentModal').modal('hide');	//hide the modal with a 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 );
	                            			listAdminDocumentById(newDocId);	//display the newly uploaded document
			        		} catch(err) {
                            				//alert("Error in done clause: " + 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
	        		listAdminDocumentsByRequest( 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);
		}		
	});
	
	

	// populate the document info
	listRequiredDocumentsByRequest( requestId, false, clip );
	listAdminDocumentsByRequest( requestId, false );
	
	
	if( superUser ) {	//super-user: do not allow the review decision to be submitted
		$('#decision .review-buttons').hide();	//hide the submit buttons
		
		//$('#decision .progress').hide();		//hide the progress bar (validating)
//		$('#decision .alert-container').hide();		//hide the progress bar (validating)
		
		$('#decision #submitReviewHeader').hide();	//hide the "submit review" header
	} else {	//NOT the super-user
	
		if( ndsAdmin == true && initialReview ) {
			
	//TODO: this whole ajax call is probably extra (there are no intermediate reviews for Operations)		
	//		// populate the list of reviews 
	//		$.ajax({
	//			url:'../../dart/listAllReviewTemplates.json',
	//			type:'GET',
	//			contentType:'application/json',		
	//			success:function(data,textStatus,three) {
	//				if(textStatus==="success" ) {
	//					
	////testing -- we only have the initial/final NDS review for OperationalRequest
	////					var irmaListBody = Mustache.render($(".irmaReview").html(),data);
	////					$('div.reviewListGoesHere').html(irmaListBody);
	////					
	////					irmaListBody = Mustache.render($(".irmaTemplateRow").html(),data);
	////					$('.irmaListData').html(irmaListBody);
	//										
	//				}
	//			}
	//		});
		
		
			//
			//set the approval button at the end of the screens		
			$('#approve').on('click', function(e){
				e.preventDefault();
				
				$('#decision .review-buttons').hide();	//hide the buttons
				$('#decision .progress').show();	//show the progress bar
							
				var submitRequest = function() {
	
					//
					// create an array and populate it with the values from the checked boxes...
					var selected = new Array();
					$('input.ndsReviewCheckBoxes:checked').each(function(e){
						var temp = $(this).attr('data-id');
						if (temp != null) {
							selected.push($(this).attr('data-id'));
						}
										
					});
	
	
					rvMap = {"requestId":requestId};			
					rvMap['reviewTemplates'] = selected;
					rvMap['workflowId'] = workflowId;
		
					$.ajax({
						url:jsonUrl,
						type:'POST',
						async:false,
						contentType:'application/json',		
						dataType:'json',
						data:JSON.stringify(rvMap),
						success:function(data,textStatus,three) {
							if(textStatus==="success" ) {
								$('#decision .progress').fadeOut();	//hide the progress bar
								
//TODO: if failed to approve the review, display that info on the dashboard								
								//
								//go back to the dashboard
								//location.href="../dashboard.html";
								window.location = "../dashboard.html#review?group="+groupName;
							}
						},
						error:function(){
							$('#decision .progress').removeClass('active');
							$('#decision .progress .bar').removeClass('bar-success').addClass('bar-danger').text('Server Error');
						}
					});//end ajax				
				}
				//short delay to allow UI (.progress) to catch up before submitting (IE bug fix)
				window.setTimeout(submitRequest, 100);
			}); // end onclick
		
		}//end if(ndsAdmin == true)
		else {
			//
			//set the approval button at the end of the screens		
			$('#approve').on('click', function(e){
				e.preventDefault();
				
				$('#decision .review-buttons').hide();	//hide the buttons
				$('#decision .progress').show();		//show the progress bar
				
				var submitRequest = function() {
					$.ajax({
						url:jsonUrl,
						type:'POST',
						async:false,
						contentType:'application/json',		
						dataType:'json',
						data:JSON.stringify(rvMap),
						success:function(data,textStatus,three) {
							if(textStatus==="success" ) {
								$('#decision .progress').fadeOut();

//TODO: if failed to approve the review, display that info on the dashboard
								//
								//go back to the dashboard
								//location.href="../dashboard.html";
								window.location = "../dashboard.html#review?group="+groupName;							
							}
						},
						error:function(){
							$('#decision .progress').removeClass('active');
							$('#decision .progress .bar').removeClass('bar-success').addClass('bar-danger').text('Server Error');
						}
					});//end ajax
				}
				//short delay to allow UI (.progress) to catch up before submitting (IE bug fix)
				window.setTimeout(submitRequest, 100);				
			}); // end onclick
			
		}//end else -- NOT an NDS admin
	}//end else -- not the superUser

	
	
	//
	//set the deny button at the end of the screens		
	$('#denyBtn').on('click', function(e){
		
//		//
//		//verify that the user is not trying to apply multiple review decisions at the same time
//		if( changeOpen ) {
//			alert("Cannot deny the request while submitting a change request.");
//			return;
//		}//end if
//		if( denyOpen ) {
//			alert("Already performing a Deny.");
//			return;
//		}//end if
//		
//
//		//
//		//open the new window
//		denyOpen = true;

		var url="review-project-deny.html?revid="+reviewId +"&userId=" + userId + "&rid=" + requestId + "&wid=" + workflowId;
		window.open(url,'mywindow','width=700,height=400');
	});
	
	//
	//set the change request button at the end of the screens		
	$('#requestChanges').on('click', function(e){

//		//
//		//verify that the user is not trying to apply multiple review decisions at the same time
//		if( changeOpen ) {
//			alert("Already performing a Change Request.");
//			return;
//		}//end if
//		if( denyOpen ) {
//			alert("Cannot submit a change request while performing a deny.");
//			return;
//		}//end if
//		
//
//		//
//		//open the new window
//		changeOpen = true;
		
		var url="review-project-request-changes.html?revid="+reviewId +"&userId=" + userId + "&rid=" + requestId + "&wid=" + workflowId;
		window.open(url,'mywindow','width=700,height=400');
	});
	
	
//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 location options
//	$.ajax({
//		url:'../dart/getAllLocations.json',
//		type:'POST',
//		contentType:'application/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
//			}
//		}
//	});
	
//	removeFromArray = function(value, arr) {
//		return $.grep(arr, function(elem, index) {
//			return elem !== value;
//		});
//	};
	

});
/*****************************/
/*****************************/
/** End Init function ********/
/*****************************/
/*****************************/

displayAmendmentInfo = function( data ) {
	
	if( data != undefined && data != null) {

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

			//
			// populate the user request info (display the updated tracking# if this is an amendment)
			//$('div.tab-study-name').attr('tracking-num-content',data.trackingNumber);		
			$('div.well h6.tracking-number').html(data.trackingNumber);
			
			
			//
			//show/hide the amendment narrative
//			$('div.tab-study-name div.narrative').html("<strong>AMENDMENT NARRATIVE:</strong> " + data.amendmentNarrative);
			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	
};


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";
						}//end if
						

						//
						//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 displayTable (participant)
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 tbody tr:last').after(newRow);
};


//get the Required Documents by requestId
listRequiredDocumentsByRequest = function(requestId, asyncVal, clip) {

	//initialize the clipboard object before trying to use it
	if( !window.clipboardData || window.clipboardData.setData("Text", "") == false ) {	//can't use the clipboardData object?
		useClipPlugin = true;		
		
		if( clip == null ) {
			clip = initClipboardObject();
		}//end if
	} else {
		useClipPlugin = false;
	}//end else
	
	
	//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($(".requiredDocumentLocationsTemplate").html(),data);
				$('div.locationDocuments').html(accordionBody);
				
				accordionBody = Mustache.render($(".requiredDocumentParticipantsTemplate").html(),data);
				$('div.participantDocuments').html(accordionBody);
				
				// TODO- populate rows with electronic documents
								
				
				//
				//on expand/collapse, update the caret icon
				initExpandCollapseIconActions();
				
	
				//
				//display the document review status
				if(data != undefined && data != null) {
					
					for (idx in data.locations) {		
						var loc = data.locations[idx];
					
						if(loc != undefined && loc != null) {
							listDocumentReviewStatus( loc.documents, clip );
						}//end if
					}//end for
					
					for (idx in data.participants) {		
						var participants = data.participants[idx];
					
						if(participants != undefined && participants != null) {
							listDocumentReviewStatus( participants.documents, clip );
						}//end if
					}//end for					
				}//end if				
				
				
				//
				//initialize the modal
				$('.add-edit').on('click',function(){
					
					var docID = $(this).attr("rel");
					$('#addEditNoteModal #submit').attr("rel",docID);

					$('#addEditNoteModal textarea#inputTopic').val("");	//clear out the previous value					
					
//TODO: we could get this information from the response from listDocumentsByRequest (reviewNotes)
					//retrieve the saved notes and display them on the modal
					listDocumentReviewNotes( docID );
				});
				
				
				//
				//copy all notes (for this document)
				$('.note-copy').on('click',function(e){
					e.preventDefault();

					//clear out the text on the clipboard
					//if( window.clipboardData &&  ) {	//IE
					if( !useClipPlugin ) {	//IE and have access to clipboardData
						
						//window.clipboardData.setData("Text", "");
						window.clipboardData.clearData("Text");
						
					} else {	//non-IE browser
						
						if( clip != null ) {
							clip.setText('');
						}
					}//end else
					
					//copy all notes to the clipboard
					var docID = $(this).attr("rel");
					copyDocumentReviewNotes( docID, clip );
				});
				
				
				//
				//document status
				$('select#docStatus').on('change',function(e){
					e.preventDefault();
					
					var selection = $(this).find(':selected');
					var docStatusVal = selection.val();
					//alert("docStatusName = " + docStatusVal);					
					
					var docID = $(this).attr("rel");
					//alert("docID = " + docID);					
					
					setDocumentReviewStatus(docID, docStatusVal);	//save the status change
				});
				
			}//end if success
			
//TODO: display something if we get an error back from the server?  (Error retrieving documents)			
		}
	});	
}

//get the Admin Documents by requestId
listAdminDocumentsByRequest = function(requestId, asyncVal) {

	//alert("requestId = " + requestId);
	var requestIdMap = {"requestId":requestId};	
	
	// populate the document info
	$.ajax({
//		url:'../../dart/listAdminDocumentsByRequest.json',
		url:'../../dart/listAdminReviewDocumentsForAllGroups.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($(".adminGroupDocumentLocationsTemplate").html(),data);
				$('div.adminLocationDocuments').html(accordionBody);
				
				accordionBody = Mustache.render($(".adminGroupDocumentParticipantsTemplate").html(),data);
				$('div.adminParticipantDocuments').html(accordionBody);
				
				// TODO- populate rows with electronic documents
				
				//
				//on expand/collapse, update the caret icon
				initExpandCollapseIconActions();				

//TODO: (this is extra for now) currently for admin documents, we do not display the checkmark when all documents are uploaded
//                //save the document JSON (admin group documents)
//                documentInfo = data;
			}//end if success
		}
	
//TODO: display something if we get an error back from the server?  (Error retrieving documents)
	
	});
}


//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
//}
//
//allDocsUploaded = function() {
//	
//	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].uploaded === false) {
//                    	return false;
//                    }
//		        }
//	        }
//	    }//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].uploaded === false) {
//                    	return false;
//                    }
//		        }
//	        }
//	    }//end for
//
//	}//end if	
//	
//	return true;
//}

//get the document for this document headId (admin group documents)
listAdminDocumentById = 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") {

                if (data != undefined && data != null) {
                	
                    //super-user cannot edit the request (including upload)
                    if( superUser == true ) {
                    	data['editable'] = false;
                    } else {
                    	data['editable'] = true;	//if we just uploaded this document, then the document is "editable"                    	
                    }
	                
	//TODO: if we want to expand this to other templates, we could pass in the template object                
	                try {
		                //display the newly uploaded document
		                var docRowBody = Mustache.render($(".newAdminGroupDocumentRowTemplate").html(), data);
		                var uploadedDocRow = $('#' + documentHeadId);
		                uploadedDocRow.html(docRowBody);
	                } catch(err) {
	                	//alert("Error: " + err);
	                }
                
	//TODO: (this is extra for now) currently for admin documents, we do not display the checkmark when all documents are uploaded (if we update this, get a copy out of create-new-project.js)
	//                //update the stored JSON -- have all documents been uploaded yet?
	//                updateDocumentInfo( data, documentHeadId );	
	//                var uploaded = allDocsUploaded();
	//                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
            }//end if success

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

        } //end success
    });
}


//save the document review status value
setDocumentReviewStatus = function(docId, status) {

	var docStatusMap = {"docId":docId};	
	docStatusMap['status'] = status;

	//alert( JSON.stringify(docStatusMap) );	
	
	// save the document status
	$.ajax({
		url:'../../dart/setDocumentReviewStatus.json',
		type:'POST',
		contentType:'application/json',
		data:JSON.stringify(docStatusMap),
		dataType:'json',
		success:function(data,textStatus,three) {
			if(textStatus==="success" ) {				
				
			}//end if success
		}
	});
}


//display the document review status and notes
listDocumentReviewStatus = function( documentList, clip ) {
	
	if(documentList != undefined && documentList != null) {

		for (idx in documentList) {		
			var doc = documentList[idx];

			var docId = doc.id;			
			var docReviewStatus = doc.reviewStatus;
			
			if( docReviewStatus != null ) {
				//alert("docReviewStatus = " + docReviewStatus);
				
				//display the document status
				$('select#docStatus[rel="'+docId+'"]').val( docReviewStatus );				
			}//end if
			
			
			//glue this copy link to the ZeroClipboard object (if not using IE)
//			if( !window.clipboardData ) {	//non-IE browser
			if( useClipPlugin ) {	//non-IE browser (no access to clipboardData)
				try {
					var copyNoteIdStr = '#copyNote' + docId;
					var copyNoteId = $( copyNoteIdStr );	//testing -- see if getting the actual object helps?
					
					if( clip != null ) {
						clip.glue(copyNoteId);
					}
				} catch( err ) {
					//alert("Error trying to glue the copy link to the clipboard: " + err);
				}
			}//end if
			
			
			//display the document review notes (snippet on the main page)
			var docReviewNotesList = doc.reviewNotes;
			if(docReviewNotesList != undefined && docReviewNotesList != null) {
				
				for( noteIdx in docReviewNotesList ) {
					
					var docNote = docReviewNotesList[noteIdx];
					
					displayDocNoteSnippet( docNote, true );	//display this note (append)
				}//end for
			}//end if
		}//end for		
	}//end if
}
//listDocumentReviewStatus = function(userId, requestId) {
//
//	var docStatusMap = {"userId":userId};	
//	docStatusMap['requestId'] = requestId;
//
//	alert( JSON.stringify(docStatusMap) );	
//	
//	// get the document status
//	$.ajax({
//		url:'../../dart/listDocumentReviewStatus.json',
//		type:'POST',
//		contentType:'application/json',
//		data:JSON.stringify(docStatusMap),
//		success:function(data,textStatus,three) {
//			if(textStatus==="success" ) {				
//				
////TODO: display the status on the page (for the appropriate document)				
////{"statuses":[{"status":"Pending","docId":1564}]}				
//				
//			}//end if success
//		}
//	});
//}


//display the note on the main page
displayDocNoteSnippet = function( singleNoteData, appendNewNote ) {
	
	if(singleNoteData != null && singleNoteData != undefined) {
		
		if(singleNoteData.note != null && singleNoteData.note !== "") {

//TODO: no longer want just a snippet?  display the whole note?	
//			var originator = $('.add-edit[rel="'+singleNoteData.documentId+'"]');
//			var commentSnippet = noteText.substr(0,15) + "&hellip;";
//			originator.before("<small class='commentSnippet'><i class='icon-pushpin'></i>"+commentSnippet+"</small>");

			var originator = $('.notes[rel="'+singleNoteData.documentId+'"]');
		
			var notesBody = Mustache.render($(".docNotesMainPageTemplate").html(),singleNoteData);
			
			//add the note to this section of notes (most recent first)
			if( appendNewNote )
				originator.append( notesBody );
			else
				originator.prepend( notesBody );
		}//end if
	}//end if
};

//display the notes in the "add notes" modal
listDocumentReviewNotes = function( docId ) {

	var docNotesMap = {"documentId":docId};	
	
	// populate the document info
	$.ajax({
		url:'../../dart/listDocumentReviewNotes.json',
		type:'POST',
		contentType:'application/json',
		dataType:'json',
		data:JSON.stringify(docNotesMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success" ) {
				var notesBody = Mustache.render($(".docNotesModalTemplate").html(),data);
				$('#addEditNoteModal div.previous-comments').html(notesBody);
			}//end if success
		}
	});
}

//initialize the ZeroClipboard object
initClipboardObject = function() {
	
	useClipPlugin = true;
	
//TODO: should probably verify that they have Flash installed and that it's the right version	
	//create the ZeroClipboard object
	ZeroClipboard.setDefaults( { moviePath: "../ZeroClipboard-1.1.7/ZeroClipboard.swf", allowScriptAccess: "sameDomain" } );
	var clip = new ZeroClipboard();

	//set up the event handlers
	clip.on( 'complete', function(client, args) {
		
		//Fix -> Firefox sometimes freezes if there is an alert in this oncomplete handler
		var alertCopiedNotes = function(){
			alert("Notes copied to clipboard.  You may now paste them into another document or window.");
		}
		window.setTimeout(alertCopiedNotes, 10);		
	});	

	
	clip.on( 'mouseup', function(client, args) {
		
		if( clip != null ) {
			clip.setText('');	//clear out the text on the clipboard
		}
		
		//copy all notes to the clipboard
		var docID = $(this).attr("rel");
		copyDocumentReviewNotes( docID, clip );		
	});
	    
	return clip;
};

//copies all of the notes associated with this document
copyDocumentReviewNotes = function( docId, clip ) {

	//
	//get the text of the selected notes
	var notesVal = "";
	$('.note-background[rel="'+docId+'"]').each(function() {

//		if( notesVal != "" )
//			notesVal += "<br>";
//		notesVal += $(this).html();
//		alert("note text = " + $(this).html());
		
		if( notesVal != "" )
			notesVal += "\n\r\n\r";
		notesVal += $(this).text().trim();
	});

	//alert("overall note text = " + notesVal);

	
	//copy all notes to the clipboard
//	if( window.clipboardData ) { //Internet Explorer
	if( !useClipPlugin ) {	//IE (have access to clipboardData)

//TODO: if the copy fails, should probably try to use the plugin?		
		var bResult = window.clipboardData.setData("Text", notesVal);

		if( bResult )
			alert("Notes copied to clipboard.  You may now paste them into another document or window.");
		else
			alert("Failed to copy the notes to the clipboard.");
		
	} else {	//non-IE browsers
		
		if( clip != null ) {
			clip.setText( notesVal );	//save the note text to the clipboard
		}
	}//end else -- non-IE
};



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


//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);	
	
	//
	//validate at the end of the review wizard
	var resultCode = validateReviewWizard( ui.nextIndex );
}

//validates the current page info (used for validating at the end of the wizard)
validateReviewWizard = function(nextPageIndex) {
	
//TODO: might want to add a spinner at the last page of the review wizard?
	//show spinner
	$('.bwizard-buttons .save a').hide();
    $('.bwizard-buttons #saveLoader').removeClass('hide');

	var resultCode = 0;
	var saveStuff = function(){
		
		//validate the request if we're moving forward to the submit page
		if (nextPageIndex == 4) {	//moving to the submit page			
			resultCode = validateInputData(); 
		}

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

	var resultCode = 0;
	
	//alert("validateUrl = " + validateUrl + ", validateMap = " + JSON.stringify(validateMap));
	
	//if this is not the super-user, hide the super-user message container
	if( superUser == false ) {
		$('#superUserMsgContainer').hide();
	}
	
	
	if( validateMap != null && validateUrl != null ) {
		
		$.ajax({
			url: validateUrl,
			type:'POST',
			async:false,
			contentType:'application/json',
			dataType:'json',
			data:JSON.stringify(validateMap),
			success:function(data,textStatus,three) {
				if(textStatus==="success" ) {
					
					if (data.errors.length !==0) {						
						$('.review-buttons').hide();	//cannot submit the review
						
						var errorMsgBody = Mustache.render($(".errorMsgTemplate").html(),data);
						//$('div.tab-study-name div.alert-container').html(errorMsgBody);
						$('#submitMsgContainer').html(errorMsgBody);
					} else {
						
						if( superUser == false ) {	//not the super-user, so display the regular validation results
						
							var successMsgBody = Mustache.render($(".successMsgTemplate").html(),data);
							//$('div.tab-study-name div.alert-container').html(successMsgBody);
							$('#submitMsgContainer').html(successMsgBody);
							
							$('.review-buttons').show();	//submit allowed
							
						} else {
							//
							//hide the validating progress bar (and the whole containing div)
							$('#submitMsgContainer').hide();
						}
					}//end else
					
					//
					//display the super-user specific messages
					if( superUser == true ) {
						//display the state of the review
						var superUserMsgTemplate = Mustache.render($(".superUserMsgTemplate").html(), data);
						$('#superUserMsgContainer').html(superUserMsgTemplate);
					}
				}//end if
			}//end success
		});

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



//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");
	moveToTab(0);
});
$('#wizard').on('click', 'li#Participants', function(e){
	//alert("clicked the Participants heading");
	moveToTab(1);
});
$('#wizard').on('click', 'li#Data', function(e){
	//alert("clicked the Data heading");
	moveToTab(2);
});
$('#wizard').on('click', 'li#Documents', function(e){
	//alert("clicked the Documents heading");
	moveToTab(3);
});
$('#wizard').on('click', 'li#Decision', function(e){
	//alert("clicked the Decision heading");
	moveToTab(4);
});

//move to this tab in the wizard
var moveToTab = function( tabIndex ) {
	
	if( tabIndex >= 0 && tabIndex <= 4 ) {
		$('#wizard').bwizard("show", tabIndex);		
	}
};


var getTabToMoveTo = function( location ) {
	
	//was this page loaded from the history or communication page?
	if(location.hash.indexOf("info") > -1) {
		
		//alert("main page!");
		moveToTabIndex = 0;
				
	} else if(location.hash.indexOf("participant") > -1) {
		
		//alert("participant page!");
		moveToTabIndex = 1;
		
	} else if(location.hash.indexOf("data") > -1) {
		
		//alert("data page!");
		moveToTabIndex = 2;
		
	} else if(location.hash.indexOf("document") > -1) {
		
		//alert("document page!");
		moveToTabIndex = 3;
		
	} else if(location.hash.indexOf("decision") > -1) {
		
		//alert("decision page!");
		moveToTabIndex = 4;
	}
	
	
	removeHash();	//update the path history (remove the tab)
};



//TODO: not editable (review)
//saveProjectInformation = function(activityId) {
//	// populate the user request info
//	var aiMap = {"requestId":requestId};
//	
//	aiMap['shortName'] = $('form.createNewProject input#shortName').val();
//	aiMap['iRBApprovalNumber'] = $('form.createNewProject input#irbNumber').val();
//	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',
//		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;
//			}
//		}
//	});
//}

//TODO: not editable (review)
//saveParticipantInformation = function(requestId) {
//	// 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;  
//	}
//
//	// actually, I want this to be synchronous
//	$.ajax({
//		url:'../dart/savePrimaryInfo.json',
//		type:'POST',
////		async:false,
//		contentType:'application/json',
//		data:JSON.stringify(piMap),
//		success:function(data,textStatus,three) {
//			if(textStatus==="success"){
//				if (data.message.text !=="OK") {
//					//alert(data.message.text);
//				}
//			}
//			else {
//				alert('error');
//			}
//		}
//	});
//} 


var setSelectedDataSources = function( dataSources ) {
	
	if( dataSources != undefined && dataSources != null ) {
		
//TODO: for now, using static checkbox values (will probably want to update the model, eventually
		var rlist2 = 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
};


var setSelectedDataSourceLocation = function( data ) {
	
	if( data != null && data != undefined ) {
	
//		if (data.dataMart) {
//		//	$('form.dataSources div.dataDestinations').val(data.locationName);
//			$('form.dataSources div.localServerLocation').remove();
//		}
//		else {
//			$('form.dataSources div.dataDestinations').remove();
//			$('form.dataSources div.localServerLocation input').val(data.localServerLocation);
//		}
		
		
		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 );		
	}//end if	
};



//TODO: not editable (review)
//saveDataSourcesInformation = function(requestId) {
//	// TODO- how about checking if the page is dirty before doing all this?
//	
//	// 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();
//	var dataSources = [];
//	
//	$('div.dataSources table tbody tr.dsr input:checked').each(function() {
//		$this = $(this);
//		var id = $this.attr('name');
//		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;
//	
//	// TODO- pass the request id, not the activitiy ID
//	$.ajax({
//		url:'../dart/saveRequestDataSources.json',
//		type:'POST',
////		async:false,
//		contentType:'application/json',
//		data:JSON.stringify(d2),
//		success:function(data,textStatus,three) {
//			if(textStatus==="success" ) {
//				document.location='./project-documents.html?id='+urlvars['id'];
//			}
//		}
//	});
//}



$('#addEditNoteModal').on('click','#submit',function(e){
	e.preventDefault();
	
	var docID = $('#addEditNoteModal #submit').attr("rel");	

	var formData = $('#addEditNoteModal form').serialize();
	var formContent = $('#addEditNoteModal form').serializeArray();
	
	//validate
	var noteText = formContent[0].value.trim();
	if(noteText !== ""){
				
		//submit the form data to the database  (Want to remember this new note)
		var docNoteMap = {'documentId':docID};
		docNoteMap['note'] = noteText;

		//alert( JSON.stringify(docNoteMap) );	
		
		// save the note
		$.ajax({
			url:'../../dart/addDocumentReviewNote.json',
			type:'POST',
			contentType:'application/json',
			dataType:'json',
			data:JSON.stringify(docNoteMap),
			async:false,
			success:function(data,textStatus,three) {
				if(textStatus==="success" ) {				

					displayDocNoteSnippet( data, false );	//display this note (prepend)
					
				}//end if success
			}
		});		

		$('#addEditNoteModal').modal('hide');	//hide the modal
	}//end if
});




//updateChildActions = function() 
//{
//	changeOpen = false;
//	denyOpen = false;
//	
//	//alert("cleared out the child actions: " + changeOpen + ", " + denyOpen);
//}
//
//update = function() 
//{
////TODO: might want to move these to app.js so that it's in one spot (and no matter where they are in the app, we should have the same copy)
////TODO: append the action type to the dashboard URL (display a message)
//	updateChildActions();
//	
//	window.location = "../dashboard.html";
//}