connectToDenyButton = function(){
	$('#denyBtn').on('click',function(e) {

		var url = "review-project-deny.html?revid=" + reviewId
		+ "&userId=" + userId + "&rid=" + requestId + "&wid="
		+ workflowId;
		window.open(url, 'mywindow', 'width=700,height=400');
	});
};

connectToRequestChangesButton = function(){
	
	$('#requestChanges').on('click',function(e) {

		var url = "review-project-request-changes.html?revid="
			+ reviewId + "&userId=" + userId + "&rid=" + requestId
			+ "&wid=" + workflowId;
		window.open(url, 'mywindow', 'width=700,height=400');
	});
}

connectToChangeReviewGroupsButton = function(){
	
	//to make sure there is only one connection at a time
	disconnectChangeReviewGroupsButton(); 
	$('#changeReviewsBtn').on('click',function(e) {
		if (reviewsToBeAdded.length > 0){
			window.localStorage.setItem("reviewsToBeAdded", JSON.stringify(reviewsToBeAdded)); // Saving
		}
		if (reviewsToBeRemoved.length > 0){
			window.localStorage.setItem("reviewsToBeRemoved", JSON.stringify(reviewsToBeRemoved)); // Saving
		}
		var url = "review-project-change-review-groups.html?revid="
			+ reviewId + "&userId=" + userId + "&rid=" + requestId
			+ "&wid=" + workflowId;
		window.open(url, 'mywindow', 'width=700,height=400');
	});
}

disconnectChangeReviewGroupsButton = function(){
	$('#changeReviewsBtn').off( "click");
}

disableButtonChangeReviewsBtn = function(){
	//$('#changeReviewsBtn').attr('disabled','disabled');
	$('#changeReviewsBtn').prop('disabled', true)
	$('#changeReviewsBtn').addClass('disabled');
	disconnectChangeReviewGroupsButton();
}

enableButtonChangeReviewsBtn = function(){
	//$('#changeReviewsBtn').attr('disabled', false);
	$('#changeReviewsBtn').prop('disabled', false);
	$('#changeReviewsBtn').removeClass('disabled');
	connectToChangeReviewGroupsButton();
}

connectToCommunication = function(){
	var urlvars = getUrlVars();

	var requestId = parseInt(urlvars['rid'], 10); 
	var activityId = parseInt(urlvars['id'], 10); 
	var reviewId = parseInt(urlvars['revid'], 10); 
	var workflowId = parseInt(urlvars['wid'], 10);
	
	$("div.container a#communication").click(
			function() {
				document.location = '../communication.html?id=' + activityId
						+ '&rid=' + requestId + '&revid=' + reviewId
						+ '&rev=true' + '&wid=' + workflowId;
			});
}

connectToHistory = function(){
	
	var urlvars = getUrlVars();

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

//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 += "\n\r\n\r";
				}
				notesVal += $(this).text().replace(/^\s\s*/, '').replace(
						/\s\s*$/, '').replace(/([\s]+)/g, ' ');
			});

	if (!useClipPlugin()) {
		// IE
		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);
		}
	}
};

//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, capriAccessCheckedVal) {

	var data = {
		"name" : name,
		"username" : username,
		"location" : locationName,
		"locationId" : locationId,
		"checked" : checkedVal,
		"dataAccessChecked" : dataAccessCheckedVal,
		"capriAccessChecked" : capriAccessCheckedVal
	};
	var newRow = Mustache.render($(".newRowTemplate").html(), data);

	$('.displayTable tbody tr:last').after(newRow);
};

connectToNDSInitialReviewApproveButton = function(){
	
	$('#approve').on('click',function(e) {
		e.preventDefault();

		$('#decision .review-buttons').hide(); 
		$('#decision .change-review-buttons').hide(); 
		$('#decision .progress').show(); 
		
		rvMap = {"requestId" : requestId};
		rvMap['workflowId'] = workflowId;	

		rvMap['reviewTemplates'] = getSelectedReviews();


		// short delay to allow UI (.progress) to
		// catch up before submitting (IE bug fix)
		window.setTimeout(submitRequest(), 100);
	});
	
}

connectToReviewApproveButton = function(){
	$('#approve').on('click',function(e) {
		e.preventDefault();

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

		$('#decision .progress').show(); 


		
		// short delay to allow UI (.progress) to catch up
		// before submitting (IE bug fix)
		window.setTimeout( submitRequest(), 100);
	});
};



