var reviewId;
var workflowId = 0;
var initialReview = null;
var readyForInitialReview = null;
var readyForGroupReview = null;
var finalReview = null;
var admin = false;	//reviewer or NDS Admin
var ndsAdmin = false;
var superUser = false;
var staff = false;	//read-only staff
var jsonUrl = null;
var validateUrl = null;
var validateMap = null;
var rvMap = null;
var groupName = "";

var previouslySelected = null;
var reviewsToBeAdded = new Array();
var reviewsToBeRemoved = new Array();

 
// Start review-project main
$(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};
	requestIdMap['workflowId'] = workflowId;
	
	var reviewIdMap = {"reviewId":reviewId};

	//move to the specified tab in the wizard after the review has loaded (history/communication)
	var moveToTabIndex = getTabToMoveTo();
	
	
		
	// grab setup info from server
	$.ajax({
		url:'../../dart/setup.json',
		type:'GET',
		async:false,
		dataType:'json',
		contentType:'application/json',
		success:function(data,textStatus,three) {
			if(textStatus==="success"){
				$('header a.active').html(data.userFullName);
				progressIncrease('60%');
				
				ndsAdmin = data.ndsAdmin;
				superUser = data.superUser;	//is this the super-user group
				staff = data.staff;			//read-only staff
				admin = data.admin;


				groupName = data.groups[0];	//use the group name for display

				//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);
				$('#decisionPageHeader').html(decisionGroupBody);
				
				$('div#decision #modalGroupMsg').html(groupName);

				
				isDebug = data.debug;				
			}
		}
	});

	populateActivityInfo();
	connectToHistory();
	connectToCommunication();	

	populateRequestGlobalInfo();
	
	populateParticipantData();

	// populate the data source table
	populateDataSourcesData();
		
	
	//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 );
	});

	
	// file upload begin
	declareUploadDocumentModal();
	connectToUploadDocumentModal();
	// file upload end
   
	
	// populate the document info
	listRequiredDocumentsByRequest( requestId, false);
	listAdminDocumentsByRequest( requestId, false );
	
	if (ndsAdmin || superUser) {
		

		if( superUser || staff ) {	
			// allow the review decision to be submitted
			$('#decision .review-buttons').hide();	

			$('#decision .change-review-buttons').hide();
			
			$('#decision #submitReviewHeader').hide();

 			if( superUser ) {
 				//hide the ReviewTemplates for the DART Admin for now
 				$('.irmaListData').hide();	
 			}
		} else {
		
			if( initialReview ) {
				rvMap = {"requestId" : requestId};
				rvMap['workflowId'] = workflowId;
							
				connectToNDSInitialReviewApproveButton();
				
			}
			
		}
	}

	var initNDSAdmin = (superUser == false && (ndsAdmin == true && initialReview));
	if( initNDSAdmin == false ) {

		//set the approval button at the end of the screens	
		connectToReviewApproveButton();	
		
	}

	connectToDenyButton();

	connectToRequestChangesButton();

});



function populateRequestGlobalInfo(){
	var requestIdMap = getRequestIdMap();
	
	$.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;
		readyForInitialReview = data.readyForInitialReview;
		readyForGroupReview = data.readyForGroupReview;

		
		if( superUser ) {	//is this the super-user group?

			jsonUrl = '../../dart/selectReviews.json';	
			
			if( initialReview ) {
			//initial NDS review (or intermediate review)
				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 (or intermediate 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 || admin || staff) && ndsAdmin == false ) {
				//intermediate review group
				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)
				// approve the overall request
				jsonUrl = '../../dart/approveRequest.json';	
				$('#approve').html('Approve');
				rvMap = {"requestId":requestId};
				rvMap['workflowId'] = workflowId;
				
				validateUrl = '../../dart/validateFinalNDSReview.json';
				validateMap = {"requestId" : requestId};
				validateMap['workflowId'] = workflowId;
			}					
			
		}


		//get the status for this workflow (from the reviewer's perspective)
		$('form.createNewProject input#status').val(data.status);
	}
});}