connectToUploadDocumentModal = function(){
	
	$('div#uploadDocumentModal').on('click', 'button#submit', function(e) {
		e.preventDefault(); // do not perform the form submit

		try {
			$('#uploadDocumentModal input#fileField').fileupload('add', {
				fileInput : $('#uploadDocumentModal input#fileField')
			});

		} catch (err) {
			// alert("Exception: " + err);
		}
	});
};

var disableReviewCheckboxes = function() {

	$('.irmaListData input').each(function() {
		$(this).attr('disabled', true);
	});
};

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
	
			$('div.well h6.tracking-number').html(data.trackingNumber);
			
			//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			
		}
	}
};

//display the note on the main page
displayDocNoteSnippet = function(singleNoteData, appendNewNote) {

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

		if (singleNoteData.note != null && singleNoteData.note !== "") {

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

			// on expand/collapse, update the caret icon
			initExpandCollapseIconNoteActions();
		}
	}
};

getSelectedReviews = function(){
	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'));
		}
						
	});
	return selected;
};

//initialize the ZeroClipboard object
initClipboardObject = function() {

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

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

				// TODO: might want to hide the "Add Note" link for the
				// read-only roles so that they can't add a note?

			}
		}
	});
}

//get the Required Documents by requestId
listRequiredDocumentsByRequest = function(requestId, asyncVal) {
	console.log("Function ListRequireDocuments Start");
	var start = performance.now();
	
	var clip = null;
	if (useClipPlugin()) {

		clip = initClipboardObject();

	}

	var requestIdMap = getRequestIdMap();

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

				var accordionBody = Mustache.render($(
						".requiredDocumentLocationsTemplate").html(), data);
				$('div.locationDocuments').html(accordionBody);

				accordionBody = Mustache.render($(
						".requiredDocumentParticipantsTemplate").html(), data);
				$('div.participantDocuments').html(accordionBody);

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

					for (idx in data.participants) {
						var participants = data.participants[idx];

						if (participants != undefined && participants != null) {
							listDocumentReviewStatus(participants.documents,
									clip);
						}
					}
				}

				// initialize the modal
				$('.add-edit').on('click', function() {

					var docID = $(this).attr("rel");
					$('#addEditNoteModal #submit').attr("rel", docID);

					$('#addEditNoteModal textarea#inputTopic').val(""); 

					// TODO: we could get this information from the response
					// from listDocumentsByRequest (reviewNotes)
					// retrieve the saved notes and display them on the modal
					listDocumentReviewNotes(docID);
				});

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

				// copy all notes (for this document)
				$('.note-copy').on('click', function(e) {
					e.preventDefault();

					if (!useClipPlugin()) {
						// IE and have access to clipboardData
						window.clipboardData.clearData("Text");

					} else {
						// non-IE browser
						if (clip != null) {
							clip.setText('');
						}
					}

					// copy all notes to the clipboard
					var docID = $(this).attr("rel");
					copyDocumentReviewNotes(docID, clip);
				});

				// document status
				$('select#docStatus').on('change', function(e) {
					e.preventDefault();

					if (superUser == false && staff == false) { 

						var selection = $(this).find(':selected');
						var docStatusVal = selection.val();
						// alert("docStatusName = " + docStatusVal);

						var docID = $(this).attr("rel");
						// alert("docID = " + docID);

						setDocumentReviewStatus(docID, docStatusVal); 

					}
				});

			}

			// TODO: display something if we get an error back from the server?
			// (Error retrieving documents)
		}
	});
	var duration = performance.now() - start;
	console.log("Function ListRequireDocuments Duration " + duration);
}



//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) {
				// display the document status
				$('select#docStatus[rel="' + docId + '"]').val(docReviewStatus);
			}

			// disable the docStatus selection for super-user role and for the
			// read-only staff role
			if (superUser == true || staff == true) {
				// disable the document status chosen box
				$('select#docStatus[rel="' + docId + '"]').attr('disabled',true); 

			}

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

					if (clip != null) {
						clip.glue(copyNoteId);
					}
				} catch (err) {
					// alert("Error trying to glue the copy link to the
					// clipboard: " + err);
				}
			}

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

//move to this tab in the wizard
var moveToTab = function(tabIndex) {

	if (tabIndex >= 0 && tabIndex <= 4) {
		$('#wizard').bwizard("show", tabIndex);
	}
};

var getTabToMoveTo = function() {

	var moveToTabIndex = null;

	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)

	return moveToTabIndex;
};

populateParticipantData = function() {
	
	var requestIdMap = getRequestIdMap();
	$.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) {
					// populate the participant table
					populateParticipantTable(primaryInfo);
					// populate the primary investigator table
					populatePrimaryInfoTable(primaryInfo);
				}
			}
		}
	});
};