/** ************************** */
/** ************************** */
/** End Init function ******* */
/** ************************** */
/** ************************** */
//Different between Prep and Research
populateActivityInfo = function(){
	
	var requestIdMap = getRequestIdMap();
	$.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.well h6.tracking-number').html(data.trackingNumber);
			$('form.createNewProject input#ndsTrackingNumber').val(data.trackingNumber);
			$('form.createNewProject input#primaryInvestigator').val(data.principalInvestigator);			
			$('form.createNewProject input#requestSubmittedDate').val(data.requestSubmittedDate);
			$('form.createNewProject textarea#officialName').val(data.officialName);			
			$('form.createNewProject input#shortName').val(data.shortName);
			$('form.createNewProject input#irbNumber').val(data.iRBApprovalNumber);
			$('form.createNewProject input#irbExpDate').val(data.iRBExpirationDate);
			$('form.createNewProject input#startDate').val(data.activityStartDate);
			$('form.createNewProject input#endDate').val(data.activityEndDate);
			
			progressIncrease('100%');
			$('#wizard').addClass('in');
			$('#preload').fadeOut();
		}
	});
};


//Research and Preparatory are different.
populateReviewTemplates = function(){
	
	var requestIdMap = getRequestIdMap();
	
	$.ajax({
		url:'../../dart/listAllReviewTemplates.json',
		type:'POST',
		contentType:'application/json',
		dataType:'json',
		async:false,
		data:JSON.stringify(requestIdMap),	//workflowIdMap
		success:function(data,textStatus,three) {
			if(textStatus==="success" ) {

				if( data != null && data != undefined && data.templates != null && data.templates != undefined ) {
					allTemplates = data.templates;
				}

				var irmaListBody = Mustache.render($(".irmaReview").html(),data);
				$('div.reviewListGoesHere').html(irmaListBody);
			
				//if we add this to the tbody element, need to remove the row instead of show/hide
				irmaListBody = Mustache.render($(".irmaTemplateRow").html(),data);
				$('.irmaListData').html(irmaListBody);
			}


			populateSelectedReviews();

			//make reviews visible at finalReview (or for super-user or read-only staff), but not editable
			if( finalReview || superUser || staff ) {
				disableReviewCheckboxes();
			}				
		}
	});
};



validateInputData = function(validateMap, validateUrl) {

	var resultCode = 0;

	//if this is not the super-user, hide the super-user message container
	if( superUser == false && staff == 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) {	//validation failed				
						$('.review-buttons').hide();	
						
						var errorMsgBody = Mustache.render($(".errorMsgTemplate").html(),data);
						$('#submitMsgContainer').html(errorMsgBody);
						
						// display the selected reviews for NDS (disable if not
						// the initialReview -> result of validate)
						disableReviewCheckboxes();
					} else {
						
						if (superUser){
							var superUserMsgTemplate = Mustache.render($(".superUserMsgTemplate").html(), data);
							$('#superUserMsgContainer').html(superUserMsgTemplate);
							$('#submitMsgContainer').hide();
							$('#decision .review-buttons').hide();	
							$('#decision #submitReviewHeader').hide();	
							$('.change-review-buttons').hide(); 
							
						}
						
						if (staff){
							var superUserMsgTemplate = Mustache.render($(".superUserMsgTemplate").html(), data);
							$('#superUserMsgContainer').html(superUserMsgTemplate);
							$('#submitMsgContainer').hide();
							$('#decision .review-buttons').hide();	
							$('#decision #submitReviewHeader').hide();	
							$('.change-review-buttons').hide(); 
							
						}
						
						if (ndsAdmin){
		
							populateReviewTemplates();
							
							if (!readyForGroupReview){
								$('#submitMsgContainer').html(successMsgBody);
								
								var successMsgBody = Mustache.render($(
								".successMsgTemplate").html(), data);
								$('#submitMsgContainer').show();
								
								$('#decision .review-buttons').show();
								
								$('.change-review-buttons').hide(); 
								
								if (initialReview){
									if (data.errors.length == 0) { // can submit the review
										warnAdditionalReviews();
										$('input:checkbox.ndsReviewCheckBoxes').change(function () {		
											warnAdditionalReviews();
										});
									}
									
								}else {
									
									disableReviewCheckboxes();
								}
								
								if (finalReview){
									var successMsgBody = Mustache.render($(".successMsgTemplate").html(),data);
									$('#submitMsgContainer').html(successMsgBody);
									
									$('#submitMsgContainer').show();
								}

							} else{
								
								$('#submitMsgContainer').hide();
								$('.change-review-buttons').show(); 
								previouslySelected = getPreviouslySelectedReviews();
								disableButtonChangeReviewsBtn();
								connectToReviewGroupChangeCheckBoxes();
							}
							
						}
						
						if (admin && !ndsAdmin){
							var successMsgBody = Mustache.render($(".successMsgTemplate").html(),data);
							$('#submitMsgContainer').html(successMsgBody);
							
							$('#submitMsgContainer').show();
							$('#decision .review-buttons').show();	
						}
					}

					$('#decision .progress').fadeOut();
				}		
			}
		});

	}
	
	//the super-user and read-only staff can both view reviews, but cannot edit them
	if( superUser == true || staff == 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);
});

//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(validateMap, validateUrl);
		}

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

//Different between Research and Preparatory
populateDataSourcesData = function(){

	var requestIdMap = getRequestIdMap();			
	$.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" ) {								

				if (data.hipaaAuth) {									
					$('.hipaaAuth').html("Yes");									
				}
				else {
					$('.hipaaAuth').html("No");
				}

				if (data.hipaaWaiver) {
					$('.hipaaWaiver').html("Yes");
				}
				else {
					$('.hipaaWaiver').html("No");
				}

				// datamart location
				setSelectedDataSourceLocation( data );

				//set the external destination
				setTransferredExternalDestination(data);

				//selected data source options
				setSelectedDataSources( data.dataSources );

				//identifier checkboxes
				if (data.realSSNIdentifier) {
					$('form.dataSources input#realSSNIdentifier').attr('checked','checked');
				} else {
					$('form.dataSources input#realSSNIdentifier').removeAttr('checked');
				}

				if (data.scrambledSSNIdentifier) {
					$('form.dataSources input#scrambledSSNIdentifier').attr('checked','checked');
				} else {
					$('form.dataSources input#scrambledSSNIdentifier').removeAttr('checked');
				}

				if (data.phiDataIdentifier) {
					$('form.dataSources input#phiIdentifier').attr('checked','checked');
				} else {
					$('form.dataSources input#phiIdentifier').removeAttr('checked');
				}								

			}
		}
	});

	
};

//Different between Research and Preparatory
var setSelectedDataSourceLocation = function( data ) {
	
	if( data != null && data != undefined ) {
	
    	if( data.dataMart ) {	//VINCI
    		$('form.dataSources input.dataLocation1').attr('checked', 'checked');
        }

		if (data.localServer) {	//local server
			$('form.dataSources input.dataLocation2').attr('checked','checked');			
		}


		//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 local server location
	}	
};

//Research Only
var setTransferredExternalDestination = function (data) {

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

        if (data.transferredExternal) {
            $('form.dataSources input.transferredExternal1').removeAttr('checked');
            $('form.dataSources input.transferredExternal2').attr('checked', 'checked');
        }
        else {
            $('form.dataSources input.transferredExternal1').attr('checked', 'checked');
            $('form.dataSources input.transferredExternal2').removeAttr('checked');
        }

        //display the location info
        $('form.dataSources input#externalDestination').val(data.externalDestination);
        $('form.dataSources input#externalStreet').val(data.externalStreet);
        $('form.dataSources input#externalCity').val(data.externalCity);
        $('form.dataSources input#externalState').val(data.externalState);
        $('form.dataSources input#externalZipCode').val(data.externalZipCode);

        showTransferredExternalDestination(data.transferredExternal); //show/hide the transferred destination
    }
};


$('#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;

		// 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" ) {				
					//display this note (prepend)
					displayDocNoteSnippet( data, false );	
					
				}
			}
		});		

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

disconnectToReviewGroupChangeCheckBoxes = function(){
	$('input:checkbox.ndsReviewCheckBoxes').off( "change");
	reviewsToBeRemoved = new Array();
	reviewsToBeAdded = new Array();
	localStorage.clear();
	
}