populateSelectedReviews = function() {

	var requestIdMap = getRequestIdMap();
	$.ajax({
		url : '../../dart/listSelectedReviewTemplates.json',
		type : 'POST',
		contentType : 'application/json',
		async : false,
		dataType : 'json',
		data : JSON.stringify(requestIdMap),
		success : function(data, textStatus, three) {
			if (textStatus === "success") {
				if (data != null) {
					if (data.templates != null
							&& data.templates != undefined) {
						if (data.templates.length > 0) {
							for ( var i in data.templates) {
								var tempId = data.templates[i].id;

								$('.irmaListData input[data-id='
										+ tempId + ']').attr(
												'checked', 'checked');
							}
						}
					}
				}
			}
		}
	});

};

getRequestIdMap = function(){
	var urlvars = getUrlVars();
	requestId = parseInt(urlvars['rid'], 10); 
	workflowId = parseInt(urlvars['wid'], 10);

	var requestIdMap = {"requestId" : requestId};
	requestIdMap['workflowId'] = workflowId;
	return requestIdMap;
};

getReviewIdMap = function(){
	var urlvars = getUrlVars();
	reviewId = parseInt(urlvars['revid'], 10); 
	var reviewIdMap = {"reviewId" : reviewId};
	return reviewIdMap;
};

getActivityIdMap = function(){
	var urlvars = getUrlVars();
	activityId = parseInt(urlvars['id'], 10); 
	var activityIdMap = {"activityId" : activityId};
	return activityIdMap
};

getPreviouslySelectedReviews = function() {
	
	var requestIdMap = getRequestIdMap();
	
	var selected = new Array();
	$.ajax({
		url : '../../dart/listSelectedReviewTemplates.json',
		type : 'POST',
		contentType : 'application/json',
		async : false,
		dataType : 'json',
		data : JSON.stringify(requestIdMap),
		success : function(data, textStatus, three) {
			if (textStatus === "success") {
				if (data != null) {
					if (data.templates != null
							&& data.templates != undefined) {
						if (data.templates.length > 0) {
							for ( var i in data.templates) {
								var tempId = data.templates[i].id;
								selected.push(tempId);
							}		
						}
					}
				}
			}
		}
	});
	return selected;
};



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

			var investigators = primaryInfo.investigators[locationId];

			if (investigators != undefined) {

				var participants = investigators.participants;
				if (participants != undefined) {

					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); // ?
						var capriAccessChecked = (participants[pIndex].capriAccessChecked);
						// "checked"
						// :
						// "";

						createAndAddRowToDisplayTable(name, username,
								locationName, locationId, checked,
								dataAccessChecked, capriAccessChecked);
					}
				}
			}
		}
	}
};

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

var setSelectedDataSources = function(dataSources) {

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

		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
				$('form.dataSources input[name=' + dsId2 + ']').attr('checked',
						'checked');
			}
		}

	}
};

//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',
		dataType:'json',
		data:JSON.stringify(docStatusMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success" ) {				
				
			}//end if success
		}
	});
};

function submitRequest() {
	$.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();

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

var submitRequestApproval = function() {
	$.ajax({
		url:'../../dart/approveRequest.json',
		type:'POST',
		async:false,
		contentType:'application/json',		
		dataType:'json',
		data:JSON.stringify(rvMap),
		success:function(data,textStatus,three) {
			if(textStatus==="success" ) {
				$('#decision .progress').fadeOut();
				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');
		}
	});
};



useClipPlugin = function() {
	if (!window.clipboardData
			|| window.clipboardData.setData("Text", "") == false) {
		return true;
	}
	return false;
};

warnAdditionalReviews = function() {
	var noMessage = true;
	
	$('input:checkbox.ndsReviewCheckBoxes').each(function() {
		var sThisVal = (this.checked ? $(this).val() : "");

		if (sThisVal != "") {
			noMessage = false;
		}
	});

	 $('#submitMsgContainer').empty(); 

	if (noMessage) {
		var successMsgBody = Mustache.render($(".successMsgTemplate").html());
		$('#submitMsgContainer').html(successMsgBody);
		$('#submitMsgContainer').append(
							'<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>Warning:  No additional reviews have been selected!</strong></div>');
		
	} else { // remove the message from the container...

			var successMsgBody = Mustache.render($(".successMsgTemplate").html());
			$('#submitMsgContainer').html(successMsgBody);
		
	}
}

//called from the bwizard to validate page changes when next or back are
//clicked
wizardValidating = function(e, ui) {

	var resultCode = validateReviewWizard(ui.nextIndex);
};