//Not different but uses Global variables currently
connectToReviewGroupChangeCheckBoxes = function() {
	//make sure they only connect once
	disconnectToReviewGroupChangeCheckBoxes();

	$('input:checkbox.ndsReviewCheckBoxes').change(function() {
		var tempId = $(this).attr('data-id');
		tempId = +tempId;
		if($(this).is(":checked")) { 
			console.log("checking a selection");

			if ($.inArray(tempId, previouslySelected) > -1)
			{
				console.log("Review already Pending already in database ");
				removeFromReviewsToBeRemoved(tempId); //changed there minds about withdrawn

			} else {
				console.log("Review will be added");
				addToReviewsToBeAdded(tempId); //add review
			}
		}
		else{ 
			
			console.log("unchecking a selection");
			if ($.inArray( tempId, previouslySelected) > -1)
			{
				console.log("unchecking a selection that IS already in the database");
				addToReviewsToBeRemoved(tempId); //withdraw review
			} else {
				console.log("unchecking a selection that IS not in database and not going to database");
				removeFromReviewsToBeAdded(tempId); //changed there minds about adding an additional review
			}
		}
		
		if (reviewsToBeAdded.length > 0 || reviewsToBeRemoved.length > 0 ) {
			$('#submitMsgContainer').show();
			var successMsgBody = Mustache.render($(".successMsgAdditionalTemplate").html(), null);
			$('#submitMsgContainer').html(successMsgBody);
			enableButtonChangeReviewsBtn();
			
		}else{
			disableButtonChangeReviewsBtn();
			$('#submitMsgContainer').hide();
		}
    });
};

addToReviewsToBeAdded = function(tempId ){
	if ($.inArray(tempId, reviewsToBeAdded) > -1)
	{
		alert("exists in reviewsToBeAdded");

	} else
	{
		reviewsToBeAdded.push(tempId);
	}	
};

removeFromReviewsToBeAdded = function(tempId ){
	if ($.inArray( tempId, reviewsToBeAdded) > -1){
		console.log("exists in reviewsToBeAdded - removing it");
		reviewsToBeAdded.splice($.inArray(tempId, reviewsToBeAdded),1);
	}
};

addToReviewsToBeRemoved = function(tempId ){
	if ($.inArray(tempId, reviewsToBeRemoved) > -1)
	{
		alert("exists in reviewsToBeRemoved");

	} else
	{
		reviewsToBeRemoved.push(tempId);
	}	
};

removeFromReviewsToBeRemoved = function(tempId ){
	if ($.inArray( tempId, reviewsToBeRemoved) > -1){
		console.log("exists in reviewsToBeAdded - removing it");
		reviewsToBeRemoved.splice($.inArray(tempId, reviewsToBeRemoved),1);
	}
};

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

	//alert("requestId = " + requestId);
	var requestIdMap = {"requestId":requestId};	
	
	// populate the document info
	$.ajax({
		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" ) {				

				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;
			}
		}
	
//TODO: display something if we get an error back from the server?  (Error retrieving documents)
	
	});
}

declareUploadDocumentModal = function(){
	$('#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
		progress : function(e, data) {
			// alert("progress . . . ");

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

			progressIncrease(progressPercentage);

		},
		add : function(e, data) {
			$.each(data.files,function(index, file) {

				var fileNamePieces = file.name
				.split(".");
				var fileExt = fileNamePieces[fileNamePieces.length - 1]; // get

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

				// alert("validFileType = " +
				// validFileType);
				if (validFileType) {
					$('#uploadDocumentModal')
					.modal('hide'); 

					data.submit(); 
				}
			});
		}, 
		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)) {

						if (data.result.indexOf("Error") != -1) {
							alert(data.result); 
							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);
			        		}
						}
					}
				}

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

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

			// indicate file upload progress
			progressIncrease('100%');
			$('#preload').fadeOut();
		}
	});
};

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 and read-only staff cannot edit the request
					// (including upload)
					if (superUser == true || staff == true) {
						data['editable'] = false;
					} else {
						data['editable'] = true; // if we just uploaded this
													// document, then the
													// document is "editable"
					}

					try {
						// display the newly uploaded document
						var docRowBody = Mustache.render($(
								".newAdminGroupDocumentRowTemplate").html(),
								data);
						var uploadedDocRow = $('#' + documentHeadId);
						uploadedDocRow.html(docRowBody);
					} catch (err) {
						// alert("Error: " + err);
					}
				}
			}
		}
	});
};
