(function () {
	'use strict';

	angular
		.module('admin', ['ui.bootstrap', 'angularUtils.directives.dirPagination', 'ui.toggle', 'mp.datePicker', 'ui.grid', 'ui.grid.moveColumns', 'ui.grid.resizeColumns', 'ui.grid.exporter', 'ui.grid.selection', 'ui.grid.saveState', 'ui.grid.pinning', 'ui.grid.cellNav', 'ui.grid.edit', 'ui.grid.pagination', ])
		.filter("dateFilter", function () {
			return function (newDate) {
				return new Date(newDate);
			}
		})
		.filter('unique', function () {

			return function (items, filterOn) {

				if (filterOn === false) {
					return items;
				}

				if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
					var hashCheck = {},
						newItems = [];

					var extractValueToCompare = function (item) {
						if (angular.isObject(item) && angular.isString(filterOn)) {
							return item[filterOn];
						} else {
							return item;
						}
					};

					angular.forEach(items, function (item) {
						var valueToCheck, isDuplicate = false;

						for (var i = 0; i < newItems.length; i++) {
							if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
								isDuplicate = true;
								break;
							}
						}
						if (!isDuplicate) {
							newItems.push(item);
						}

					});
					items = newItems;
				}
				return items;
			};
		})


		.controller('adminController', adminCtrl)

	function adminCtrl($location, $window, $state, $timeout, $scope, $http, $stateParams, adminService, User, reviewStudentAppService, ProfileService, reviewRegService, reviewProfileService, ProjectService, DateTimeService, SkillsService) {



		var vm = this;
		$scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Dakota', 'North Carolina', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];
		$scope.showUserMaint = false
		$scope.showSemesterMaint = false
		$scope.showProjectMaint = false
		$scope.showAdminPage = true
		$scope.showCoursePage = false
		$scope.routeUserMaint = routeUserMaint
		$scope.routeProjectMaintenance = routeProjectMaintenance
		$scope.routeSemesterMaintenance = routeSemesterMaintenance
		$scope.routeAdminMaint = routeAdminMaint
		$scope.routeCourseMaintenance = routeCourseMaintenance
		$scope.routeSkillMaint = routeSkillMaint
		$scope.countRows = 0;
		vm.mjKey


		vm.gridOptionsCourse = {

			enableRowHeaderSelection: true,
			enableFullRowSelection: false,
			enableRowSelection: true,
			enableSelectAll: true,
			multiSelect: true,
			saveFocus: false,
			saveScroll: true,
			saveGroupingExpandedStates: true,
			enableFiltering: true,
			enableGridMenu: true,
			enableCellEditOnFocus: true,


			columnDefs: [{
					name: '_id',
					enableCellEdit: false,
					visible: false
				},
				{
					name: 'name',
					displayName: 'Course',
					enableCellEdit: false,
					minWidth: 200
				},
				{
					name: 'title',
					displayName: 'Title',
					enableCellEdit: true,
					minWidth: 200
				},
				{
					name: 'subject',
					displayName: 'Subject',
					enableCellEdit: true,
					minWidth: 100
				},
				{
					name: 'number',
					displayName: 'Course Number',
					minWidth: 100,
					type: 'number',
					enableCellEdit: true,
					visible: false
				},
				{
					name: 'section',
					displayName: 'Section',
					minWidth: 100,
					enableCellEdit: true,
					visible: false
				},
				{
					name: 'course_id',
					displayName: 'ID',
					type: 'number',
					enableCellEdit: true,
					minWidth: 200
				},
				{
					name: 'semester',
					displayName: 'Semester',
					enableCellEdit: false,
					minWidth: 200
				},
				{
					name: 'fullName',
					displayName: 'Full Name',
					minWidth: 100,
					enableCellEdit: false,
					visible: false
				},



			],
			onRegisterApi: function (gridApi) {

				$scope.courseFilter = function () {
					vm.gridApi.grid.refresh();
				};

				//Filter for courses' super search
				vm.singleFilter = function (renderableRows) {

					//Makes sure the table's been initialized, otherwise it'll crash due to using an
					//undefine variable vm.courseFilterValue
					if (typeof vm.courseFilterValue !== 'undefined') {
						var splitInput = vm.courseFilterValue.split(" ");
						var match = false;

						for (var i = 0; i < splitInput.length; i++) {

							var matcher = new RegExp(splitInput[i]);

							renderableRows.forEach(function (row) {
								match = false;
								['name', 'title', 'subject', 'section', 'fullName', 'semester'].forEach(function (name) {
									try {
										if (row.entity[name].match(new RegExp(matcher, "i"))) {
											match = true;
										}
									} catch (err) {
										console.log(err)
									}
								});
								if (!match) {
									row.visible = false;
								}
							});
						}
					}

					return renderableRows;
				};

				var location = 0;
				vm.gridApi = gridApi;
				vm.gridApi.grid.registerRowsProcessor(vm.singleFilter, 200);

				gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
					
					for (; location < vm.gridOptionsCourse.data.length; location++) {
						if (vm.gridOptionsCourse.data[location]._id === rowEntity._id) {
							break;
						}

					}
					//$scope.gridOptionsSemester.data[location].colDef = newValue;
					var corUpdate = vm.gridOptionsCourse.data[location];

					corUpdate.colDef = newValue;
					
					if (corUpdate.subject.length > 3 || !(/^[a-zA-Z]+$/.test(corUpdate.subject)) || corUpdate.number > 9999 || corUpdate.number < 0 || corUpdate.course_id < 0) {
						corUpdate.colDef = oldValue;
						swal({
							title: "Error",
							text: "Format Error! Can't Update Course",
							type: "error",
							confirmButtonText: "Continue",
							allowOutsideClick: true,
							timer: 10000,
						}, function () {});
					} else {
						vm.editCourse(corUpdate);
						vm.saveChangesCourse();
						//swal({
						//	title: "Course Properties have Changed",
						//	text: "",
						//	type: "success",
						//	confirmButtonText: "Continue",
						//	allowOutsideClick: true,
						//	timer: 10000,
						//}, function () {

						//});
					}
					//VIP-205
					// rpach023 reset location to allow multiple updates.
					location = 0;


				});
			},



		};


		vm.saveCourseState = function () {
			adminService.getAdminSettings().then(function (data) {
				var state = data;
				state.courseState = vm.gridApi.saveState.save();
				console.log(state);

				adminService.saveAdminSettings(state).then(function (data) {
					console.log("SAVE SUCCESS")
				})
			});




		};
		$scope.state = {};

		vm.restoreCourseState = function () {
			adminService.getAdminSettings().then(function (data) {
				var state = data;
				for (var i = 0; i < state.courseState.columns.length; i++) {
					state.courseState.columns[i].sort = {};
					state.courseState.columns[i].filters = [{}];
				}

				$scope.state = state.courseState;
				vm.gridApi.saveState.restore($scope, $scope.state);

			});
			console.log("LOAD SUCCESS");

		};

		//User Story: FA18 | VIP-175, mvale080 (added grid panel for Skills, based off rmart080 work)
		vm.gridOptionsSkill = {

			enableRowHeaderSelection: true,
			enableFullRowSelection: false,
			enableRowSelection: true,
			enableSelectAll: true,
			multiSelect: true,
			saveFocus: false,
			saveScroll: true,
			saveGroupingExpandedStates: true,
			enableFiltering: true,
			enableGridMenu: true,
			enableCellEditOnFocus: true,

			columnDefs: [{
					name: '_id',
					enableCellEdit: false,
					visible: false
				},
				{
					name: 'skill',
					displayName: 'Skill',
					enableCellEdit: true,
					minWidth: 200
				},

				{
					name: 'Approved',
					displayName: 'Approved',
					minWidth: 200,
					width: '50%',
					type: 'boolean',
					cellTemplate: '<div ><input type="checkbox" ng-checked="{{row.entity.Approved}}" ng-model="row.entity.Approved" ></div>'
				},
				/*
				{
					name: 'Approved', displayName: 'Approved', minWidth: 200, editableCellTemplate: 'ui-grid/dropdownEditor', editDropdownValueLabel: 'current', editDropdownOptionsArray: [
						{ id: true, current: true },
						{ id: false, current: false }
					]
				}
				*/
			],
			onRegisterApi: function (gridApi) {
				var location = 0;
				vm.gridApi = gridApi;
				//vm.gridApi.grid.registerRowsProcessor( vm.skillFilter, 3 ); used for supersearch, rmart080
				gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
					
					for (; location < vm.gridOptionsSkill.data.length; location++) {
						if (vm.gridOptionsSkill.data[location]._id === rowEntity._id) {
							break;
						}

					}
					//$scope.gridOptionsSkill.data[location].colDef = newValue;
					var skiUpdate = vm.gridOptionsSkill.data[location];

					skiUpdate.colDef = newValue;
					SkillsService.updateSkill(skiUpdate, skiUpdate._id).then(function (success) {
						console.log("Successfully Edited Skill");
						//skillchange_msg();
						resetSkiSettings();
						loadSkills();

					});
					//VIP-205
					//rpach023 location reset to allow multiple changes without refreshing.
					location = 0;

				});
			},
		};

		vm.getSelectedRow = function () {
			var semToDelete = vm.gridApi.selection.getSelectedRows();


			return semToDelete[0];
		}


		adminService.loadCourses().then(function (data) {
			vm.gridOptionsCourse.data = data;


		});
		SkillsService.retrieveSkills().then(function (data) {
			vm.gridOptionsSkill.data = data;

		});


		vm.saveSkillsState = function () {
			adminService.getAdminSettings().then(function (data) {
				var state = data;
				state.skillsState = vm.gridApi.saveState.save();

				adminService.saveAdminSettings(state).then(function (data) {
					console.log("SAVE SUCCESS")
				})
			});




		};
		$scope.state = {};
		vm.restoreSkillsState = function () {
			adminService.getAdminSettings().then(function (data) {
				var state = data;
				for (var i = 0; i < state.skillsState.columns.length; i++) {
					state.skillsState.columns[i].sort = {};
					state.skillsState.columns[i].filters = [{}];
				}

				$scope.state = state.skillsState;
				vm.gridApi.saveState.restore($scope, $scope.state);

			});
			console.log("LOAD SUCCESS");

		};










		/** User Story FA18 | VIP-37, VIP-139, VIP-140, VIP-147, VIP-121,
		 *  VIP-140, VIP-170, VIP-169, VIP-134, Rmart080(User Tab)
		 * 
		 * This new table replaces the old User tab, it includes custom filters,
		 * the base for super search, refresh filters, inline edits, while
		 * using existing functions for adding new data or eliminating data.
		 * */
		vm.gridOptionsUser = {
			filterOptions: $scope.userFilterOptions,
			paginationPageSizes: [10, 15, 25],
			paginationPageSize: 10,
			enableRowHeaderSelection: true,
			enableFullRowSelection: false,
			enableRowSelection: true,
			enableSelectAll: true,
			multiSelect: true,
			saveFocus: false,
			saveScroll: true,
			saveGroupingExpandedStates: true,
			enableFiltering: true,
			enableGridMenu: true,
			enableCellEditOnFocus: true,
			showGridFooter: true,


			columnDefs: [{
					name: '_id',
					displayName: 'ID',
					visible: false,
					minWidth: 200
				},
				{
					name: 'firstName',
					displayName: 'First Name',
					visible: true,
					minWidth: 200
				},
				{
					name: 'lastName',
					displayName: 'Last Name',
					visible: true,
					minWidth: 200
				},
				{
					name: 'email',
					displayName: 'Email',
					visible: true,
					minWidth: 200
				},
				{
					name: 'semester',
					displayName: 'Semester',
					visible: true,
					minWidth: 200
				},
				{
					name: 'rank',
					displayName: 'Rank',
					visible: false,
					minWidth: 200
				},
				{
					name: 'project',
					displayName: 'Project',
					enableCellEdit: true,
					visible: true,
					minWidth: 200,
					editableCellTemplate: 'ui-grid/dropdownEditor',
					width: '20%',
					editDropdownValueLabel: 'title',
					editDropdownIdLabel: 'title',
				},
				{
					name: 'piApproval',
					displayName: 'Approved',
					visible: false,
					minWidth: 200,
					editableCellTemplate: 'ui-grid/dropdownEditor',
					width: '20%',
					editDropdownValueLabel: 'piApproval',
					editDropdownOptionsArray: [{
							id: true,
							piApproval: true
						},
						{
							id: false,
							piApproval: false
						}
					]
				},
				{
					name: 'isSuperUser',
					displayName: 'Super User',
					visible: false,
					minWidth: 200,
					editableCellTemplate: 'ui-grid/dropdownEditor',
					width: '20%',
					editDropdownValueLabel: 'isSuperUser',
					editDropdownOptionsArray: [{
							id: true,
							isSuperUser: true
						},
						{
							id: false,
							isSuperUser: false
						}
					]
				},
				{
					name: 'piDenial',
					displayName: 'Denied',
					visible: false,
					minWidth: 200,
					editableCellTemplate: 'ui-grid/dropdownEditor',
					width: '20%',
					editDropdownValueLabel: 'piDenial',
					editDropdownOptionsArray: [{
							id: true,
							piDenial: true
						},
						{
							id: false,
							piDenial: false
						}
					]
				},
				{
					name: 'college',
					displayName: 'College',
					visible: false,
					minWidth: 200
				},
				{
					name: 'major',
					displayName: 'Major',
					visible: false,
					minWidth: 200
				},
				{
					name: 'minor',
					displayName: 'Minor',
					visible: false,
					minWidth: 200
				},
				{
					name: 'resume',
					displayName: 'Resume',
					visible: false,
					minWidth: 200
				},
				{
					name: 'userType',
					displayName: 'Type',
					visible: false,
					minWidth: 200
				},
				{
					name: 'isDecisionMade',
					displayName: 'Decision Made',
					visible: false,
					minWidth: 200,
					editableCellTemplate: 'ui-grid/dropdownEditor',
					width: '20%',
					editDropdownValueLabel: 'isDecisionMade',
					editDropdownOptionsArray: [{
							id: true,
							isDecisionMade: true
						},
						{
							id: false,
							isDecisionMade: false
						}
					]
				},
				{
					name: 'joined_project',
					displayName: 'Joined Project',
					visible: false,
					minWidth: 200,
					editableCellTemplate: 'ui-grid/dropdownEditor',
					width: '20%',
					editDropdownValueLabel: 'joined_project',
					editDropdownOptionsArray: [{
							id: true,
							joined_project: true
						},
						{
							id: false,
							joined_project: false
						}
					]
				},
				{
					name: 'skillItem',
					displayName: 'Skill Item',
					visible: false,
					minWidth: 200
				},
				{
					name: 'vipcredit',
					displayName: 'VIP Credit',
					visible: false,
					minWidth: 200
				},
				{
					name: 'volunteer',
					displayName: 'Volunteer',
					visible: false,
					minWidth: 200
				},
				{
					name: 'independentstudy',
					displayName: 'Indepenedent Study',
					visible: false,
					minWidth: 200
				},
				{
					name: 'appliedDate',
					displayName: 'Applied Date',
					visible: false,
					minWidth: 200
				},
				{
					name: 'RegDate',
					displayName: 'Register Date',
					visible: false,
					minWidth: 200
				},
				{
					name: 'firstlogin_date',
					displayName: 'First Login',
					visible: false,
					minWidth: 200
				},
				{
					name: 'allowNotifications',
					displayName: 'Allow Notifications',
					visible: false,
					minWidth: 200,
					editableCellTemplate: 'ui-grid/dropdownEditor',
					width: '20%',
					editDropdownValueLabel: 'allowNotifications',
					editDropdownOptionsArray: [{
							id: true,
							allowNotifications: true
						},
						{
							id: false,
							allowNotifications: false
						}
					]
				},
				{
					name: 'course',
					displayName: 'Course',
					visible: false,
					minWidth: 200
				},
				{
					name: 'isEnrolled',
					displayName: 'Enrolled',
					visible: false,
					minWidth: 200,
					editableCellTemplate: 'ui-grid/dropdownEditor',
					width: '20%',
					editDropdownValueLabel: 'isEnrolled',
					editDropdownOptionsArray: [{
							id: true,
							isEnrolled: true
						},
						{
							id: false,
							isEnrolled: false
						}
					]
				},
				{
					name: 'piProjectApproval',
					displayName: 'PI Approved',
					visible: false,
					minWidth: 200,
					editableCellTemplate: 'ui-grid/dropdownEditor',
					width: '20%',
					editDropdownValueLabel: 'piProjectApproval',
					editDropdownOptionsArray: [{
							id: true,
							piProjectApproval: true
						},
						{
							id: false,
							piProjectApproval: false
						}
					]
				},
				{
					name: 'selectedSemester',
					displayName: 'Selected Semester',
					visible: false,
					minWidth: 200
				},
			],

			onRegisterApi: function (gridApi) {
				//Used for Editing Users rmart080 FA18

				$scope.userFilter = function () {
					vm.gridApi.grid.refresh();
				};

				gridApi.selection.on.rowSelectionChanged($scope, function (row) {
					var scount = gridApi.grid.selection.selectedCount;
					var msg = 'row selected ' + row.isSelected; //+ ' count: ' + $scope.gridApi.grid.selection.selectedCount;
					console.log(msg);

					if (scount == 1) {
						document.getElementById("impersonateUser").disabled = false;
					} else {
						document.getElementById("impersonateUser").disabled = true;
					}

				});


				//Filter for users tab's super search
				vm.singleFilter = function (renderableRows) {

					//Makes sure the table's been initialized, otherwise it'll crash due to using an
					//undefine variable vm.userFilterValue
					if (typeof vm.userFilterValue !== 'undefined') {
						var splitInput = vm.userFilterValue.split(" ");
						var match = false;

						for (var i = 0; i < splitInput.length; i++) {
							var matcher = new RegExp(splitInput[i]);

							renderableRows.forEach(function (row) {
								match = false;
								['firstName', 'lastName', 'email', 'semester', 'rank', 'project', 'college', 'major',
									'minor', 'resume', 'userType', 'skillItem', 'vipcredit', 'volunteer', 'independentstudy',
									'RegDate', 'appliedDate', 'firstlogin_date', 'course', 'selectedSemester'
								].forEach(function (name) {
									try {
										if (row.entity[name].match(new RegExp(matcher, "i"))) {
											match = true;
										}
									} catch (err) {
										console.log(err)
									}
								});
								if (!match) {
									row.visible = false;
								}
							});
						}
					}

					return renderableRows;
				};

				var location = 0;
				vm.gridApi = gridApi;

				vm.gridApi.grid.registerRowsProcessor(vm.singleFilter, 200);
				gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
					for (; location < vm.gridOptionsUser.data.length; location++) {
						if (vm.gridOptionsUser.data[location]._id === rowEntity._id) {
							break;
						}


					}
					vm.gridOptionsUser.data[location].colDef = newValue;
					var userUpdate = vm.gridOptionsUser.data[location];

					userUpdate.colDef = newValue;
					User.update({
						user: userUpdate
					}).then(function (success) {
						console.log("Successfully Edited User");



					});

					//tests if the changed column was the project
					if (colDef.name == "project") {
						addUserToProject(userUpdate);
						removeUserFromProject(userUpdate, oldValue, false);
					}
					//VIP-205
					//rpach023: Resetting location to allow multiple changes without refreshing site.
					location = 0;

				});
			}
		};


		vm.getSelectedUserRowDelete = function () {
			var userToManipulate = vm.gridApi.selection.getSelectedRows();


			return userToManipulate;
		};
		vm.getSelectedUserRow = function () {
			var userToManipulate = vm.gridApi.selection.getSelectedRows();





			return userToManipulate[0];
		};


		vm.saveUserState = function () {
			adminService.getAdminSettings().then(function (data) {
				var state = data;
				state.userState = vm.gridApi.saveState.save();

				adminService.saveAdminSettings(state).then(function (data) {
					console.log("SAVE SUCCESS")
				})
			});




		};
		$scope.state = {};
		vm.restoreUserState = function () {
			adminService.getAdminSettings().then(function (data) {
				var state = data;
				for (var i = 0; i < state.userState.columns.length; i++) {
					state.userState.columns[i].sort = {};
					state.userState.columns[i].filters = [{}];
				}

				$scope.state = state.userState;
				vm.gridApi.saveState.restore($scope, $scope.state);

			});
			console.log("LOAD SUCCESS");

		};

		adminService.loadAllUsers().then(function (data) {
			vm.gridOptionsUser.data = data;
		});

		/** User Story FA18 | VIP-38, VIP-139, VIP-140, VIP-147, VIP-121,
		 *  VIP-140, VIP-170, VIP-169, VIP-134, Rmart080(Project Tab)
		 * 
		 * This new table replaces the old Project tab, it includes custom filters,
		 * the base for super search, refresh filters, inline edits, while
		 * using existing functions for adding new data or eliminating data.
		 * */
		vm.gridOptionsProjects = {
			paginationPageSizes: [10, 15, 25],
			paginationPageSize: 10,
			enableRowHeaderSelection: true,
			enableFullRowSelection: false,
			enableRowSelection: true,
			enableSelectAll: true,
			multiSelect: true,
			saveFocus: false,
			saveScroll: true,
			saveGroupingExpandedStates: true,
			enableFiltering: true,
			enableGridMenu: true,
			enableCellEditOnFocus: true,

			columnDefs: [{
					name: '_id',
					minWidth: 200,
					enableCellEdit: false,
					visible: false
				},
				{
					name: 'title',
					displayName: 'Title',
					enableCellEdit: true,
					minWidth: 200
				},
				{
					name: 'owner_email',
					displayName: 'Owner Email',
					enableCellEdit: true,
					minWidth: 200
				},
				{
					name: 'owner_rank',
					displayName: 'Owner Rank',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'owner_name',
					displayName: 'Owner',
					enableCellEdit: true,
					minWidth: 150
				},
				{
					name: 'description',
					displayName: 'Description',
					enableCellEdit: true,
					minWidth: 200
				},
				{
					name: 'disciplines',
					displayName: 'Disciplines',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'firstSemester',
					displayName: 'Semester',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'maxStudents',
					displayName: 'Max Students',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'goals',
					displayName: 'Goals',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'keyElements',
					displayName: 'Key Elements',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'researchIssues',
					displayName: 'Research Issues',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'meetingTime',
					displayName: 'Meeting Time',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'advisors',
					displayName: 'Advisors',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'sponsors',
					displayName: 'Sponsors',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'majPrepInt',
					visible: false,
					minWidth: 200
				},
				{
					name: 'faculty',
					displayName: 'Faculty',
					enableCellEdit: false,
					visible: false,
					minWidth: 200
				},
				{
					name: 'mentor',
					displayName: 'Mentor',
					enableCellEdit: false,
					visible: false,
					minWidth: 200
				},
				{
					name: 'addedStudents',
					visible: false,
					minWidth: 200
				},
				{
					name: 'members',
					displayName: 'Members',
					enableCellEdit: false,
					visible: false,
					minWidth: 200
				},
				{
					name: 'members_detailed',
					displayName: 'Students',
					enableCellEdit: false,
					minWidth: 200
				},
				{
					name: 'contact',
					displayName: 'Contact',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'status',
					displayName: 'Status',
					enableCellEdit: true,
					minWidth: 100,
					editableCellTemplate: 'ui-grid/dropdownEditor',
					width: '20%',
					editDropdownValueLabel: 'status',
					editDropdownOptionsArray: [{
							id: 'Active',
							status: 'Active'
						},
						{
							id: 'Pending',
							status: 'Pending'
						},
						{
							id: 'Disabled',
							status: 'Disabled'
						}
					]
				},
				{
					name: 'edited',
					displayName: 'Edited',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'old_project',
					visible: false,
					minWidth: 200
				},
				{
					name: 'image',
					visible: false,
					minWidth: 200
				},
				{
					name: 'video_url',
					visible: false,
					minWidth: 200
				},
				{
					name: 'attachments',
					visible: false,
					minWidth: 200
				},
				{
					name: 'deliverables_attached',
					visible: false,
					minWidth: 200
				},
				{
					name: 'mingle_url',
					visible: false,
					minWidth: 200
				},
				{
					name: 'youtube_url',
					visible: false,
					minWidth: 200
				},
				{
					name: 'github_url',
					visible: false,
					minWidth: 200
				},
				{
					name: 'drive_url',
					visible: false,
					minWidth: 200
				},
				{
					name: 'archive_url',
					visible: false,
					minWidth: 200
				},
				{
					name: 'term',
					displayName: 'Term',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
				{
					name: 'reqskillItem',
					visible: false,
					minWidth: 200
				},
				{
					name: 'semester',
					displayName: 'Semester',
					enableCellEdit: true,
					minWidth: 150
				},
				{
					name: 'proposedDate',
					displayName: 'Proposed Date',
					enableCellEdit: true,
					visible: false,
					minWidth: 200
				},
			],
			onRegisterApi: function (gridApi) {
				//Used for Editing Projects rmart080
				$scope.projectFilter = function () {
					vm.gridApi.grid.refresh();
				};

				//Filter for projects' super search
				vm.singleFilter = function (renderableRows) {

					//Makes sure the table's been initialized, otherwise it'll crash due to using an
					//undefine variable vm.projectFilterValue
					if (typeof vm.projectFilterValue !== 'undefined') {
						var splitInput = vm.projectFilterValue.split(" ");
						var match = false;

						for (var i = 0; i < splitInput.length; i++) {
							var matcher = new RegExp(splitInput[i]);

							renderableRows.forEach(function (row) {
								match = false;
								['title', 'description', 'owner_email', 'owner_name', 'owner_rank', 'disciplines', 'firstSemester', 'maxStudents', 'goals',
									'keyElements', 'researchIssues', 'meetingTime', 'advisors', 'sponsors', 'majPrepInt',
									'faculty', 'mentor', 'addedStudents', 'members', 'contact', 'edited', 'old_project',
									'github_url', 'archive_url', 'term', 'reqskillItem', 'proposedDate', 'semester'
								].forEach(function (name) {
									try {
										if (row.entity[name].match(new RegExp(matcher, "i"))) {
											match = true;
										}
									} catch (err) {
										console.log(err)
									}
								});
								if (!match) {
									row.visible = false;
								}
							});
						}
					}

					return renderableRows;
				};

				var location = 0;
				vm.gridApi = gridApi;
				vm.gridApi.grid.registerRowsProcessor(vm.singleFilter, 200);


				gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
					for (; location < vm.gridOptionsProjects.data.length; location++) {
						if (vm.gridOptionsProjects.data[location]._id === rowEntity._id) {
							break;
						}

					}
					vm.gridOptionsProjects.data[location].colDef = newValue;
					var projUpdate = vm.gridOptionsProjects.data[location];

					projUpdate.colDef = newValue;
					ProjectService.editProject(projUpdate, projUpdate._id).then(function (success) {
						console.log("Successfully Edited Project");
						//projectrefresh();



					});

					//checks if the title/name of the project was changed
					if (colDef.name == "title") {

						vm.allusers.forEach(function (user) {

							//Checks all the students that were in the just-updated project
							if (user.project == oldValue) {

								//DO CODE HERE, YOU HAVEN'T TOUCHED THISSSSSSSSSSSSSS
								user.project = newValue;
								User.update({
									user: user
								});
							}
						});
					}
					//VIP-205
					//rpach023 resetting location to be able to update multiple times without refreshing..
					location = 0;

				});
			}
		};

		vm.getSelectedProjRowDelete = function () {
			var projToDelete = vm.gridApi.selection.getSelectedRows();





			return projToDelete;
		};

		vm.getSelectedProjRowMod = function () {
			var projToMod = vm.gridApi.selection.getSelectedRows();



			return projToMod[0];
		};


		vm.saveProjectState = function () {
			adminService.getAdminSettings().then(function (data) {
				var state = data;
				state.projectState = vm.gridApi.saveState.save();


				adminService.saveAdminSettings(state).then(function (data) {
					console.log("SAVE SUCCESS")
				})
			});




		};
		$scope.state = {};
		vm.restoreProjectState = function () {
			adminService.getAdminSettings().then(function (data) {
				var state = data;
				for (var i = 0; i < state.projectState.columns.length; i++) {
					state.projectState.columns[i].sort = {};
					state.projectState.columns[i].filters = [{}];
				}

				$scope.state = state.projectState;
				vm.gridApi.saveState.restore($scope, $scope.state);

			});
			console.log("LOAD SUCCESS");

		};


		reviewStudentAppService.loadAllProjects().then(function (data) {
			vm.gridOptionsProjects.data = data;

		});


		/** User Story FA18 | VIP-39, VIP-139, VIP-140, VIP-147, VIP-121,
		 *  VIP-140, VIP-170, VIP-169, VIP-134, Rmart080(User Tab)
		 * 
		 * This new table replaces the old Semester tab, it includes custom filters,
		 * the base for super search, refresh filters, inline edits, while
		 * using existing functions for adding new data or eliminating data.
		 * 
		 * */
		vm.gridOptionsSemester = {

			enableRowHeaderSelection: true,
			enableFullRowSelection: false,
			enableRowSelection: true,
			enableSelectAll: true,
			multiSelect: true,
			saveFocus: false,
			saveScroll: true,
			saveGroupingExpandedStates: true,
			enableFiltering: true,
			enableGridMenu: true,
			enableCellEditOnFocus: true,


			columnDefs: [{
					name: '_id',
					enableCellEdit: false,
					visible: false
				},
				{
					name: 'name',
					displayName: 'Semester',
					enableCellEdit: true,
					minWidth: 200
				},
				{
					name: 'start',
					displayName: 'Start Date',
					enableCellEdit: true,
					minWidth: 200,
					type: 'date',
					cellFilter: 'date:"yyyy-MM-dd"',
					filterCellFiltered: true
				},
				{
					name: 'end',
					displayName: 'End Date',
					enableCellEdit: true,
					minWidth: 200,
					type: 'date',
					cellFilter: 'date:"yyyy-MM-dd"',
					filterCellFiltered: true
				},

				//rpach
				//VIP-202 Checkboxes instead of Dropdowns.
				{
					name: 'status.currentSemester',
					displayName: 'Currrent Semester',
					minWidth: 30,
					width: '10%',
					type: 'boolean',
					cellTemplate: '<div ><input type="checkbox" ng-checked="{{row.entity.status.currentSemester}}" ng-model="row.entity.status.currentSemester" ></div>'
				},

				{
					name: 'status.viewable',
					displayName: 'Viewable',
					minWidth: 20,
					width: '10%',
					type: 'boolean',
					cellTemplate: '<div ><input type="checkbox" ng-checked="{{row.entity.status.viewable}}" ng-model="row.entity.status.viewable" ></div>'
				},
				//rpach
				/*{
					name: 'status.currentSemester', displayName: 'Current Semester', minWidth: 150, editableCellTemplate: 'ui-grid/dropdownEditor', width: '20%',
					editDropdownValueLabel: 'current', editDropdownOptionsArray: [
						{ id: true, current: true },
						{ id: false, current: false }
					]
				},
				{
					name: 'status.viewable', displayName: 'Viewable', minWidth: 100, editableCellTemplate: 'ui-grid/dropdownEditor', width: '20%',
					editDropdownValueLabel: 'viewable', editDropdownOptionsArray: [
						{ id: true, viewable: true },
						{ id: false, viewable: false }
					]
				},

				*/

				{
					name: 'status.openForProposal',
					displayName: 'Proposable',
					minWidth: 20,
					width: '10%',
					type: 'boolean',
					cellTemplate: '<div ><input type="checkbox" ng-checked="{{row.entity.status.openForProposal}}" ng-model="row.entity.status.openForProposal" ></div>'
				},

				{
					name: 'status.openForApply',
					displayName: 'Applicable',
					minWidth: 20,
					width: '10%',
					type: 'boolean',
					cellTemplate: '<div><input type="checkbox" ng-checked="{{row.entity.status.openForApply}}" ng-model="row.entity.status.openForApply" ></div>'
				},

				/*
				{
					name: 'status.openForApply', displayName: 'Applicable', minWidth: 100, editableCellTemplate: 'ui-grid/dropdownEditor', width: '20%',
					editDropdownValueLabel: 'openForApply', editDropdownOptionsArray: [
						{ id: true, openForApply: true },
						{ id: false, openForApply: false }
					]
				},
				*/
				{
					name: 'status.defaultSemester',
					displayName: 'Default',
					minWidth: 20,
					width: '10%',
					type: 'boolean',
					cellTemplate: '<div><input type="checkbox" ng-checked="{{row.entity.status.defaultSemester}}" ng-model="row.entity.status.defaultSemester"></div>'

				},

				/*
				{
					name: 'status.defaultSemester', displayName: 'Default', minwidth: 100, editableCellTemplate: 'ui-grid/dropdownEditor', width: '20%',
					editDropdownValueLabel: 'defaultSemester', editDropdownOptionsArray: [
						{ id: true, defaultSemester: true},
						{ id: false, defaultSemester: false}
					]
				}

				*/



			],
			onRegisterApi: function (gridApi) {
				//Used for Editing Semesters rmart080

				$scope.semFilter = function () {
					vm.gridApi.grid.refresh();
				};

				//Filter for semester's super search
				vm.singleFilter = function (renderableRows) {

					//Makes sure the table's been initialized, otherwise it'll crash due to using an
					//undefine variable vm.semFilterValue
					if (typeof vm.semFilterValue !== 'undefined') {
						var splitInput = vm.semFilterValue.split(" ");
						var match = false;

						for (var i = 0; i < splitInput.length; i++) {
							var matcher = new RegExp(splitInput[i]);

							renderableRows.forEach(function (row) {
								match = false;
								['name', 'start', 'end'].forEach(function (name) {
									try {
										if (row.entity[name].match(new RegExp(matcher, "i"))) {
											match = true;
										}
									} catch (err) {
										console.log(err)
									}
								});
								if (!match) {
									row.visible = false;
								}
							});
						}
					}

					return renderableRows;
				};

				var location = 0;
				vm.gridApi = gridApi;
				vm.gridApi.grid.registerRowsProcessor(vm.singleFilter, 200);

				gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
					for (; location < vm.gridOptionsSemester.data.length; location++) {
						if (vm.gridOptionsSemester.data[location]._id === rowEntity._id) {
							break;
						}

					}

					//question mark




					var semUpdate = vm.gridOptionsSemester.data[location];

					semUpdate.colDef = newValue;
					ProjectService.editTerm(semUpdate, semUpdate._id).then(function (success) {
						console.log("Successfully Edited Semester");
						//semesterchange_msg();
						resetSemSettings();

						//If the value on the row that was changed was "defaultSemester",
						//check if it was changed to true. If so, changed any other one that is true to false.
						if (semUpdate.status.defaultSemester) {
							defaultSemesterCheck(semUpdate);
							loadDefaultSemester();
						} else {
							var noDefaultSemFlag = true;
							vm.terms.forEach(function (term, index) {
								if (term.status.defaultSemester) {
									noDefaultSemFlag = false;
								}
							})

							if (noDefaultSemFlag) {
								semUpdate.status.defaultSemester = true;
								ProjectService.editTerm(semUpdate, semUpdate._id).then(function (success) {
									resetSemSettings();
								})
								vm.terms.forEach(function (term, index) {
									if (term.status.defaultSemester && !(semUpdate._id == term._id)) {
										term.status.defaultSemester = false;
										ProjectService.editTerm(term, term._id).then(function (success) {

											resetSemSettings();
											return;
										})
									}
								})
							}
							loadDefaultSemester();

						}

						location = 0;



					});

					ProjectService.getCurrentSemester().then(function (data) {
						if (data) {
							vm.currentSemesters = data;
						}
						vm.currentSemesters = vm.currentSemesters.join(", ");
						document.getElementById("currentSemester").innerHTML = "Current Semesters: " + vm.currentSemesters;

					});

				});
			},

		};


		//-------------------------------------End of gridOptionsSemester--------------------------------------//

		//Used in conjunction with existing delete function to delete rows UiGrid rmart080
		vm.getSelectedSemRow = function () {
			var semToDelete = vm.gridApi.selection.getSelectedRows();





			return semToDelete;
		}





		reviewStudentAppService.loadTerms().then(function (data) {
			vm.gridOptionsSemester.data = data;



		});


		vm.saveSemesterState = function () {
			adminService.getAdminSettings().then(function (data) {
				var state = data;
				state.semesterState = vm.gridApi.saveState.save();

				adminService.saveAdminSettings(state).then(function (data) {
					console.log("SAVE SUCCESS")
				})
			});




		};
		$scope.state = {};
		vm.restoreSemesterState = function () {
			adminService.getAdminSettings().then(function (data) {
				var state = data;
				for (var i = 0; i < state.semesterState.columns.length; i++) {
					state.semesterState.columns[i].sort = {};
					state.semesterState.columns[i].filters = [{}];
				}

				$scope.state = state.semesterState;
				vm.gridApi.saveState.restore($scope, $scope.state);

			});
			console.log("LOAD SUCCESS");

		};

		vm.currentSwitchStatus;
		vm.proposableSwitchStatus;
		vm.viewableSwitchStatus;
		vm.applicableSwitchStatus;
		vm.defaultSwitchStatus;
		vm.simulateQuery = false;
		vm.isDisabled = false;

		//Column sorting
		$scope.orderByFieldApp = ''
		$scope.reverseSortApp = false;
		$scope.orderByFieldProj = ''
		$scope.reverseSortProj = false;
		$scope.orderByFieldSem = ''
		$scope.reverseSortSem = false;
		// list of `state` value/display objects
		vm.querySearch = querySearch;
		vm.selectedItemChange = selectedItemChange;
		vm.searchTextChange = searchTextChange;

		function querySearch(query) {
			var results = query ? vm.filteredusers.filter(createFilterFor(query)) : vm.filteredusers,
				deferred;
			if (self.simulateQuery) {
				deferred = $q.defer();
				$timeout(function () {
					deferred.resolve(results);
				}, Math.random() * 1000, false);
				return deferred.promise;
			} else {
				return results;
			}
		}



		function searchTextChange(text) {
			$log.info('Text changed to ' + text);
		}


		function updateSelectedSemesterQueries(selectedSemester) {
			$scope.query14 = selectedSemester;
			$scope.queryp5 = selectedSemester;
			$scope.queryC3 = selectedSemester;
		}

		$scope.semesterFilter = function (myUser) {
			return (myUser.semester === $scope.query14 && myUser.userType === 'Student') || (myUser.userType !== 'Student');
		};

		function selectedItemChange(item) {
			$log.info('Item changed to ' + JSON.stringify(item));
		}
		/*User Story: FA18 | VIP-175, mvale080 (added showSkillMaint boolean)
			Below are functions that control what is visible in the admin panel. showSkillMaint was added to control when the Skill Panel is shown and when it is hidden.
		*/
		function routeAdminMaint() {
			$scope.showUserMaint = false;
			$scope.showSemesterMaint = false;
			$scope.showProjectMaint = false;
			$scope.showAdminPage = true;
			$scope.showCoursePage = false;
			$scope.showSkillMaint = false;
		}

		function routeUserMaint() {
			$scope.showUserMaint = true;
			$scope.showSemesterMaint = false;
			$scope.showProjectMaint = false;
			$scope.showAdminPage = false;
			$scope.showCoursePage = false;
			$scope.showSkillMaint = false;
			userrefresh();
			vm.restoreUserState();
		}

		function routeProjectMaintenance() {
			$scope.showUserMaint = false;
			$scope.showSemesterMaint = false;
			$scope.showProjectMaint = true;
			$scope.showAdminPage = false;
			$scope.showCoursePage = false;
			$scope.showSkillMaint = false;
			projectrefresh();
			vm.restoreProjectState();
		}

		function routeSemesterMaintenance() {
			$scope.showUserMaint = false;
			$scope.showSemesterMaint = true;
			$scope.showProjectMaint = false;
			$scope.showAdminPage = false;
			$scope.showCoursePage = false;
			$scope.showSkillMaint = false;
			semesterrefresh();
			vm.restoreSemesterState();
		}

		function routeCourseMaintenance() {
			$scope.showUserMaint = false;
			$scope.showSemesterMaint = false;
			$scope.showProjectMaint = false;
			$scope.showAdminPage = false;
			$scope.showCoursePage = true;
			$scope.showSkillMaint = false;
			courserefresh();
			vm.restoreCourseState();
		}

		function routeSkillMaint() {
			$scope.showUserMaint = false;
			$scope.showSemesterMaint = false;
			$scope.showProjectMaint = false;
			$scope.showAdminPage = false;
			$scope.showCoursePage = false;
			$scope.showSkillMaint = true;
			skillrefresh();
			vm.restoreSkillsState();
		}
		ProfileService.loadProfile().then(function (data) {
			if (data) {
				$scope.done = true;
				vm.cuser = data;
				var profile = data;
				if (profile.userType != "Pi/CoPi") {
					//$location.path("/");
					$location.path('/').replace();
				}
				if (profile.selectedSemester) {
					reviewStudentAppService.getTerm(profile.selectedSemester).then(function (term) {
						updateSelectedSemesterQueries(term.name);
						vm.defaultSemester;
						loadDefaultSemester();

					})
				}
			} else {
				$scope.done = true;
				$window.sessionStorage.setItem('lr', 'adminpanel');
				$location.path('login').replace();
			}
		});

		vm.currentSemesters;
		vm.users; //Confirmed users only (Email is verified)
		vm.allusers; //All confirmed and unconfirmed users
		vm.unconfirmedusers; //Unconfirmed users (Email is not verified)
		vm.filteredusers; //filteredusers affected by filter function
		vm.projects; //Projects that are active
		vm.courses; // Course list
		vm.currentSem;
		vm.currentSemesterName;
		vm.cStatus;
		vm.vStatus;
		vm.pStatus;
		vm.aStatus;
		vm.defaultSemStatus;
		// vm.currentSemesterName = [];// TODO Remove if not needed
		vm.filterUsers = filterUsers;
		vm.currentuserview;
		vm.currentview = currentview;
		vm.deleteUser = RemoveUser;
		vm.changeUserType = changeUserType;
		vm.ConfirmUser = ConfirmUser;
		vm.RejectUser = RejectUser;
		vm.seed = seed;
		// userstory #1172
		vm.exportData = exportData;
		vm.tabledata = null;
		// User story #1176
		vm.allprojects; //All projects
		vm.filteredprojects;
		vm.tabledata_p = null;
		// User story #1300
		vm.editingUser;
		vm.editingUserOrig;
		// Used for filtering of ranks in add and editing user modal
		vm.addRanks = [];
		vm.editRanks = [];
		// User story #1313
		vm.editingProject;
		vm.editingProjOrigMembers;
		// User story #1328
		vm.editingProjOrigTitle;
		vm.editingProjNewTitle;
		// User story #1346
		vm.courseFiles;
		vm.semesterToBeDeleted;
		vm.emailSemester;

		vm.printFriendlyView = false;
		vm.printFriendlyViewButtonText1 = "LIST VIEW";
		vm.printFriendlyViewfunc = printFriendlyViewfunc;

		//Out of scope functions
		vm.userTypeChange = userTypeChange;
		vm.userChange = userChange;
		vm.userinUnconfirmedfunc = userinUnconfirmedfunc;

		//For out of scope variables:
		vm.userinusertype;
		vm.userinprojects;
		vm.usertypeinusertype;
		vm.projectinprojects;
		vm.userinunconfirmed;
		vm.AddTerms = AddTerms;
		vm.selectUser = function (user) {
			$scope.Selecteduserconfirm = user
		}

		vm.currentUser = function (user) {
			vm.cuser = user;
		}
		vm.currentProject = function (project) {
			vm.cproject = project;
		}
		vm.currentTerm = function (term) {
			vm.cterm = term;
			if (term) {
				vm.cStatus = term.status.currentSemester;
				vm.vStatus = term.status.viewable;
				vm.pStatus = term.status.openForProposal;
				vm.aStatus = term.status.openForApply;
				vm.defaultSemStatus = term.status.defaultSemester;
				if (vm.currentSwitchStatus == null) {
					vm.currentSwitchStatus = term.status.currentSemester;
				}
				if (vm.viewableSwitchStatus == null) {
					vm.viewableSwitchStatus = term.status.viewable;
				}
				if (vm.proposableSwitchStatus == null) {
					vm.proposableSwitchStatus = term.status.openForProposal;
				}
				if (vm.applicableSwitchStatus == null) {
					vm.applicableSwitchStatus = term.status.openForApply;
				}
				if (vm.defaultSwitchStatus == null) {
					vm.defaultSwitchStatus = term.status.defaultSemester;
				}

			}
		}
		vm.sw = ChangeUserProject;
		vm.sc = ClearProject;

		//Joe's User Story
		vm.se = ChangeProjectStatus;
		vm.nw = ChangeTermStatus;

		vm.csf = currentSwitch;
		vm.vsf = viewableSwitch;
		vm.asf = applicableSwitch;
		vm.psf = proposableSwitch;
		vm.dsf = defaultSwitch;
		vm.msc = makeSemesterChanges;
		vm.cns = createNewSemester;
		vm.ds = deleteSemester;
		vm.defsb = setDefaultSemester;
		vm.dsb = delSemButton;
		vm.esb = editSemButton;
		vm.rss = resetSemSettings;
		vm.pi = printInfo;
		vm.epo = emailProductOwners;
		//User Story: FA18 | VIP-181, mvale080 (added definitions for use in the scope)
		vm.dskill = DeleteSkill;
		vm.dskillb = SkillDeleteButton;
		vm.rskills = resetSkiSettings;
		vm.ses = function (semester) {
			vm.emailSemester = semester.name;
		}

		function printFriendlyViewfunc() {
			vm.printFriendlyView = !vm.printFriendlyView;
			if (!vm.printFriendlyView) {
				vm.printFriendlyViewButtonText1 = "LIST VIEW";
			} else {
				vm.printFriendlyViewButtonText1 = "TABLE VIEW";
			}
		}

		vm.siteSummaryItems;
		vm.buildSiteSummary = function () {
			vm.siteSummaryItems = [];
			var total, total1, total2, total3, tooltip, tooltip1, tooltip2, tooltip3, total4, tooltip4, total5, tooltip5;
			var bcR = "style={'background-color':'red'}";
			var bcG = "style={'background-color':'goldenrod'}";

			//vm.siteSummaryItems.push({summary:"Projects in the system 2", badgecount: 0,  badgecolor: bcG});
			// Projects summary
			if (vm.allprojects != null) {
				total = 0;
				vm.allprojects.forEach(function (proj) {
					total += 1;
				});
				vm.siteSummaryItems.push({
					summary: "Projects in the system",
					badgecount: total,
					badgecolor: bcG
				});
			}
			if (vm.projects != null) {
				tooltip = "";
				total = 0;
				vm.projects.forEach(function (proj) {
					if (proj.status == 'pending') {
						tooltip += "Project: " + proj.title + "\n";
						total += 1;
					}
				});
				vm.siteSummaryItems.push({
					summary: "Projects pending approval",
					badgecount: total,
					badgecolor: bcR,
					tooltip: tooltip
				});
			}
			if (vm.projects != null) {
				tooltip = "";
				total = 0;
				total1 = 0;
				vm.projects.forEach(function (proj) {
					total += 1;
					if (proj.owner_name == null) {
						tooltip += "Project: " + proj.title + "\n";
						total1 += 1;
					}
				});
				vm.siteSummaryItems.push({
					summary: "Projects active",
					badgecount: total,
					badgecolor: bcG
				});
				vm.siteSummaryItems.push({
					summary: "Projects active without owner",
					badgecount: total1,
					badgecolor: bcR,
					tooltip: tooltip
				});
			}

			// Terms summary
			// No current semester selected
			if (vm.terms != null) {
				total = 0;
				total1 = 0;
				vm.terms.forEach(function (term, index) {
					total += 1;
					if (term.status.currentSemester) {
						total1 += 1;
					}
				});
				if (total != 0 && total == total1) {
					vm.siteSummaryItems.push({
						summary: "No current semester selected",
						badgecount: 1,
						badgecolor: bcR
					});
				}
			}

			// Users summary
			if (vm.users != null) {
				tooltip = "";
				tooltip1 = "";
				tooltip2 = "";
				tooltip3 = "";
				tooltip4 = "";
				tooltip5 = "";
				total = 0;
				total1 = 0;
				total2 = 0;
				total3 = 0;
				total4 = 0;
				total5 = 0;
				vm.allusers.forEach(function (user, index) {
					total += 1; // Users in the system
					if (user.project == null || user.rank == null || user.department == null || user.college == null) {
						tooltip1 += "User: " + user.firstName + " " + user.lastName + "\n";
						total1 += 1;
					}
					if (user.userType == "Student" && (user.semester == null || user.semester != vm.defaultSemester)) {
						tooltip2 += "User: " + user.firstName + " " + user.lastName + "\n";
						total2 += 1;
					}
					if (user.userType == null || user.pantherID == null) {
						tooltip3 += "User: " + user.firstName + " " + user.lastName + "\n";
						total3 += 1;
					}
					if (!user.piApproval) {
						tooltip4 += "User: " + user.firstName + " " + user.lastName + "\n";
						total4 += 1;
					}
					if (user.userType == "Student" && user.course == null) {
						tooltip5 += "User: " + user.firstName + " " + user.lastName + "\n";
						total5 += 1;
					}
				});
				vm.siteSummaryItems.push({
					summary: "Users in the system",
					badgecount: total,
					badgecolor: bcG
				});
				vm.siteSummaryItems.push({
					summary: "Users with no project, rank, department, or college",
					badgecount: total1,
					badgecolor: bcR,
					tooltip: tooltip1
				});
				vm.siteSummaryItems.push({
					summary: "Students with no semester or not in default semester",
					badgecount: total2,
					badgecolor: bcR,
					tooltip: tooltip2
				});
				vm.siteSummaryItems.push({
					summary: "Students in no course",
					badgecount: total5,
					badgecolor: bcR,
					tooltip: tooltip5
				});
				vm.siteSummaryItems.push({
					summary: "Users with no user type or panther ID",
					badgecount: total3,
					badgecolor: bcR,
					tooltip: tooltip3
				});
				vm.siteSummaryItems.push({
					summary: "Users pending PI approval",
					badgecount: total4,
					badgecolor: bcR,
					tooltip: tooltip4
				});
			}
			if (vm.users != null) {
				total = 0;
				vm.users.forEach(function (user, index) {
					total += 1;
				});
				vm.siteSummaryItems.push({
					summary: "Users Confirmed (email verified)",
					badgecount: total,
					badgecolor: bcG
				});
			}
			if (vm.users != null) {
				tooltip = "";
				total = 0;
				vm.unconfirmedusers.forEach(function (user, index) {
					tooltip += "User: " + user.firstName + " " + user.lastName + "\n";
					total += 1;
				});
				vm.siteSummaryItems.push({
					summary: "Users Unconfirmed (email not verified)",
					badgecount: total,
					badgecolor: bcR,
					tooltip: tooltip
				});
			}

			if (vm.skills != null) {
				tooltip = "";
				total = 0;
				vm.skills.forEach(function (skill) {
					if (skill.Approved == false) {
						tooltip += "Skills: " + skill.skill + "\n";
						total += 1;
					}
				});
				vm.siteSummaryItems.push({
					summary: "Skills needing approval",
					badgecount: total,
					badgecolor: bcR
				});
			}

		}

		function emailProductOwners() {
			var users;
			var productOwners = [];
			var ownersEmailed = "The following Product Owners have been notified about the new " + vm.emailSemester + " semester: <br>";

			adminService.loadAllUsers().then(function (data) {
				users = data;
				users.forEach(function (user) {
					if (user.userType == 'Staff/Faculty' || user.userType == 'Pi/CoPi') {
						productOwners.push({
							name: user.firstName + " " + user.lastName,
							email: user.email
						});
					}
				})

				productOwners.forEach(function (owner) {
					var email_msg = {
						recipient: owner.email,
						text: "The " + vm.emailSemester +
							" semester is now open for project proposals. If you are interested, you can do so now.",
						subject: "New Semester added to FIU VIP"
					};

					ownersEmailed = ownersEmailed + "- " + owner.name + "<br>";
					User.nodeEmail(email_msg);
				})

				var admin_email_msg = {
					recipient: vm.adminSettings.current_email,
					text: ownersEmailed,
					subject: "Product Owners Emailed"
				};
				User.nodeEmail(admin_email_msg);
			});
		}

		function printInfo() {
			console.log("vm.cStatus: " + vm.cStatus);
			console.log("vm.vStatus: " + vm.vStatus);
			console.log("vm.pStatus: " + vm.pStatus);
			console.log("vm.aStatus: " + vm.aStatus);
			console.log("vm.defaultSemStatus: " + vm.defaultSemStatus);

			console.log("$scope.cStatus: " + $scope.cStatus);
			console.log("$scope.vStatus: " + $scope.vStatus);
			console.log("$scope.pStatus: " + $scope.pStatus);
			console.log("$scope.aStatus: " + $scope.aStatus);
			console.log("$scope.defaultSemStatus: " + $scope.defaultSemStatus);
		}

		vm.usertype = ['Staff/Faculty', 'Pi/CoPi', 'Student', 'Undefined'];
		//Joe's User Story
		vm.status = ['Active', 'Disabled'];
		vm.active = ['Active', 'Disabled'];
		vm.open = ['Open', 'Closed'];
		vm.getProjectTitle = function (email) {
			if (email) {
				if (vm.projects) {
					var results = vm.projects.filter(function (project) {
						return project.members.includes(email)
					});
					if (results.length >= 1) {
						return "Member of " + results[0].title + ".";
					} else {
						return "Hasn't joined any project!";
					}
				}
			}
		};

		vm.changeEmailSignature = function () {
			vm.savesetting();
		};

		vm.changeProjectDeadlineDates = function () {
			vm.savesetting();
		};

		// User Story 1345

		// Add a course
		vm.addCourse = function () {
			if (!$scope.addNewCourseInputSubject || !$scope.addNewCourseInputNumber || !$scope.addNewCourseInputSection || !$scope.addNewCourseInputID ||
				!$scope.addCourseTerm || $scope.addNewCourseInputSubject.length < 3 || $scope.addNewCourseInputNumber.length < 4) {
				var errMsg = "";
				if (!$scope.addNewCourseInputSubject)
					errMsg += "\tSubject Missing\n";
				else if ($scope.addNewCourseInputSubject.length < 3)
					errMsg += "\tSubject is not 3 Character Code\n";
				if (!$scope.addNewCourseInputNumber)
					errMsg += "\tNumber Missing\n";
				else if ($scope.addNewCourseInputNumber.length < 4)
					errMsg += "\tNumber is not 4 Digit Number\n";
				if (!$scope.addNewCourseInputSection)
					errMsg += "\tSection Missing\n";
				if (!$scope.addNewCourseInputID)
					errMsg += "\tID Missing\n";
				if (!$scope.addCourseTerm)
					errMsg += "\tSemester Missing\n";

				swal({
					title: "Error",
					text: errMsg,
					type: "error",
					confirmButtonText: "Continue",
					allowOutsideClick: true,
					timer: 10000,
				}, function () {});
			} else {
				// test if duplicate exists
				var courseName = $scope.addNewCourseInputSubject + ' ' + $scope.addNewCourseInputNumber + " - " + $scope.addNewCourseInputSection;
				var courseFullName = courseName + ' ' + $scope.addCourseTerm.name + ' (' + $scope.addNewCourseInputID + ')';
				var found = false;
				vm.courses.forEach(function (course) {
					if (course.fullName == courseFullName)
						found = true;
				});
				if (!found) { // Create the new course and save it
					var newCourse = {
						name: courseName,
						subject: $scope.addNewCourseInputSubject,
						number: $scope.addNewCourseInputNumber,
						section: $scope.addNewCourseInputSection,
						course_id: $scope.addNewCourseInputID,
						semester: $scope.addCourseTerm.name,
						fullName: courseFullName
					};

					if ($scope.addNewCourseInputTitle != "")
						newCourse["title"] = $scope.addNewCourseInputTitle;

					adminService.addCourse(newCourse).then(function (data) {
						vm.courses.push(data);

						// Notify User of Added Course
						swal({
							title: "Success",
							text: "Course " + courseFullName + " has been added to the database",
							type: "success",
							confirmButtonText: "Continue",
							allowOutsideClick: true,
							timer: 10000,
						}, function () {});
						adminService.loadCourses().then(function (data) {
							vm.gridOptionsCourse.data = data;
							courserefresh();
						})
					});
					// Clear Input fields
					$scope.addNewCourseInputSubject = "";
					$scope.addNewCourseInputNumber = "";
					$scope.addNewCourseInputSection = "";
					$scope.addNewCourseInputID = "";
					$scope.addNewCourseInputTitle = "";
					$scope.addCourseTerm = "";
				}
			}
		};

		// Remove a course
		vm.removeCourse = function (removingCourse) {
			var courseFullName = removingCourse.fullName;
			adminService.deleteCourse(removingCourse._id).then(function (data) {
				if (data.message == "successfully deleted!") { // http delete request was successful
					// Remove from courses list
					vm.courses.forEach(function (course, index) {
						if (course.fullName == courseFullName)
							vm.courses.splice(index, 1);
					});

					// Go through users and remove them from the deleted course
					vm.allusers.forEach(function (user, index) {
						if (user.course == courseFullName) {
							user.course = null;
							User.update({
								user: user
							});
						}
					});
					// Refresh User panel
					adminService.loadCourses().then(function (data) {
						vm.gridOptionsCourse.data = data;
						courserefresh();
					});


					// Clears the course file list & resets input
					vm.clearCourseFiles();

					// Notify User of Deleted Course
					swal({
						title: "Success",
						text: "Course " + courseFullName + " has been deleted from the database",
						type: "success",
						confirmButtonText: "Continue",
						allowOutsideClick: true,
						timer: 10000,
					}, function () {});
				}
			});

			vm.tabledata = JSON.stringify(vm.filteredusers);
			vm.tabledata = eval(vm.tabledata);
		};

		// User Story #1362

		// Populate the edit course modal with current course info
		vm.editCourse = function (course) {
			vm.editingCourse = course;
			vm.editingCourseOrig = {
				name: course.name,
				fullName: course.fullName,
			};

			// Set initial values of input to be current course values
			$scope.editCourseInputSubject = vm.editingCourse.subject;
			$scope.editCourseInputNumber = vm.editingCourse.number;
			$scope.editCourseInputSection = vm.editingCourse.section;
			$scope.editCourseInputID = vm.editingCourse.course_id;
			$scope.editCourseInputTitle = vm.editingCourse.title;
			$scope.editCourseTerm = vm.editingCourse.semester;
		};

		// Update the editing course with new information
		vm.saveChangesCourse = function () {
			// Check if required information is missing
			if ($scope.editCourseInputSubject && $scope.editCourseInputNumber && $scope.editCourseInputSection && $scope.editCourseInputID) {
				// Confirm that the changed course does not become a copy of an existing course
				var newFullName = $scope.editCourseInputSubject + ' ' + $scope.editCourseInputNumber + ' - ' + $scope.editCourseInputSection + ' ' +
					$scope.editCourseTerm.name + ' (' + $scope.editCourseInputID + ')';
				var found = false;
				vm.courses.forEach(function (course) {
					if (course.fullName == newFullName)
						found = true;
				});
				if (!found) {
					updateCourse();
				} else {
					document.getElementById('editCourseMessage').innerHTML = 'Error: Course: ' + newFullName + ' already exists';
				}
			} else {
				document.getElementById('editCourseMessage').innerHTML = 'Error: Missing required information';
			}
		}

		// Updates the course
		function updateCourse() {
			// Update editingCourse
			vm.editingCourse.subject = $scope.editCourseInputSubject;
			vm.editingCourse.number = $scope.editCourseInputNumber;
			vm.editingCourse.section = $scope.editCourseInputSection;
			vm.editingCourse.course_id = $scope.editCourseInputID;
			if (vm.editingCourse.title)
				vm.editingCourse.title = $scope.editCourseInputTitle;
			else
				vm.editingCourse['title'] = $scope.editCourseInputTitle;

			vm.editingCourse.name = vm.editingCourse.subject + ' ' + vm.editingCourse.number + ' - ' + vm.editingCourse.section;
			vm.editingCourse.fullName = vm.editingCourse.name + ' ' + vm.editingCourse.semester + ' (' + vm.editingCourse.course_id + ')';

			// Send PUT request
			adminService.updateCourse(vm.editingCourse, vm.editingCourse._id).then(function (data) {
				if (data) {
					if (data.success) {
						document.getElementById('editCourseMessage').innerHTML = 'Editing course was successful';
						// Update the users that are associated with the given course
						if (vm.editingCourseOrig.fullName != vm.editingCourse.fullName)
							updateCourseUsers();
					} else {
						document.getElementById('editCourseMessage').innerHTML = 'Error: HTTP request failed';
						// Refresh course panel
						vm.courses = eval(vm.courses);
					}
				} else { // http error
					document.getElementById('editCourseMessage').innerHTML = 'Error: HTTP response not received';
					// Refresh course panel
					vm.courses = eval(vm.courses);
				}
			});
		};

		// Update the course value for users in the editing course
		function updateCourseUsers() {
			vm.allusers.forEach(function (user) {
				if (user.course == vm.editingCourseOrig.fullName) {
					user.course = vm.editingCourse.fullName;
					// Update the user
					User.update({
						user: user
					});
				}
			});
			// Refresh user panel
			vm.tabledata = JSON.stringify(vm.filteredusers);
			vm.tabledata = eval(vm.tabledata);
		};

		// User Story #1346

		vm.addCourseFileName;
		vm.addCourseData; // Holds the parsed TXT data after onchanged event fires

		// Parse the TXT file using File API
		function handleFile(e) {
			if (document.getElementById('courseFileInput').value) {
				var files = e.target.files,
					fileSource = files[0];
				var reader = new FileReader();
				reader.onload = function (e) {
					vm.addCourseData = parseTXT(e.target.result, document.getElementById('courseFileInput').value.replace(/.*[\/\\]/, ''));
				};
				reader.readAsText(fileSource);

				// Read fileName and check if existing course exists to set as default course
				vm.addCourseFileName = document.getElementById('courseFileInput').value.replace(/.*[\/\\]/, '');
				matchOrCreateCourse(vm.addCourseFileName);
			}
		};
		document.getElementById('courseFileInput').addEventListener('change', handleFile, false);

		//Adds files retrieved from the server 
		vm.getCourseFilesFromServer = function () {
			vm.clearCourseFiles();
			var courseFiles = adminService.getCourseFiles().then(function (data) {
				data.forEach(function (file) {
					vm.addCourseData = parseTXT(file.content, file.fileName);
					vm.addCourseFileName = file.fileName;
					matchOrCreateCourse(vm.addCourseFileName);
					vm.addCourseFile()
				})
			});
		}

		// Updates the course select box with best fit course given the file name
		function matchOrCreateCourse(file) {
			try {
				var currentTerms = [],
					currentTermIndex = -1;
				vm.terms.forEach(function (term, index) {
					if (term.status.currentSemester) {
						currentTerms.push(term.name);
						if (currentTermIndex == -1)
							currentTermIndex = index;
					}
				});

				// Start with cleared selection
				document.getElementById('syncCourseSelect').selectedIndex = -1;
				// Hide add course table
				$scope.showAddCourse = false;
				//$scope.$digest();

				// Try to match a segment of the file name with a course from a current semester
				var found = false;
				var selectIndex = -1;
				var indexQuality = -1;
				file = file.toUpperCase();
				vm.courses.forEach(function (course, index) {
					currentTerms.forEach(function (cTerm) {
						if (course.semester == cTerm) {
							if (file.indexOf(course.number) != -1 &&
								file.indexOf(course.subject.toUpperCase()) != -1 &&
								file.indexOf(course.section.toUpperCase()) != -1) {

								selectIndex = index;
								indexQuality = 3;
							} else if (file.indexOf(course.number) != -1 && file.indexOf(course.subject.toUpperCase()) != -1) {
								if (indexQuality < 2) {
									selectIndex = index;
									indexQuality = 2;
								}
							} else if (file.indexOf(course.number) != -1) {
								if (indexQuality < 1) {
									selectIndex = index;
									indexQuality = 1;
								}
							} else if (file.indexOf(course.subject.toUpperCase()) != -1) {
								if (indexQuality < 0) {
									selectIndex = index;
									indexQuality = 0;
								}
							}
						}
					});
				});
				if (selectIndex != -1) {
					console.log("course found");
					// Update course selection box
					$scope.syncCourseSelect = vm.courses[selectIndex];
					document.getElementById('syncCourseSelect').selectedIndex = selectIndex + 1;
					found = true;
				}

				// Create a course object that would represent this course File
				if (!found) {
					console.log("course not found");
					// Try to find a pattern match for a complete course name
					var courseMatch = file.match(/[A-Z]{3}\s+[0-9]{4}\s+-\s+[A-Z0-9]+\s+\([0-9]+\)/);
					console.log("courseMatch:", file, file.match(/[A-Z]{3}\s+[0-9]{4}\s+-\s+[A-Z0-9]+\s+\([0-9]+\)/));
					if (courseMatch) {
						var newCourseTokens = courseMatch[0].split(/\s+/);
						var newCourseData = {
							subject: newCourseTokens[0],
							number: newCourseTokens[1],
							section: newCourseTokens[3],
							course_id: newCourseTokens[4].replace(/[()]/g, "")
						};
						var newCourseName = newCourseData.subject + ' ' + newCourseData.number + ' - ' + newCourseData.section
						// Show add course table
						$scope.showAddCourse = true;
						// Populate the add course fields with matched data
						$scope.addNewCourseInputSubject2 = newCourseData.subject;
						$scope.addNewCourseInputNumber2 = newCourseData.number;
						$scope.addNewCourseInputSection2 = newCourseData.section;
						$scope.addNewCourseInputID2 = newCourseData.course_id;
						$scope.addCourseTerm2 = vm.terms[currentTermIndex];
						document.getElementById('addCourseTerm2').selectedIndex = currentTermIndex + 1;
						$scope.$digest();

						// Prompt User to Comfirm course match
						swal({
							title: "Notice",
							text: "Confirm the creation of new course '" + newCourseName + "' for " + currentTerms[0],
							type: "info",
							confirmButtonText: "Continue",
							allowOutsideClick: false,
							timer: 10000,
						}, function () {});
					} else {
						// Show add course table
						$scope.showAddCourse = true;
						// Clear the add course fields
						$scope.addNewCourseInputSubject2 = "";
						$scope.addNewCourseInputNumber2 = "";
						$scope.addNewCourseInputSection2 = "";
						$scope.addNewCourseInputID2 = "";
						$scope.addCourseTerm2 = vm.terms[currentTermIndex];
						document.getElementById('addCourseTerm2').selectedIndex = currentTermIndex + 1;
						$scope.$digest();
						// Prompt User to enter course information
						swal({
							title: "Notice",
							text: "Could not automatically generate a course for this file, please create a course for this file",
							type: "info",
							confirmButtonText: "Continue",
							allowOutsideClick: true,
							timer: 10000,
						}, function () {});
					}
				}
			} catch (err) {
				console.log(err)
			}
		};

		// Adds a course file to course file list
		vm.addCourseFile = function () {
			if ($scope.syncCourseSelect && vm.addCourseFileName) {
				// test if duplicate exists in courseFiles list
				var courseName = $scope.syncCourseSelect.fullName;
				var found = false;
				var fileWithSameCourseName = '';

				vm.courseFiles.forEach(function (courseFile) {
					if (courseFile.course.fullName == courseName) {
						found = true;
						fileWithSameCourseName = courseFile.file;
					}
				});
				if (!found || ((fileWithSameCourseName.match('.*-.*-.*-INC\.txt') && vm.addCourseFileName.match('.*-.*-.*\.txt')) ||
						fileWithSameCourseName.match('.*-.*-.*\.txt') && vm.addCourseFileName.match('.*-.*-.*-INC\.txt'))) {
					// Test whether file data was successfully pulled from TXT file
					if (vm.addCourseData != null) {
						// Create the new courseFile and add it to the list
						var newCourseFile = {
							course: $scope.syncCourseSelect,
							file: vm.addCourseFileName,
							data: vm.addCourseData
						};

						vm.courseFiles.push(newCourseFile);
						// Clear Data and UI
						$scope.syncCourseSelect = "";
						document.getElementById('syncCourseSelect').selectedIndex = -1;
						vm.addCourseFileName = null;
						vm.addCourseData = null;
						// Hide add course table
						$scope.showAddCourse = false;
					} else {
						// Clear Data and UI
						$scope.syncCourseSelect = "";
						document.getElementById('syncCourseSelect').selectedIndex = -1;
						vm.addCourseFileName = null;
						vm.addCourseData = null;
						// Hide add course table
						$scope.showAddCourse = false;

						swal({
							title: "Error",
							text: "Course data is missing, cannot load course file. Please check file to make sure the user's Email, Panther ID and Name are all present",
							type: "error",
							confirmButtonText: "Continue",
							allowOutsideClick: true,
							timer: 10000,
						}, function () {});
					}
				} else {
					swal({
						title: "Error",
						text: "Course already queued with file. Try again with another course or remove the course already queued",
						type: "error",
						confirmButtonText: "Continue",
						allowOutsideClick: true,
						timer: 10000,
					}, function () {});
				}
			}
		};

		// Add a course within the course file modal
		vm.addCourse2 = function () {
			if (!$scope.addNewCourseInputSubject2 || !$scope.addNewCourseInputNumber2 || !$scope.addNewCourseInputSection2 ||
				!$scope.addNewCourseInputID2 || !$scope.addCourseTerm2 ||
				$scope.addNewCourseInputSubject2.length < 3 || $scope.addNewCourseInputNumber2.length < 4) {
				var errMsg = "";
				if (!$scope.addNewCourseInputSubject2)
					errMsg += "\tSubject Missing\n";
				else if ($scope.addNewCourseInputSubject2.length < 3)
					errMsg += "\tSubject is not 3 Character Code\n";
				if (!$scope.addNewCourseInputNumber2)
					errMsg += "\tNumber Missing\n";
				else if ($scope.addNewCourseInputNumber2.length < 4)
					errMsg += "\tNumber is not 4 Digit Number\n";
				if (!$scope.addNewCourseInputSection2)
					errMsg += "\tSection Missing\n";
				if (!$scope.addNewCourseInputID2)
					errMsg += "\ID Missing\n";
				if (!$scope.addCourseTerm2)
					errMsg += "\tSemester Missing\n";

				swal({
					title: "Error",
					text: errMsg,
					type: "error",
					confirmButtonText: "Continue",
					allowOutsideClick: true,
					timer: 10000,
				}, function () {});
			} else {
				// test if duplicate exists
				var courseName = $scope.addNewCourseInputSubject2 + ' ' + $scope.addNewCourseInputNumber2 + " - " + $scope.addNewCourseInputSection2;
				var courseFullName = courseName + ' ' + $scope.addCourseTerm2.name + ' (' + $scope.addNewCourseInputID2 + ')';

				var found = false;
				vm.courses.forEach(function (course) {
					if (course.fullName == courseFullName)
						found = true;
				});
				if (!found) { // Create the new course and save it
					var newCourse = {
						name: courseName,
						subject: $scope.addNewCourseInputSubject2,
						number: $scope.addNewCourseInputNumber2,
						section: $scope.addNewCourseInputSection2,
						course_id: $scope.addNewCourseInputID2,
						semester: $scope.addCourseTerm2.name,
						fullName: courseFullName
					};

					if ($scope.addNewCourseInputTitle2 != "")
						newCourse["title"] = $scope.addNewCourseInputTitle2;

					adminService.addCourse(newCourse).then(function (data) {
						vm.courses.push(data);
						// Update course selection box
						$scope.syncCourseSelect = vm.courses[vm.courses.length - 1];

						// Notify User of Added Course
						swal({
							title: "Success",
							text: "Course " + courseFullName + " has been added to the database",
							type: "success",
							confirmButtonText: "Continue",
							allowOutsideClick: true,
							timer: 10000,
						}, function () {});
					});
					// Hide add course table
					$scope.showAddCourse = false;

					// Clear Input fields
					$scope.addNewCourseInputSubject2 = "";
					$scope.addNewCourseInputNumber2 = "";
					$scope.addNewCourseInputSection2 = "";
					$scope.addNewCourseInputID2 = "";
					$scope.addNewCourseInputTitle2 = "";
					$scope.addCourseTerm2 = "";
				}
			}
		};

		// Parse TXT file into readable data
		function parseTXT(file, fileName) {
			var entries = file.split("\n"); // Splits at the end of line. entries has the rows now

			if (entries[entries.length - 1] == null || entries[entries.length - 1] == "") {
				entries.pop(); // Sometimes the file has an empty line at the end. This will remove it.
			}

			var users = [];
			for (var i = 0; i < entries.length; i++) {
				var rowArr = entries[i].split("::");
				if (rowArr.length != 3) {
					alert("Incorrect file format: Not all entries have three columns. Row:" + (i + 1));
					return null;
				}

				var pID = rowArr[1];
				if (pID.length != 7) {
					alert("Incorrect file format: PantherID length is not equal to 7. Row: " + (i + 1));
					return null;
				}

				var userLoginName = rowArr[0].toLowerCase();
				var fullName = rowArr[2];
				var email = userLoginName + "@fiu.edu";
				console.log(userLoginName.match('\\d+'));
				var lastNameFirst4 = userLoginName.slice(1, userLoginName.match('\\d+').index);

				var nameParts = fullName.split(" ");
				var current = "";
				var index = -1;

				for (var j = nameParts.length - 1; j > 0; j--) {
					current = (nameParts[j].toLowerCase() + " " + current).trim();
					index = current.replace(/-| |'|_|@|!/g, "").indexOf(lastNameFirst4);
					if (index != -1) {
						break;
					}
				};
				if (index == -1) {
					alert("Incorrect file format: On file: " + fileName + " Student name does not match login user name structure.On Row: " + (i + 1));
					return null;
				}
				var firstAndMidName = fullName.slice(0, fullName.toLowerCase().indexOf(current) - 1);
				var lastName = fullName.slice(fullName.toLowerCase().indexOf(current), fullName.length);

				var newUser = {
					pantherID: pID,
					email: email,
					firstName: capitalizeFirstLetter(firstAndMidName),
					lastName: capitalizeFirstLetter(lastName),
					userType: "Student"
				};

				users.push(newUser);
			}
			return users;
		};

		function capitalizeFirstLetter(strings) {
			var result = "";
			strings.split(" ").forEach(function (string) {
				result = result + " " + string.charAt(0).toUpperCase() + string.slice(1);
			});
			return result.trim();
		}

		// Removes a course file from course file list
		vm.removeCourseFile = function (removingCourseFile) {
			if (vm.courseFiles.length == 1) {
				vm.clearCourseFiles();
				return;
			}
			vm.courseFiles.forEach(function (courseFile, index) {
				if (courseFile.course.fullName == removingCourseFile.course.fullName) {
					vm.courseFiles.splice(index, 1);
				}
			});
		};

		// Updates each course with its corresponding courseFile in the database
		vm.syncDatabase = function () {
			if (vm.courseFiles.length == 0) {
				alert("No data to process. Please add a file/course to the list");
				return;
			}
			loadUsers();

			var newStudents = [];
			var updatedStudents = [];
			var removedStudents = [];
			var studentsAdded = 0,
				studentsUpdated = 0,
				studentsRemovedFromCourses = 0,
				studentsProcessed = 0;

			// Build map for users for fast lookup
			var userMap = new Map();
			vm.allusers.forEach(function (user, index) {
				userMap.set(user.email, index);
			});

			vm.courseFiles.forEach(function (courseFile, indexA) {
				// Map for users in this course file
				var courseEnrolled = new Map();

				courseFile.data.forEach(function (courseUser, indexB) {
					studentsProcessed += 1;
					courseEnrolled.set(courseUser.email, indexB + 1);
					// Determine if user exists already
					if (userMap.get(courseUser.email)) {

						// Determine if user needs to be updated
						var testUser = vm.allusers[userMap.get(courseUser.email)];
						var needUpdate = false;

						if ((testUser.course != courseFile.course.fullName) ||
							(testUser.pantherID != courseUser.pantherID) ||
							(testUser.isEnrolled != true) ||
							(testUser.semester != courseFile.course.semester)) {
							needUpdate = true;
						}

						// Update the user in the database
						if (needUpdate) {
							updatedStudents.push(testUser);
							studentsUpdated += 1;
						}
					} else { // User doesn't exist, create a new user and add it to the database & user lists
						courseUser['course'] = courseFile.course.fullName;
						courseUser['isEnrolled'] = true;
						courseUser['semester'] = courseFile.course.semester;
						courseUser['piApproval'] = true;
						courseUser['adminCreated'] = true;
						courseUser['RegDate'] = DateTimeService.getCurrentDateTimeAsString();
						studentsAdded += 1;
						newStudents.push(courseUser);
					}
				});

				// Remove users that are no longer in this specific course
				vm.allusers.forEach(function (user, index) {
					if (!courseEnrolled.get(user.email)) {
						if (user.course == courseFile.course.fullName) {
							studentsRemovedFromCourses += 1;
							removedStudents.push(user);
						}
					}
				});
			});
			// Refresh User panel
			vm.tabledata = JSON.stringify(vm.filteredusers);
			vm.tabledata = eval(vm.tabledata);

			adminService.loadCourses().then(function (data) {
				vm.gridOptionsCourse.data = data;
				courserefresh();
			});

			//prepares HTML code to display lists of the students from the given file, 
			//and whether their new, updated, or would be removed.
			var newStudentsHtml = "<div style=\"width: 450px; height: 170px; overflow-y:scroll;\"><table border=1><col width=\"225\"><col width=\"225\">" +
				"<tr><td><font size=\"3\"><b>Student Name</b></font></td><td><font size=\"3\"><b>Past Course (if updated)</b></font></td></tr>";
			for (var i = 0; i < newStudents.length; i++) {
				newStudentsHtml += "<tr style=\"background-color:#6699ff;\"><td><font color=\"#00000;\">" + newStudents[i].firstName + " " + newStudents[i].lastName +
					"</font></td><td><font color=\"#00000;\"> N/A </font></td></tr>";
			}
			for (var i = 0; i < updatedStudents.length; i++) {
				newStudentsHtml += "<tr style=\"background-color:#66ffc2;\"><td><font color=\"#00000;\">" + updatedStudents[i].firstName + " " + updatedStudents[i].lastName + "</font></td>";
				newStudentsHtml += "<td><font color=\"#00000;\">" + updatedStudents[i].course + "</font></td></tr>";
			}
			for (var i = 0; i < removedStudents.length; i++) {
				newStudentsHtml += "<tr style=\"background-color:#ff4d4d;\"><td><font color=\"#00000;\">" + removedStudents[i].firstName + " " + removedStudents[i].lastName +
					"</font></td><td><font color=\"#00000;\"> N/A </font></td></tr>";
			}
			newStudentsHtml += "</table></div>";

			swal({
				title: "Success",
				text: "Students data updated with the course file" +
					"<br>Records processed: " + studentsProcessed +
					"<br><div style=\"width: 10px;height: 10px;display: inline-block;vertical-align: middle; background-color: #6699ff;\"></div>" +
					"<span style=\"margin-left: 5px; vertical-align: middle;\">Students added: " + studentsAdded + "</span>" +
					"<br><div style=\"width: 10px;height: 10px;display: inline-block;vertical-align: middle; background-color: #66ffc2;\"></div>" +
					"<span style=\"margin-left: 5px; vertical-align: middle;\">Students updated: " + studentsUpdated + "</span>" +
					"<br><div style=\"width: 10px;height: 10px;display: inline-block;vertical-align: middle; background-color: #ff4d4d;\"></div>" +
					"<span style=\"margin-left: 5px; vertical-align: middle;\">Students removed from course(s): " + studentsRemovedFromCourses + "</span><br>" +
					newStudentsHtml,
				type: "success",
				html: true,
				showCancelButton: true,
				confirmButtonText: "Confirm",
				allowOutsideClick: true,
			}, function () {
				// Build map for users for fast lookup
				var newUserMap = new Map();
				vm.allusers.forEach(function (user, index) {
					newUserMap.set(user.email, index);
				});

				vm.courseFiles.forEach(function (courseFile, indexA) {
					// Map for users in this course file
					var newCourseEnrolled = new Map();
					courseFile.data.forEach(function (courseUser, indexB) {
						studentsProcessed += 1;
						newCourseEnrolled.set(courseUser.email, indexB + 1);
						// Determine if user exists already
						if (newUserMap.get(courseUser.email)) {
							// Determine if user needs to be updated
							var testUser = vm.allusers[newUserMap.get(courseUser.email)];
							var needUpdate = false;

							if ((testUser.course != courseFile.course.fullName) ||
								(testUser.pantherID != courseUser.pantherID) ||
								(testUser.isEnrolled != true) ||
								(testUser.semester != courseFile.course.semester)) {
								needUpdate = true;
							}

							// Update the user in the database
							if (needUpdate) {
								studentsUpdated += 1;
								testUser.course = courseFile.course.fullName;
								testUser.pantherID = courseUser.pantherID;
								testUser.isEnrolled = true;
								testUser.semester = courseFile.course.semester;
								User.update({
									user: testUser
								});
							}
						} else { // User doesn't exist, create a new user and add it to the database & user lists
							courseUser['course'] = courseFile.course.fullName;
							courseUser['isEnrolled'] = true;
							courseUser['semester'] = courseFile.course.semester;
							courseUser['piApproval'] = true;
							courseUser['adminCreated'] = true;
							courseUser['RegDate'] = DateTimeService.getCurrentDateTimeAsString();
							studentsAdded += 1;
							User.create(courseUser).then(function (data) {
								if (data) {
									if (data.data.success) {
										newUserMap.set(courseUser.email, vm.allusers.length);
										vm.allusers.push(data.data.object);
										// Refresh User panel
										vm.tabledata = JSON.stringify(vm.filteredusers);
										vm.tabledata = eval(vm.tabledata);
									}
								}
							});
						}
					});

					// Remove users that are no longer in this specific course
					vm.allusers.forEach(function (user, index) {
						if (!newCourseEnrolled.get(user.email)) {
							if (user.course == courseFile.course.fullName) {
								// Update the user in the database
								user.course = "";
								user.isEnrolled = false;
								User.update({
									user: user
								});
								studentsRemovedFromCourses += 1;
							}
						}
					});
				});
				// Refresh User panel
				vm.tabledata = JSON.stringify(vm.filteredusers);
				vm.tabledata = eval(vm.tabledata);
				// Clear the course file list
				vm.clearCourseFiles();

			});
		};

		// Clears the course file list & resets input
		vm.clearCourseFiles = function () {
			vm.courseFiles = [];
			document.getElementById('syncCourseSelect').selectedIndex = -1;
			document.getElementById('courseFileInput').value = null;
			// Hide add course table
			$scope.showAddCourse = false;
			// Clear Input fields
			$scope.addNewCourseInputSubject2 = "";
			$scope.addNewCourseInputNumber2 = "";
			$scope.addNewCourseInputSection2 = "";
			$scope.addNewCourseInputID2 = "";
			$scope.addNewCourseInputTitle2 = "";
			$scope.addCourseTerm2 = "";
		};

		vm.colleges = [{
				name: 'Architecture & The Arts',
				schools: [
					'Architecture',
					'Interior Architecture',
					'Landscape Architecture and Environmental Urban Design',
					'Art and Art History',
					'Communication Arts',
					'School of Music',
					'Theatre'
				]
			},
			{
				name: 'Arts and Sciences & Education',
				schools: [
					'Biological Sciences',
					'Chemistry and Biochemistry',
					'Earth and Environment',
					'English',
					'Mathematics and Statistics',
					'Philosophy',
					'Physics',
					'Psychology',
					'Teaching and Learning',
					'Leadership and Professional Studies',
					'School of Education',
					'School of Enviroment, Arts & Society',
					'School of Integrated Science & Humanity'
				]
			},
			{
				name: 'Business',
				schools: [
					'Decision Sciences and Information Systems',
					'Alvah H. Chapman Jr. Graduate School of Business',
					'R. Kirk Landon Undergraduate School of Business',
					'Finance',
					'Management and International Business',
					'Marketing',
					'School of Accounting',
					'Real Estate'
				]
			},
			{
				name: 'Chaplin School of Hospitality and Tourism Management',
				schools: [
					'Hospitality and Tourism Management'
				]
			},
			{
				name: 'Engineering & Computing',
				schools: [
					'School of Computing and Information Sciences',
					'OHL School of Construction',
					'Department of Biomedical Engineering',
					'Department of Civil and Environment Engineering',
					'Department of Electrical and Computer Engineering',
					'Department of Mechanical and Materials Engineering'
				]
			},
			{
				name: 'Herbert Wertheim College of Medicine',
				schools: [
					'Cellular Biology and Pharmacology',
					'Human and Molecular Genetics',
					'Immunology',
					'Medical and Population Health Sciences Research'
				]
			},
			{
				name: 'Honors College',
				schools: []
			},
			{
				name: 'Journalism and Mass Communication',
				schools: [
					'Advertising and Public Relations',
					'Journalism Broadcasting and Digital Media'
				]
			},
			{
				name: 'Law',
				schools: [
					'College of Law'
				]
			},
			{
				name: 'Nicole Wertheim College of Nursing & Health Sciences',
				schools: [
					'Biostatistics',
					'Dietetics and Nutrition',
					'Environmental and Occupational Health',
					'Epidemiology',
					'Health Policy and Management',
					'Health Promotion and Disease Prevention'
				]
			},
			{
				name: 'Robert Stempel College of Public Health & Social Work',
				schools: [
					'School of Social Work'
				]
			},
			{
				name: 'Steven J. Green School of International and Public Affairs',
				schools: [
					'Criminal Justice',
					'Economics',
					'Global and Sociocultural Studies',
					'History',
					'Modern Languages',
					'Public Administration',
					'Religious Studies'
				]
			}
		];

		function currentSwitch(e) {
			vm.currentSwitchStatus = e == 'true' ? true : false;
		}

		function viewableSwitch(e) {
			vm.viewableSwitchStatus = e == 'true' ? true : false;
		}

		function proposableSwitch(e) {
			vm.proposableSwitchStatus = e == 'true' ? true : false;
		}

		function applicableSwitch(e) {
			vm.applicableSwitchStatus = e == 'true' ? true : false;
		}

		function defaultSwitch(e) {
			vm.defaultSwitchStatus = e == 'true' ? true : false;
		}

		function validateEmail(email) {
			return /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i.test(email)
		};

		function validatePassword(pwd) {
			if (pwd) {
				var array = [];
				array[0] = /[A-Z]/g.test(pwd);
				array[1] = /[a-z]/g.test(pwd);
				array[2] = /\d/g.test(pwd);
				array[3] = hasSpecialChars(pwd)

				var sum = 0;
				for (var i = 0; i < array.length; i++) {
					sum += array[i] ? 1 : 0;
				}

				return pwd.length >= 8 && sum == 4;
			} else
				return false;
		};

		function hasSpecialChars(string) {
			return (string.indexOf('!') != -1 ||
				string.indexOf('@') != -1 ||
				string.indexOf('#') != -1 ||
				string.indexOf('$') != -1 ||
				string.indexOf('%') != -1 ||
				string.indexOf('&') != -1 ||
				string.indexOf('*') != -1 ||
				string.indexOf('(') != -1 ||
				string.indexOf(')') != -1);
		};

		vm.genderOptions = [{
			type: 'Male'
		}, {
			type: 'Female'
		}];
		vm.booleanOptions = [{
			type: true
		}, {
			type: false
		}];

		// user story #1300
		vm.editUser = function (user) {
			vm.editingUser = user;
			vm.editingUserOrig = {
				firstName: user.firstName,
				lastName: user.lastName,
				email: user.email,
				project: user.project
			};

			// Set initial values of input to be current user values
			$scope.editUserFirstName = vm.editingUser.firstName;
			$scope.editUserLastName = vm.editingUser.lastName;
			$scope.editUserEmail = vm.editingUser.email;
			$scope.editUserPID = vm.editingUser.pantherID;

			// Search for indexes for references to user's values (if they exist)
			var indexes = {
				gender: findIndexGender(vm.editingUser.gender),
				college: findIndexCollege(vm.editingUser.college),
				userType: findIndexUserType(vm.editingUser.userType),
				approval: findIndexApproval(vm.editingUser.piApproval),
				emailVerification: findIndexApproval(vm.editingUser.verifiedEmail),
				enrolled: findIndexApproval(vm.editingUser.isEnrolled),
				project: findIndexProject(vm.editingUser.project),
				term: findIndexTerm(vm.editingUser.semester),
				course: findIndexCourse(vm.editingUser.course)
			};
			var indexRank;

			// Assign to drop down box if index was found (the value existed)
			// Otherwise reset selected index of drop down box

			if (indexes.gender != -1)
				$scope.editUserGender = vm.genderOptions[indexes.gender];
			else
				document.getElementById("ddGender").selectedIndex = -1;
			if (indexes.college != -1)
				$scope.editUserCollege = vm.colleges[indexes.college];
			else
				document.getElementById("ddCollege").selectedIndex = -1;

			if (indexes.userType != -1) {
				$scope.editUserType = vm.typeranks[indexes.userType];
				// Modify and search for rank
				vm.getEditRanks(vm.typeranks[indexes.userType]);
				indexRank = findIndexEditRank(vm.editingUser.rank);
			} else {
				document.getElementById("ddUserType").selectedIndex = -1;
				indexRank = -1;
			}

			if (indexRank != -1)
				$scope.editUserRank = vm.typeranks[indexes.userType].ranks[indexRank];
			else
				document.getElementById("ddRank").selectedIndex = -1;
			if (indexes.approval != -1)
				$scope.editUserPIApproval = vm.booleanOptions[indexes.approval];
			else
				document.getElementById("ddPIApproval").selectedIndex = -1;
			//User story #1419
			if (indexes.approval != -1)
				$scope.editUserVerifyEmail = vm.booleanOptions[indexes.emailVerification];
			else
				document.getElementById("ddVerifyEmail").selectedIndex = -1;

			if (indexes.approval != -1)
				$scope.editUserisEnrolled = vm.booleanOptions[indexes.enrolled];
			else
				document.getElementById("ddisEnrolled").selectedIndex = -1;

			if (indexes.project != -1)
				$scope.editUserProject = vm.allprojects[indexes.project];
			else
				document.getElementById("ddProject").selectedIndex = -1;
			if (indexes.term != -1)
				$scope.editUserTerm = vm.terms[indexes.term];
			else
				document.getElementById("ddTerm").selectedIndex = -1;
			if (indexes.course != -1)
				$scope.editUserCourse = vm.courses[indexes.course];
			else
				document.getElementById("ddCourse").selectedIndex = -1;
		};

		// List of functions to find object references that match the user value
		function findIndexGender(gender) {
			if (gender)
				for (var i = 0; i < vm.genderOptions.length; i++)
					if (vm.genderOptions[i].type == gender)
						return i;
			return -1;
		};

		function findIndexCollege(college) {
			if (college)
				for (var i = 0; i < vm.colleges.length; i++)
					if (vm.colleges[i].name == college)
						return i;
			return -1;
		};

		function findIndexUserType(userType) {
			if (userType)
				for (var i = 0; i < vm.typeranks.length; i++)
					if (vm.typeranks[i].name == userType)
						return i;
			return -1;
		};

		function findIndexEditRank(rank) {
			if (rank)
				for (var i = 0; i < vm.editRanks.length; i++)
					if (vm.editRanks[i] == rank)
						return i;
			return -1;
		};

		function findIndexApproval(rank) {
			if (rank == true)
				return 0;
			else if (rank == false)
				return 1;
			else
				return -1;
		};

		function findIndexProject(project) {
			if (project)
				for (var i = 0; i < vm.allprojects.length; i++)
					if (vm.allprojects[i].title == project)
						return i;
			return -1;
		};

		function findIndexTerm(term) {
			if (term)
				for (var i = 0; i < vm.terms.length; i++)
					if (vm.terms[i].name == term)
						return i;
			return -1;
		};

		function findIndexCourse(course) {
			if (course)
				for (var i = 0; i < vm.courses.length; i++)
					if (vm.courses[i].fullName == course)
						return i;
			return -1;
		};

		vm.newUser; // Stores new user after its created

		// Add newly created user
		vm.addUser = function () {
			vm.newUser = null;
			// First check if required information is missing
			if ($scope.addUserFirstName && $scope.addUserLastName && $scope.addUserEmail) {
				// Then check if email and password is valid
				if (validateEmail($scope.addUserEmail) && validatePassword($scope.addUserPassword) && validatePassword($scope.addUserPasswordConf) && $scope.addUserPassword == $scope.addUserPasswordConf) {
					// Create user object
					var newUser = {
						firstName: $scope.addUserFirstName,
						lastName: $scope.addUserLastName,
						email: $scope.addUserEmail,
						RegDate: DateTimeService.getCurrentDateTimeAsString(),
						adminCreated: true
					};

					if ($scope.addUserPassword)
						newUser["password"] = $scope.addUserPassword;
					if ($scope.addUserPasswordConf)
						newUser["passwordConf"] = $scope.addUserPasswordConf;
					if ($scope.addUserRank)
						newUser["rank"] = $scope.addUserRank;
					if ($scope.addUserPID)
						newUser["pantherID"] = $scope.addUserPID;
					if ($scope.addUserGender)
						newUser["gender"] = $scope.addUserGender.type;
					if ($scope.addUserProject)
						newUser["project"] = $scope.addUserProject.title;
					if ($scope.addUserPIApproval)
						newUser["piApproval"] = $scope.addUserPIApproval.type;
					if ($scope.addUserCollege)
						newUser["college"] = $scope.addUserCollege.name;
					if ($scope.addUserCourse)
						newUser["course"] = $scope.addUserCourse.fullName;
					if ($scope.addUserType)
						newUser["userType"] = $scope.addUserType.name;
					if ($scope.addUserTerm)
						newUser["semester"] = $scope.addUserTerm.name;

					if (newUser.project)
						newUser["joined_project"] = true;
					else
						newUser["joined_project"] = false;

					newUser["isEnrolled"] = false;

					// Send POST request
					User.create(newUser).then(function (data) {
						if (data) {
							if (data.data.success) {
								document.getElementById('addUserMessage').innerHTML = 'Adding user was successful';
								vm.newUser = data.data.object;
								// Update the project if user is added to one
								if (newUser.project) {
									addUserToProject(newUser);
								}
								adminService.loadAllUsers().then(function (data) {
									vm.gridOptionsUser.data = data;
									userrefresh();
								});
							} else {
								document.getElementById('addUserMessage').innerHTML = 'Error: HTTP request failed';
							}
						} else { // http error
							document.getElementById('addUserMessage').innerHTML = 'Error: HTTP response not received';
						}
					});
				} else {
					if (!validateEmail($scope.addUserEmail)) {
						document.getElementById('addUserMessage').innerHTML = 'Error: Invalid Email Address';
					} else if (!validatePassword($scope.addUserPassword) || !validatePassword($scope.addUserPasswordConf)) {
						document.getElementById('addUserMessage').innerHTML = 'Error: Invalid Password<br>Passwords need to be at least 8 letters long and must contain at least one of each:' +
							'<br>&nbsp;-&nbsp;Uppercase characters<br>&nbsp;-&nbsp;Lowercase characters<br>&nbsp;-&nbsp;Numbers<br>&nbsp;-&nbsp;Special characters: ! @ # $ % & * ( )';
					} else {
						document.getElementById('addUserMessage').innerHTML = 'Error: Mismatched Passwords';
					}
				}
			} else {
				document.getElementById('addUserMessage').innerHTML = 'Error: Missing required information';
			}
		};

		// Save changes to editing user
		vm.saveChangesUser = function () {
			// First check if required information is missing
			if ($scope.editUserFirstName && $scope.editUserLastName && $scope.editUserEmail) {
				// Then check if email is valid
				if (validateEmail($scope.editUserEmail)) {
					// Update editingUser
					vm.editingUser.firstName = $scope.editUserFirstName;
					vm.editingUser.lastName = $scope.editUserLastName;
					vm.editingUser.email = $scope.editUserEmail;

					if ($scope.editUserRank)
						vm.editingUser.rank = $scope.editUserRank;
					else
						vm.editingUser.rank = null;
					if ($scope.editUserPID)
						vm.editingUser.pantherID = $scope.editUserPID;
					else
						vm.editingUser.pantherID = null;
					if ($scope.editUserGender)
						vm.editingUser.gender = $scope.editUserGender.type;
					else
						vm.editingUser.gender = null;
					if ($scope.editUserProject)
						vm.editingUser.project = $scope.editUserProject.title;
					else
						vm.editingUser.project = null;
					if ($scope.editUserPIApproval)
						vm.editingUser.piApproval = $scope.editUserPIApproval.type;
					else
						vm.editingUser.piApproval = null;
					//User story #1419
					if ($scope.editUserVerifyEmail)
						vm.editingUser.verifiedEmail = $scope.editUserVerifyEmail.type;
					else
						vm.editingUser.verifiedEmail = null;

					if ($scope.editUserisEnrolled)
						vm.editingUser.isEnrolled = $scope.editUserisEnrolled.type;
					else
						vm.editingUser.verifiedEmail = null;

					if ($scope.editUserCollege)
						vm.editingUser.college = $scope.editUserCollege.name;
					else
						vm.editingUser.college = null;
					if ($scope.editUserType)
						vm.editingUser.userType = $scope.editUserType.name;
					else
						vm.editingUser.userType = null;
					if ($scope.editUserTerm)
						vm.editingUser.semester = $scope.editUserTerm.name;
					else
						vm.editingUser.semester = null;
					if ($scope.editUserCourse)
						vm.editingUser.course = $scope.editUserCourse.fullName;
					else
						vm.editingUser.course = null;


					if (vm.editingUser.project)
						vm.editingUser.joined_project = true;
					else
						vm.editingUser.joined_project = false;

					if (!vm.editingUser.isEnrolled)
						vm.editingUser["isEnrolled"] = false;

					// Send PUT request
					User.update({
						user: vm.editingUser
					}).then(function (data) {
						if (data) {
							if (data.data.success) {
								document.getElementById('editUserMessage').innerHTML = 'Editing user was successful';
								// Update the projects that are associated with the given user (name and email)
								if (vm.editingUserOrig.firstName != vm.editingUser.firstName || vm.editingUserOrig.lastName != vm.editingUser.lastName || vm.editingUserOrig.email != vm.editingUser.email)
									updateProjects();

								// Update the project users if user is added to one
								if (!vm.editingUserOrig.project && vm.editingUser.joined_project)
									addUserToProject(vm.editingUser);
								// Send notification and update project if user was removed from project
								else if (vm.editingUserOrig.project && !vm.editingUser.joined_project)
									removeUserFromProject(vm.editingUser, vm.editingUserOrig.project, true);
								// Update both projects users if user is moved from one project to another
								else if (vm.editingUserOrig.project != vm.editingUser.project && vm.editingUser.joined_project)
									updateProjectsUser(vm.editingUser, vm.editingUserOrig.project);
							} else {
								document.getElementById('editUserMessage').innerHTML = 'Error: HTTP request failed';
								// Refresh user panel
								vm.tabledata = JSON.stringify(vm.filteredusers);
								vm.tabledata = eval(vm.tabledata);
							}
						} else { // http error
							document.getElementById('editUserMessage').innerHTML = 'Error: HTTP response not received';
							// Refresh user panel
							vm.tabledata = JSON.stringify(vm.filteredusers);
							vm.tabledata = eval(vm.tabledata);
						}
					});
				} else {
					document.getElementById('editUserMessage').innerHTML = 'Error: Invalid Email Address';
				}
			} else {
				document.getElementById('editUserMessage').innerHTML = 'Error: Missing required information';
			}
		};

		// US 1328 - Update the projects that are currently associated with the given user
		function updateProjects() {
			var profileName = vm.editingUser.firstName + ' ' + vm.editingUser.lastName;

			// Find projects that contain the user
			vm.allprojects.forEach(function (project) {
				var found = false;

				if (project.owner_email == vm.editingUserOrig.email) {
					found = true;
					project.owner_name = profileName;
					project.owner_email = vm.editingUser.email;
				}

				project.members.forEach(function (memberEmail, index) {
					if (memberEmail == vm.editingUserOrig.email) {
						found = true;
						project.members_detailed[index] = profileName;
						project.members[index] = vm.editingUser.email;
					}
				});

				project.faculty.forEach(function (faculty, index) {
					if (faculty.email == vm.editingUserOrig.email) {
						found = true;
						project.faculty[index].name = profileName;
						project.faculty[index].email = vm.editingUser.email;
					}
				});

				project.mentor.forEach(function (mentor, index) {
					if (mentor.email == vm.editingUserOrig.email) {
						found = true;
						project.mentor[index].name = profileName;
						project.mentor[index].email = vm.editingUser.email;
					}
				});

				// Update project if associated with user
				if (found) {
					ProjectService.editProject(project, project._id);
				}
			});
			// Refresh projects panel
			vm.tabledata_p = JSON.stringify(vm.filteredprojects);
			vm.tabledata_p = eval(vm.tabledata_p);
		}

		// Update the project if user is added to one
		function addUserToProject(user) {
			var project;

			for (var i = 0; i < vm.allprojects.length; i++) {
				if (vm.allprojects[i].title == user.project) {
					project = vm.allprojects[i];
				}
			}

			// Check user isnt already part of the project (should not happen)
			var exists = false;
			for (var j = 0; j < project.members.length; j++) {
				if (project.members[j] == user.email) {
					exists = true;
					break;
				}
			}
			if (!exists) {
				project.members_detailed.push(user.firstName + " " + user.lastName);
				project.members.push(user.email);
				ProjectService.editProject(project, project._id);
				// Refresh projects panel
				vm.tabledata_p = JSON.stringify(vm.filteredprojects);
				vm.tabledata_p = eval(vm.tabledata_p);
			}
		};

		// Update the project if user is removed from one
		function removeUserFromProject(user, formerProject, sendNotification) {
			var name = user.firstName + " " + user.lastName;
			var email = user.email;

			for (i = 0; i < vm.allprojects.length; i++) {
				if (vm.allprojects[i].title == formerProject) {
					formerProject = vm.allprojects[i];
				}
			}

			if (formerProject) {
				for (i = 0; i < formerProject.members.length; i++) {
					if (formerProject.members[i] == email) {
						formerProject.members.splice(i, 1);
						formerProject.members_detailed.splice(i, 1);
						break;
					}
				}
				ProjectService.editProject(formerProject, formerProject._id);
				// Refresh projects panel
				vm.tabledata_p = JSON.stringify(vm.filteredprojects);
				vm.tabledata_p = eval(vm.tabledata_p);
			}
			if (sendNotification)
				sendEmailRemovedProject(name, email, formerProject);
		};

		// Send notification user has been removed from project
		function sendEmailRemovedProject(name, email, formerProject) {
			var email_msg = {
				recipient: email,
				text: "Your current project has been cleared. For more information, please contact a PI.",
				subject: "Project Cleared",
				recipient2: vm.adminSettings.current_email,
				text2: name + " has been successfully removed from project '" + (formerProject ? formerProject : 'unknown') + "'.",
				subject2: "Removed user from project"
			};
			User.nodeEmail(email_msg);
		};

		// Update the both projects if user is moved from one project to another
		function updateProjectsUser(user, formerProject) {
			addUserToProject(user);
			removeUserFromProject(user, formerProject, false);
		};

		vm.deletingUser;

		vm.selectDeleteUser = function (user) {
			vm.deletingUser = user;
		};

		// Delete selected user
		vm.deleteUser = function () {
			for (var i = 0; i < vm.deletingUser.length; i++) {
				User.delete(vm.deletingUser[i]._id).then(function (data) {
					if (data) {
						if (data.data.message == 'successfully deleted!') {
							document.getElementById('deleteUserMessage').innerHTML = 'Deleting user was successful';
							// Remove user from project if user was in one
							if (vm.deletingUser.project) {
								removeUserFromProject(vm.deletingUser, vm.deletingUser.project, false);
							}

						} else {
							document.getElementById('deleteUserMessage').innerHTML = 'Error: HTTP request failed';
							vm.deletingUser = null;
						}
					} else { // http error
						document.getElementById('deleteUserMessage').innerHTML = 'Error: HTTP response not received';
						vm.deletingUser = null;
					}
				});
			}
			adminService.loadAllUsers().then(function (data) {
				vm.gridOptionsUser.data = data;
				userrefresh();
			});
			loadUsers();
		};

		// Add/remove the user from vm.tabledata after user has been added/deleted

		vm.updateTableAdd = function () {
			if (vm.newUser) {
				vm.filteredusers.push(vm.newUser);
				vm.tabledata = JSON.stringify(vm.filteredusers);
				vm.tabledata = eval(vm.tabledata);
			}
		};

		vm.updateTableDelete = function () {
			if (vm.deletingUser) {
				var ind = -1;
				for (var i = 0; i < vm.filteredusers.length; i++)
					if (vm.filteredusers[i]._id == vm.deletingUser._id)
						ind = i;

				if (ind != -1) {
					vm.filteredusers.splice(ind, 1);
				}
				vm.tabledata = JSON.stringify(vm.filteredusers);
				vm.tabledata = eval(vm.tabledata);
			}
			vm.deletingUser = null;
		};

		//rpach023 impersonation only if the user is approved by the PI.
		vm.impersonate = function (user) {
			if (!user.piApproval) {
				swal({
					title: 'Impersonation error.',
					text: 'User is not approved by PI ' + user.email,
					html: true,
					timer: 10000,
					showConfirmButton: true
				});

			} else {


				adminService.impersonate(user).then(function (data) {
					if (!data.redirectUrl) { //there was an error
						swal({
							title: 'Impersonation error.',
							text: 'There was an error when attempting to impersonate user: ' + user.email + "\n" + data.message,
							html: true,
							timer: 10000,
							showConfirmButton: true
						});
					}
					//rpach ImpersonationError
					/*else if (!user.isEnrolled || user.isEnrolled == null) {
						swal({
							title: 'Impersonation error: User is not approved by PI.',
							text: 'There was an error when attempting to impersonate user: ' + user.email + "\n" + data.message + "\n" + "Approved: " + user.isEnrolled,
							html: true,
							timer: 10000,
							showConfirmButton: true
						});

					}*/
					else {
						$window.location.href = data.redirectUrl;
						$window.location.reload();
					}


				});

			}
		};

		//Used for filters
		vm.getRank = getRank;
		vm.filteredrank; //Value changed by getRank function after a usertype is selected in filter
		vm.typeranks = [{
				name: 'Staff/Faculty',
				ranks: [
					'Instructor',
					'Assitant Professor',
					'Associate Professor',
					'Full Professor',
					'Administrator',
					'Director'

				]
			},
			{
				name: 'Pi/CoPi',
				ranks: [
					'PI',
					'CoPI',
					'Coordinator',
					'External Member'
				]
			},
			{
				name: 'Student',
				ranks: [
					'Freshman',
					'Sophmore',
					'Junior',
					'Senior',
					'Masters',
					'PhD',
					'postDoc'
				]
			},
			{
				name: 'Undefined',
				ranks: [
					'Undefined'
				]
			}
		];

		function getRank(usertype) {
			if (usertype) {
				vm.typeranks.forEach(function (obj) {
					if (obj.name == usertype.name) {
						vm.filteredrank = obj.ranks;
					}

				});
			}
		};

		vm.getAddRanks = function (usertype) {
			var found = false;
			if (usertype) {
				vm.typeranks.forEach(function (obj) {
					if (obj.name == usertype.name) {
						vm.addRanks = obj.ranks;
						found = true;
					}
				});
			}
			if (!found)
				vm.addRanks = [];

		};

		vm.getEditRanks = function (usertype) {
			var found = false;
			if (usertype) {
				vm.typeranks.forEach(function (obj) {
					if (obj.name == usertype.name) {
						vm.editRanks = obj.ranks;
						found = true;
					}
				});
			}
			if (!found)
				vm.editRanks = [];
		};

		// User Story #1313

		vm.statusList = [{
			type: 'Active'
		}, {
			type: 'Disabled'
		}];


		// Fill in edit project form with existing values in project
		vm.editProject = function (project) {

			vm.editingProject = project;
			vm.editingProjOrigTitle = project.title;
			// Set initial values of input to be current projects values
			$scope.editPTitle = vm.editingProject.title;
			$scope.editPDescription = vm.editingProject.description;
			$scope.editPMaxStudents = vm.editingProject.maxStudents;

			// Search for indexes for references to projects's values (if they exist)
			var indexes = {
				owner: findIndexOwner(vm.editingProject.owner_name),
				term: findIndexTerm(vm.editingProject.semester),
				status: findIndexStatus(vm.editingProject.status)
			};

			// Assign to drop down box if index was found (the value existed)
			// Otherwise reset selected index of drop down box

			if (indexes.owner != -1)
				$scope.editPOwner = vm.allusers[indexes.owner];
			else
				document.getElementById("ddOwnerP").selectedIndex = -1;
			if (indexes.term != -1)
				$scope.editPTerm = vm.terms[indexes.term];
			else
				document.getElementById("ddTermP").selectedIndex = -1;
			if (indexes.status != -1)
				$scope.editPStatus = vm.statusList[indexes.status];
			else
				document.getElementById("ddStatusP").selectedIndex = -1;
		};

		function findIndexOwner(owner) {
			var userName;
			if (owner)
				for (var i = 0; i < vm.allusers.length; i++) {
					userName = vm.allusers[i].firstName + ' ' + vm.allusers[i].lastName;
					if (userName == owner) {
						return i;
					}
				}
			return -1;
		};

		function findIndexStatus(status) {
			if (status)
				for (var i = 0; i < vm.statusList.length; i++)
					if (vm.statusList[i].type == status)
						return i;
			return -1;
		};

		function findTermID(term) {
			if (term)
				for (var i = 0; i < vm.terms.length; i++)
					if (vm.terms[i].name == term)
						return vm.terms[i]._id;
			return -1;
		};

		// Save changes to edited project
		vm.saveChangesProject = function () {
			// First check if required information is missing
			if ($scope.editPTitle) {
				// Then check if there are illegal values
				if ($scope.editPMaxStudents < 0) {
					document.getElementById('editProjectMessage').innerHTML = 'Error: Max Students must be a positive value';
				} else if ($scope.editPMaxStudents < vm.editingProject.members.length) {
					document.getElementById('editProjectMessage').innerHTML = 'Error: Max Students should not be less than currently enlisted member count';
				} else if ($scope.editPStatus.type == 'Active' && !(vm.terms[findIndexTerm($scope.editPTerm.name)].status.currentSemester)) {
					document.getElementById('editProjectMessage').innerHTML = 'Error: Cannot set project to Active status in a non-active semester';
				} else { // Update editingProject
					vm.editingProject.title = $scope.editPTitle;
					vm.editingProjNewTitle = $scope.editPTitle;
					vm.editingProject.description = $scope.editPDescription;
					vm.editingProject.maxStudents = $scope.editPMaxStudents;

					if ($scope.editPOwner) {

						var projectOwner = vm.allusers[findIndexOwner($scope.editPOwner.firstName + ' ' + $scope.editPOwner.lastName)];

						vm.editingProject.owner = projectOwner._id;
						vm.editingProject.owner_name = projectOwner.firstName + ' ' + projectOwner.lastName;
						vm.editingProject.owner_email = projectOwner.email;
						vm.editingProject.owner_rank = projectOwner.rank;
					} else {
						vm.editingProject.owner = null;
						vm.editingProject.owner_name = null;
						vm.editingProject.owner_email = null;
						vm.editingProject.owner_rank = null;
					}
					if ($scope.editPTerm) {
						vm.editingProject.semester = $scope.editPTerm.name;
						var newTermID = findTermID(vm.editingProject.semester);
						vm.editingProject.term = newTermID;
					} else {
						vm.editingProject.semester = null;
						vm.editingProject.term = null;
					}
					if ($scope.editPStatus)
						vm.editingProject.status = $scope.editPStatus.type;
					else
						vm.editingProject.status = null;

					// Send PUT request
					ProjectService.editProject(vm.editingProject, vm.editingProject._id).then(function (data) {
						if (data) {
							if (data.data.message == 'Updated!') {
								if (vm.editingProject.status == 'Disabled') {
									sendDeactivationEmail();
									document.getElementById('editProjectMessage').innerHTML = 'Editing project was successful. The page will reload because a project was disabled.';
								} else {
									document.getElementById('editProjectMessage').innerHTML = 'Editing project was successful';
								}
								// Update users associated with this project if project title has changed
								if (vm.editingProjOrigTitle != vm.editingProjNewTitle)
									updateUsers();
							} else {
								document.getElementById('editProjectMessage').innerHTML = 'Error: HTTP request failed';
								// Refresh projects panel
								vm.tabledata_p = JSON.stringify(vm.filteredprojects);
								vm.tabledata_p = eval(vm.tabledata_p);
							}
						} else { // http error
							document.getElementById('editProjectMessage').innerHTML = 'Error: HTTP response not received';
							// Refresh projects panel
							vm.tabledata_p = JSON.stringify(vm.filteredprojects);
							vm.tabledata_p = eval(vm.tabledata_p);
						}
					});
				}
			} else {
				document.getElementById('editProjectMessage').innerHTML = 'Error: Missing required information';
			}

		};

		vm.reloadDeactivate = function () {
			if (vm.editingProject.status == 'Disabled') {
				$window.location.reload();
				$timeout(function () {
					// We must reevaluate the value in case it was changed by a subsequent
					// watch handler in the digest.

					$scope.$digest()
				}, 0, false);
			}
		}

		// User story #1238 - Update users associated with this project if project title has changed
		function updateUsers() {
			vm.allusers.forEach(function (user) {
				if (user.project == vm.editingProjOrigTitle) {
					user.project = vm.editingProjNewTitle;
					// Update the user with new project title
					User.update({
						user: user
					});
				}
			});
			// Refresh user panel
			vm.tabledata = JSON.stringify(vm.filteredusers);
			vm.tabledata = eval(vm.tabledata);
		};

		// User story #1329 - add and remove video urls from an editing project
		vm.addProjectVideo = function () {
			if ($scope.addPVidUrl) {
				var vidUrl = $scope.addPVidUrl;
				var processedVidUrl = ProcessVideoURL(vidUrl);
				var processedVidThumb = createThumbURL(processedVidUrl);
				var found = false;
				if (vm.editingProject.video_url == null) {
					vm.editingProject.video_url = [];
				}
				vm.editingProject.video_url.forEach(function (user, index) {
					if (vm.editingProject.video_url[index].vidurl == processedVidUrl)
						found = true;
				});
				if (!found)
					vm.editingProject.video_url.push({
						vidurl: processedVidUrl,
						vimgurl: processedVidThumb
					});
			}
			$scope.addPVidUrl = null;
		};

		vm.removeProjectVideo = function (video) {
			vm.editingProject.video_url.forEach(function (user, index) {
				if (vm.editingProject.video_url[index].vidurl == video.vidurl) {
					vm.editingProject.video_url.splice(index, 1);
				}
			});
		};

		function sendDeactivationEmail() {
			var email;
			if (vm.editingProject.status == 'Disabled') {
				for (i = 0; i < vm.editingProject.members.length; i++) {
					email = vm.editingProject.members[i];
					console.log("Sending to " + email);
					var email_msg = {
						recipient: email,
						text: "Your current project '" + vm.editingProject.title + "' has been disabled. For more information, please contact a PI.",
						subject: "Project No Longer Available"
					};
					User.nodeEmail(email_msg);
					// removeUserFromProject(vm.editProjectUsers[i], vm.editingProject, false);
					// vm.tabledata = JSON.stringify(vm.filteredusers);
					// vm.tabledata = eval(vm.tabledata);
				}
				//vm.editingProject.status = null;
				var admin_email_msg = {
					recipient: vm.adminSettings.current_email,
					text: "The project '" + vm.editingProject.title + "' has been disabled. All students who were in the project have been notified and asked to contact a PI for further instruction.",
					subject: "Project Deactivated"
				};
				console.log("Sending to admin " + vm.adminSettings.current_email);
				User.nodeEmail(admin_email_msg);
				//vm.editingProject.status = null;
				// removeUserFromProject(vm.editProjectUsers[i], vm.editingProject, false);
				// vm.tabledata = JSON.stringify(vm.filteredusers);
				// vm.tabledata = eval(vm.tabledata);
			}
		}

		function ProcessVideoURL(VideoURL) {
			// format the youtube videos correctly
			// input: https://www.youtube.com/watch?v=uQ_DHRI-Xp0
			// output: https://www.youtube.com/embed/uQ_DHRI-Xp0
			if (VideoURL) {
				var videoID = "";
				var updatedVideoURL = "";
				// video is already embed format, return
				if (VideoURL.indexOf("youtube.com/embed/") > -1) {
					return VideoURL;
				} else if (VideoURL.indexOf("&list=") > -1) {
					videoID = VideoURL.substr(VideoURL.indexOf("list=") + 5);
					updatedVideoURL = "https://www.youtube.com/embed/?listType=playlist&list=" + videoID;
					return updatedVideoURL;
				}

				// youtube.com universal filter
				else if (VideoURL.indexOf("youtube.com") > -1) {
					videoID = VideoURL.substr(VideoURL.indexOf("?v=") + 3);
					updatedVideoURL = "https://www.youtube.com/embed/" + videoID;
					return updatedVideoURL;
				}

				// youtu.be filter
				else if (VideoURL.indexOf("youtu.be") > -1) {
					videoID = VideoURL.substr(VideoURL.indexOf(".be/") + 4);
					updatedVideoURL = "https://www.youtube.com/embed/" + videoID;
					return updatedVideoURL;
				} else {
					return VideoURL;
				}
			} else {
				return "";
			}
		};

		function createThumbURL(VideoURL) {
			var videoID = "";
			var createdThumbURL = "";

			if (VideoURL.indexOf("&list=") > -1) {
				videoID = VideoURL.substr(VideoURL.indexOf("list=") + 5);
				createdThumbURL = "img/playlist.png";
				return createdThumbURL;
			} else {
				videoID = VideoURL.substr(VideoURL.indexOf("embed/") + 6);
				createdThumbURL = "https://img.youtube.com/vi/" + videoID + "/0.jpg";
				return createdThumbURL;
			}
		};


		vm.editProjectUsers = function (project) {
			var detailedApproval = []
			var promiseArr = []
			project.members.map(email => {
				promiseArr.push(
					new Promise((resolve, reject) => {
						User.getByEmail(email).then((res) => {
							User.get(res.data).then((user) => {
								resolve(user.data)
								// let name = res.firstName + " " res.lastName
								// detailedApproval.push({
								//    name: name,
								//    approved: approvalStat
								// })
							})
						})
					})
				)

			})
			Promise.all(promiseArr).then(obj => {
				obj.map(user => {
					name = user.firstName + " " + user.lastName
					var approved = false
					user.piProjectApproval ? approved = user.piProjectApproval : approved
					detailedApproval.push({
						name: name,
						id: user._id,
						approved: approved
					})
				})
				vm.editingProject = project;

				vm.editingProject.members_detailed_copy = detailedApproval
				vm.editingProjOrigMembers = Array.from(vm.editingProject.members);
				$scope.$digest();
			})
		};

		vm.addStudentProject = function () {
			if ($scope.addPUser) {
				var addStudent = $scope.addPUser;

				var found = false;
				for (i = 0; i < vm.editingProject.members.length; i++)
					if (vm.editingProject.members[i] == addStudent.email) {
						found = true;
						break;
					}
				if (!found) { // Add student into project list if they are not already in the project
					var name = addStudent.firstName + ' ' + addStudent.lastName
					vm.editingProject.members_detailed_copy.push({
						name: name,
						approved: true
					});
					vm.editingProject.members.push(addStudent.email);
					vm.editingProject.members_detailed.push(name);
				}
			}

			/** User Story FA 18 |  VIP-134 Rmart080
			 * Used for updating user projects when a user is added to a project,
			 */
			addStudent.project = vm.editingProject.title;
			User.update({
				user: addStudent
			}).then(function (success) {
				console.log("Successfully Edited User");

				adminService.loadAllUsers().then(function (data) {
					vm.gridOptionsUser.data = data;
				});
				userrefresh();




			});
		};

		vm.approveStudentProject = function (student) {

			adminService.approveProject(student).then((res) => {
				$timeout(function () {
					// We must reevaluate the value in case it was changed by a subsequent
					// watch handler in the digest.

					$scope.$digest()
				}, 0, false);
			})
		}
		vm.approveUser = function (user) {
			adminService.approveUser(user).then((res) => {
				$state.reload()
				$timeout(function () {
					// We must reevaluate the value in case it was changed by a subsequent
					// watch handler in the digest.

					$scope.$digest()
				}, 0, false);
			})
		}

		vm.unapproveUser = function (user) {
			adminService.unapproveUser(user).then((res) => {
				$state.reload()
				$timeout(function () {
					// We must reevaluate the value in case it was changed by a subsequent
					// watch handler in the digest.

					$scope.$digest()
				}, 0, false);
			})
		}
		vm.removeStudentProject = function (removingStudent) {
			// Remove student from project roster
			for (i = 0; i < vm.editingProject.members.length; i++) {
				if (vm.editingProject.members_detailed_copy[i].name == removingStudent) {
					vm.editingProject.members.splice(i, 1);
					vm.editingProject.members_detailed.splice(i, 1);
					vm.editingProject.members_detailed_copy.splice(i, 1);
				}
			}
		};

		vm.editingProjectNew;

		// Update Project's users information
		vm.saveChangesProjectUsers = function () {
			// Send PUT request
			ProjectService.editProject(vm.editingProject, vm.editingProject._id).then(function (data) {
				if (data) {
					if (data.data.message == 'Updated!') {
						document.getElementById('editProjectMessage').innerHTML = 'Editing projects users was successful';

						vm.editingProjectNew = Array.from(vm.editingProject.members);
						updateProjectUsers(vm.editingProject.title, vm.editingProjectNew, vm.editingProjOrigMembers);
						// Refresh User Panel
						vm.tabledata = JSON.stringify(vm.filteredusers);
						vm.tabledata = eval(vm.tabledata);
						projectrefresh();
					} else {
						document.getElementById('editProjectMessage').innerHTML = 'Error: HTTP request failed';
						// Refresh projects panel
						vm.tabledata_p = JSON.stringify(vm.filteredprojects);
						vm.tabledata_p = eval(vm.tabledata_p);
					}
				} else { // http error
					document.getElementById('editProjectMessage').innerHTML = 'Error: HTTP response not received';
					// Refresh projects panel
					vm.tabledata_p = JSON.stringify(vm.filteredprojects);
					vm.tabledata_p = eval(vm.tabledata_p);
				}
				/*loadUsers();
				userrefresh();*/
				loadAllProjects();
				projectrefresh();
				//$window.location.reload();

			});
		};

		function updateProjectUsers(project, projectMembers, formerProjectMembers) {
			var i, j;
			// Find added users and update them
			for (i = 0; i < projectMembers.length; i++) {
				var found = false;
				for (j = 0; j < formerProjectMembers.length; j++) {
					if (formerProjectMembers[j] == projectMembers[i]) {
						found = true;
						break;
					}
				}
				if (!found) {
					var pUser = vm.allusers[findIndexUser(projectMembers[i])];
					if (pUser) {
						pUser.project = project;
						pUser.joined_project = true;
						User.update({
							user: pUser
						});
					}
				}
			}
			// Find removed users and delete them
			for (j = 0; j < formerProjectMembers.length; j++) {
				var found = false;
				for (i = 0; i < projectMembers.length; i++) {
					if (formerProjectMembers[j] == projectMembers[i]) {
						found = true;
						break;
					}
				}
				if (!found) {
					var pUser = vm.allusers[findIndexUser(formerProjectMembers[j])];
					if (pUser) {
						pUser.project = null;
						pUser.joined_project = false;
						User.update({
							user: pUser
						});
					}
				}
			}
		};

		function findIndexUser(email) {
			for (i = 0; i < vm.allusers.length; i++) {
				if (vm.allusers[i].email == email)
					return i;
			}
			return -1;
		};


		vm.deletingProject;

		vm.selectDeleteProject = function (project) {
			vm.deletingProject = project;
		}

		vm.deleteProject = function () {
			for (var i = 0; i < vm.deletingProject.length; i++) {
				ProjectService.delete(vm.deletingProject[i]._id).then(function (data) {
					if (data) {
						if (data.message == 'successfully deleted!') {
							document.getElementById('deleteProjectMessage').innerHTML = 'Deleting project was successful';
							// Remove project from all users (if any) in deleted project

							if (typeof vm.deletingProject.members != "undefined" && vm.deletingProject.members != null && vm.deletingProject.members.length > 0)
								updateProjectUsers(vm.deletingProject.title, [], vm.deletingProject.members);
							// Refresh User Panel
							vm.tabledata = JSON.stringify(vm.filteredusers);
							vm.tabledata = eval(vm.tabledata);
							reviewStudentAppService.loadAllProjects().then(function (data) {
								vm.gridOptionsProjects.data = data;
								projectrefresh();
							});
						} else {
							document.getElementById('deleteProjectMessage').innerHTML = 'Error: HTTP request failed';
							vm.deletingProject = null;
						}
					} else { // http error
						document.getElementById('deleteProjectMessage').innerHTML = 'Error: HTTP response not received';
						vm.deletingProject = null;
					}
				});
			}
			reviewStudentAppService.loadAllProjects().then(function (data) {
				vm.gridOptionsProjects.data = data;
				projectrefresh();
			});
		};

		vm.updatePTableDelete = function () {
			if (vm.deletingProject) {
				var ind = -1;
				for (var i = 0; i < vm.filteredprojects.length; i++)
					if (vm.filteredprojects[i]._id == vm.deletingProject._id)
						ind = i;

				if (ind != -1) {
					vm.filteredprojects.splice(ind, 1);
				}
				vm.tabledata_p = JSON.stringify(vm.filteredprojects);
				vm.tabledata_p = eval(vm.tabledata_p);
			}
			vm.deletingProject = null;
			reviewStudentAppService.loadAllProjects().then(function (data) {
				vm.gridOptionsProjects.data = data;
				projectrefresh();
			});
		};

		// End US #1313

		// User Story #1365

		vm.addFacultyProject = function () {
			if ($scope.addPFaculty) {
				var addFaculty = $scope.addPFaculty;
				var found = false;
				for (i = 0; i < vm.editingProject.faculty.length; i++)
					if (vm.editingProject.faculty[i].email == addFaculty.email) {
						found = true;
						break;
					}
				if (!found) { // Add faculty into project list if they are not already in the project
					vm.editingProject.faculty.push({
						name: addFaculty.firstName + ' ' + addFaculty.lastName,
						email: addFaculty.email
					});
				}
			}
		};

		vm.removeFacultyProject = function (faculty) {
			// Remove faculty from project faculty roster
			for (i = 0; i < vm.editingProject.faculty.length; i++) {
				if (vm.editingProject.faculty[i].email == faculty.email) {
					vm.editingProject.faculty.splice(i, 1);
				}
			}
		};

		vm.addMentorProject = function () {
			if ($scope.addPMentor) {
				var addMentor = $scope.addPMentor;
				var found = false;
				for (i = 0; i < vm.editingProject.mentor.length; i++)
					if (vm.editingProject.mentor[i].email == addMentor.email) {
						found = true;
						break;
					}
				if (!found) { // Add mentor into project list if they are not already in the project
					vm.editingProject.mentor.push({
						name: addMentor.firstName + ' ' + addMentor.lastName,
						email: addMentor.email
					});
				}
			}
		};

		vm.removeMentorProject = function (mentor) {
			// Remove mentor from project mentor roster
			for (i = 0; i < vm.editingProject.mentor.length; i++) {
				if (vm.editingProject.mentor[i].email == mentor.email) {
					vm.editingProject.mentor.splice(i, 1);
				}
			}
		};

		//Ravi's Help
		function AddTerms() {
			var termsdata = {
				name: "Fall 2017 Test",
				start: new Date('2017', '08'),
				end: new Date('2017', '12'),
				deadline: new Date('2017, 08'),
				active: true,
				status: "Active",
				open: true
			};

			reviewStudentAppService.addterm(termsdata).then(function (success) {}, function (error) {});
		};

		vm.deleteemail = DeleteEmail;
		vm.addemail = AddEmail;
		vm.addsetting = AddSetting;
		vm.deletesetting = DeleteSetting;
		vm.savesetting = SaveSetting;
		vm.toggleactive = ToggleActive;
		vm.loadsettings = loadSettings;
		vm.changekey = ChangeKey;


		function ToggleActive(event) {
			if ($(event.target).val().length > 0) {

				$(".list-group .list-group-item").removeClass("active");
				$(event.target).toggleClass("active");

				vm.adminSettings.current_email = $(event.target).val();
			}
		}

		function DeleteEmail(which) {
			if (vm.adminSettings.emails.length > 1) {
				var indexToRemove = vm.adminSettings.emails.indexOf(which);

				if (which === vm.adminSettings.current_email) {
					if (indexToRemove == 0)
						vm.adminSettings.current_email = vm.adminSettings.emails[indexToRemove + 1];
					else
						vm.adminSettings.current_email =
						vm.adminSettings.emails[indexToRemove - 1];
				}

				vm.adminSettings.emails.splice(indexToRemove, 1);
			} else
				cannotdelete_msg();
		}

		//Changes the value of the MJKey cookie, as long as it isn't left blank
		function ChangeKey() {
			if ($scope.newMJKey == null || $scope.newMJKey == "") {
				swal({
						title: "New Key Is Empty",
						text: "New key cannot be blank. No changes made.",
						type: "warning",
						confirmButtonText: "Continue",
						allowOutsideClick: true,
						timer: 10000,
					},
					function () {});
			} else {
				//creates a new object based on the user's given key
				var outputObj = {
					"key": "123FIUspw",
					"mjCookie": $scope.newMJKey
				};
				document.getElementById("currentKey").innerHTML = "Current key: " + $scope.newMJKey;

				//Replaces the file with the new one, and warns the admin to make sure the MJ app has the same key.
				adminService.saveNewKey(outputObj).then(function (data) {});
				swal({
						title: "Key Changed Successfuly",
						text: "You have changed the key to the MJ app connection. Please make sure the key on the MJ side is the same.",
						type: "info",
						confirmButtonText: "Continue",
						allowOutsideClick: true,
						timer: 10000,
					},
					function () {});
			}

		}

		function AddEmail() {
			if ($scope.newEmail != null) {
				vm.adminSettings.emails.push($scope.newEmail);
				$scope.newEmail = "";
			} else
				cannotadd_msg();
		}

		function DeleteSetting(setting) {
			adminService.deleteSettings(setting._id);
		}

		function AddSetting() {
			adminService.makeInitialSettings();
		}

		function SaveSetting() {
			if (vm.adminSettings.projectDeadlineStartDate == null || vm.adminSettings.projectDeadlineEndDate == null) {
				savesettings_msg_error();
				return;
			}
			if (vm.adminSettings.emailSignature) {
				vm.adminSettings.emailSignature = vm.adminSettings.emailSignature.replace(/\n/g, "<br/>");
			}
			var ed = new Date(vm.adminSettings.projectDeadlineEndDate);
			ed.setHours(23, 59, 59, 0);
			vm.adminSettings.projectDeadlineEndDate = ed;
			adminService.saveAdminSettings(vm.adminSettings).then(function (data) {
				vm.adminSettings.emailSignature = vm.adminSettings.emailSignature.replace(/<br\/>/g, "\n");
				var sd = new Date(vm.adminSettings.projectDeadlineStartDate);
				vm.adminSettings.projectDeadlineStartDate = sd.toLocaleDateString();
				var ed = new Date(vm.adminSettings.projectDeadlineEndDate);
				vm.adminSettings.projectDeadlineEndDate = ed.toLocaleDateString();
				document.getElementById("startDate").innerHTML = "Start Date: " + sd.toLocaleDateString();
				document.getElementById("endDate").innerHTML = "End Date: " + ed.toLocaleDateString();

			});
			savesettings_msg();
		}

		init();

		function init() {
			loadProjects();
			// User story - 1176
			loadAllProjects();
			// Joe's User Story
			loadTerms();
			loadSettings();
			// User story 1345
			loadCourses();
			loadUsers();
			loadSkills();
		}

		vm.adminSettings;

		function loadSettings() {
			adminService.getAdminSettings().then(function (data) {
				var result = data;

				var getAdminSettings = function () {
					adminService.getAdminSettings().then(function (data) {
						vm.adminSettings = data;
						vm.adminSettings.emailSignature = vm.adminSettings.emailSignature.replace(/<br\/>/g, "\n");
						var sd = new Date(vm.adminSettings.projectDeadlineStartDate);
						vm.adminSettings.projectDeadlineStartDate = sd.toLocaleDateString();
						var ed = new Date(vm.adminSettings.projectDeadlineEndDate);
						vm.adminSettings.projectDeadlineEndDate = ed.toLocaleDateString();
						document.getElementById("startDate").innerHTML = "Start Date: " + sd.toLocaleDateString();
						document.getElementById("endDate").innerHTML = "End Date: " + ed.toLocaleDateString();

						document.getElementById("impersonateUser").disabled = true;

						//Gets the current value of the MJKey cookie, and displays it for the admin
						$http.get('/vip/api/mjkey/', {
							headers: {
								'Cache-Control': 'no-cache'
							}
						}).then((res) => {
							vm.adminSettings.key = JSON.stringify(res.data.mjCookie);
							vm.adminSettings.key = vm.adminSettings.key.replace("/", '');
							if (vm.mjKey != undefined) {
								vm.adminSettings.key = vm.mjKey;
							}
							document.getElementById("currentKey").innerHTML = "Current key: " + vm.adminSettings.key;
						});
					});
				};

				if (result) {
					getAdminSettings();
				} else {
					adminService.makeInitialSettings().then(function (response) {
						getAdminSettings();
					}, function (response) {});
				}
			});
		}

		//Load all user information
		vm.usersWOProject;

		function loadUsers() {
			var tempArray = [];
			var tempArray2 = [];
			adminService.loadAllUsers().then(function (data) {
				vm.allusers = data;
				vm.gridOptionsUser.data = data;
				vm.usersWOProject = []; //array of users without projects
				vm.allusers.forEach(function (obj) {
					if (!obj.project && obj.userType == 'Student') {
						vm.usersWOProject.push(obj); //pushes users without projects to the array
					}
					tempArray2.push(obj);
					if (obj.verifiedEmail == false) {
						tempArray2.pop();
						tempArray.push(obj);
					}
				});
				vm.users = tempArray2;
				vm.unconfirmedusers = tempArray;
				vm.filteredusers = vm.allusers;
				vm.tabledata = JSON.stringify(vm.filteredusers);
				vm.tabledata = eval(vm.tabledata);
				vm.buildSiteSummary();
			});
		}

		//Loads all project information for active projects
		function loadProjects() {
			reviewStudentAppService.loadProjects().then(function (data) {
				vm.projects = data;
				vm.buildSiteSummary();
			});
		}

		//Loads all project information regardless of status
		function loadAllProjects() {
			reviewStudentAppService.loadAllProjects().then(function (data) {
				vm.gridOptionsProjects.data = data;

				vm.allprojects = data;
				vm.filteredprojects = vm.allprojects;
				// Store the project data into vm.tabledata_p
				vm.tabledata_p = JSON.stringify(vm.allprojects);
				vm.tabledata_p = eval(vm.tabledata_p);
				vm.buildSiteSummary();


				ProjectService.getProjects().then(function (newdata) {
					var currentSemProjects = newdata;

					currentSemProjects.sort(function (a, b) {
						if (a.title.toLowerCase() > b.title.toLowerCase()) return 1;
						if (a.title.toLowerCase() < b.title.toLowerCase()) return -1;
						return 0;
					})

					vm.gridOptionsUser.columnDefs[6].editDropdownOptionsArray = currentSemProjects;
				});
			});
		}

		//Joe's User Story
		function loadTerms() {

			reviewStudentAppService.loadTerms().then(function (data) {

				vm.terms = data;
				vm.gridOptionsSemester.data = data;

				data.forEach(function (term) {
					if (term.status.currentSemester == true) {
						vm.currentSem = term;
						// vm.currentSemesterName.push(term.name); // TODO Remove if not needed
						vm.currentSemesterName = term.name;
						vm.buildSiteSummary();
					}
				})



			});
		}

		function loadDefaultSemester() {
			vm.defaultSemester;

			vm.terms.forEach(function (term) {
				if (term.status.defaultSemester) {
					vm.defaultSemester = term;
				}
			})
		}

		// Loads all courses & initializes course file list
		function loadCourses() {
			adminService.loadCourses().then(function (data) {
				vm.courses = data;
				vm.buildSiteSummary();
			});
			vm.courseFiles = [];
		}

		function loadSkills() {
			SkillsService.retrieveSkills().then(function (data) {
				vm.skills = data;
				vm.buildSiteSummary();
			});
		}

		vm.uncheck = function () {

			for (var i = 1; i <= 18; i++) {
				$scope['query' + i] = '';
			}
			$scope.selectedusertype = '';
			$scope.selecteduserrank = '';
			$scope.selecteduserproject = '';
			$scope.SelectedProject = '';
			$scope.selectedPiApproval = '';
			$scope.selectedGoogle = '';
			// userstory #1176
			$scope.selectedTerm = '';
			// userstory #1352
			$scope.selectedCouse = '';
			$scope.selectedIsEnrolled = '';
		}

		vm.uncheckp = function () {
			// userstory #1176
			for (var i = 1; i <= 12; i++) {
				$scope['queryp' + i] = '';
			}
			$scope.selectedPOwner = '';
			$scope.selectedPTerm = '';
			$scope.selectedPStatus = '';
		}

		vm.uncheckc = function () {
			// userstory #1346
			for (var i = 1; i <= 4; i++) {
				$scope['queryC' + i] = '';
			}
			$scope.selectedCourseTerm = '';
		}


		//Filters users based on parameters
		function filterUsers(selectedPiApproval, selectedGoogle, selectedusertype, selecteduserrank, SelectedProject, selectedTerm) {
			vm.filteredusers = vm.allusers;
			// n^2
			if (SelectedProject) {
				//alert("not null SelectedProject");
				var studentsArray = [];

				vm.filteredusers.forEach(function (obj) {
					SelectedProject.members.forEach(function (obj2) {
						//alert(obj.email);
						//alert(obj2);

						// user is in project we selected
						if (obj.email == obj2) {
							studentsArray.push(obj);
							//alert(obj.email);
						}

					});
				});

				vm.filteredusers = studentsArray;
				vm.tabledata = JSON.stringify(vm.filteredusers);
				vm.tabledata = eval(vm.tabledata);
			}
			if (selectedusertype) {
				var tempArray = [];
				vm.filteredusers.forEach(function (obj) {
					if (obj.userType == selectedusertype.name) {
						tempArray.push(obj);
					}
				});
				vm.filteredusers = tempArray;
				vm.tabledata = JSON.stringify(vm.filteredusers);
				vm.tabledata = eval(vm.tabledata);
			}
			if (selecteduserrank) {
				var tempArray = [];
				vm.filteredusers.forEach(function (obj) {
					if (obj.userRank == selecteduserrank) {
						tempArray.push(obj);
					}
				});
				vm.filteredusers = tempArray;
				vm.tabledata = JSON.stringify(vm.filteredusers);
				vm.tabledata = eval(vm.tabledata);
			}
			// # userstory 1176
			if (selectedTerm) {
				var tempArray = [];
				vm.filteredusers.forEach(function (obj) {
					if (obj.semester == selectedTerm.name) {
						tempArray.push(obj);
					}
				});
				vm.filteredusers = tempArray;
				vm.tabledata = JSON.stringify(vm.filteredusers);
				vm.tabledata = eval(vm.tabledata);
			}
			if (selectedPiApproval) {
				var tempArray = [];
				vm.filteredusers.forEach(function (obj) {
					if (obj.piApproval == false) {
						tempArray.push(obj);
					}
				});
				vm.filteredusers = tempArray;
				vm.tabledata = JSON.stringify(vm.filteredusers);
				vm.tabledata = eval(vm.tabledata);
			}
			if (selectedGoogle) {
				var tempArray = [];
				vm.filteredusers.forEach(function (obj) {
					if (obj.google) {
						tempArray.push(obj);
					}
				});
				vm.filteredusers = tempArray;
				vm.tabledata = JSON.stringify(vm.filteredusers);
				vm.tabledata = eval(vm.tabledata);
			}
			/* -- Both of these are inefficient and not in use, no users have either of these properties set
            if (mentor) // O(n^3) Very slow.
            {
                var tempArray = [];
                vm.filteredusers.forEach(function (obj) {
                    vm.projects.forEach(function (proj) {
                        var full = obj.firstName + " " + obj.lastName;
                        if (proj.owner_name == full && tempArray) {
                            var contains;
                            tempArray.forEach(function (temp) {
                                var full2 = temp.firstName + " " + temp.lastName;
                                if (full2 == full) {
                                    contains = true;
                                }
                            });
                            if (!contains) {
                                tempArray.push(obj);
                            }
                        }
                        else if (proj.owner_name == full) {
                            tempArray.push(obj);
                        }
                    });
                });
                vm.filteredusers = tempArray;
                vm.tabledata = JSON.stringify(vm.filteredusers);
                vm.tabledata = eval(vm.tabledata);
            }
            if (multipleprojects) // O(n^3) Very slow.
            {
                var tempArray = [];

                vm.filteredusers.forEach(function (obj) {
                    var counter = 0;
                    if (obj.joined_project == true) {
                        vm.projects.forEach(function (proj) {
                            proj.members.forEach(function (email) {
                                if (email == obj.email) {
                                    counter++;
                                    if (counter > 1) {
                                        if (tempArray) {
                                            var contains;
                                            tempArray.forEach(function (temp) {
                                                var full = obj.firstName + " " + obj.lastName;
                                                var full2 = temp.firstName + " " + temp.lastName;
                                                if (full2 == full) {
                                                    contains = true;
                                                }
                                            });
                                            if (!contains) {
                                                tempArray.push(obj);
                                            }
                                        }
                                        else {
                                            tempArray.push(obj);
                                        }
                                    }
                                }
                            });
                        });
                    }
                });
                vm.filteredusers = tempArray;
                vm.tabledata = JSON.stringify(vm.filteredusers);
                vm.tabledata = eval(vm.tabledata);
            }
			*/
		}

		//Filters projects based on parameters
		function filterProjects(selectedPTerm) {
			// # userstory 1176
			vm.filteredprojects = vm.allprojects;
			if (selectedPTerm) {
				var tempArray = [];
				vm.filteredprojects.forEach(function (obj) {
					if (obj.semester == selectedPTerm.name) {
						tempArray.push(obj);
					}
				});
				vm.filteredprojects = tempArray;
				vm.tabledata_p = JSON.stringify(vm.filteredprojects);
				vm.tabledata_p = eval(vm.tabledata_p);
			}
		}

		function currentview(user) {
			var projectTitle = "";
			var project_title = "project_title";
			vm.currentuserview = [];
			ProjectService.getProject(user.project).then(function (data) {
				if (data.kind == "ObjectId") {
					user[project_title] = user.project;
					vm.currentuserview.push(user);
				} else {
					projectTitle = data.title;
					user[project_title] = projectTitle;
					vm.currentuserview.push(user);
				}

			});

		}

		//Remove users
		function RemoveUser(user) {
			swal({
				title: "Final warning!",
				text: "You will not be able to redo this action",
				type: "warning",
				confirmButtonText: "Delete my account",
				showCancelButton: true
			}, function () {
				User.delete(user._id).then(function () {
					delete_msg();
				});
			});
		}

		//Out of scope function for Confirm/Reject unconfirmed users
		function userinUnconfirmedfunc(user) {
			vm.userinunconfirmed = user;
		}

		function verifyEmail() {
			if (vm.userinunconfirmed) {
				user.verifiedEmail = true;
				vm.message = "User email has been verified!";

				reviewRegService.acceptProfile(user).then(function (data) {});
				confirm_msg();
			}
		}

		//Confirm unconfirmed users
		function ConfirmUser() {
			if (vm.userinunconfirmed) {
				var user = vm.userinunconfirmed;
				user.piApproval = true;
				user.isDecisionMade = true;
				user.__v = 3;
				user.verifiedEmail = true;
				vm.message = "User has been Accepted!";

				// if a Pi is approved, mark him in the DB as a super user, so he can switch usertypes to student/faculty/pi without approval
				if (user.userType == "Pi/CoPi") {
					user.isSuperUser = true;
				}

				// non-pi user must be restricted
				else {
					user.isSuperUser = false;
				}

				reviewRegService.acceptProfile(user).then(function (data) {});
				confirm_msg();
			}
		}

		//Reject Unconfirmed users
		function RejectUser() {
			if (vm.userinunconfirmed) {
				var user = vm.userinunconfirmed;
				user.verifiedEmail = false;
				ProfileService.saveProfile(user).then(function (data) {
					Reject_msg();
				});
			}
		}

		function seed() {

			ProjectService.createTerm();
		}

		//Out of scope functions for Change User Type function
		function userTypeChange(usertype) {
			vm.usertypeinusertype = usertype;
		}

		function userChange(user) {
			vm.userinusertype = user;
		}

		//Change User Type
		function changeUserType() {
			if (vm.userinusertype || vm.usertypeinusertype) {
				var user = vm.userinusertype;
				user.userType = vm.usertypeinusertype;
				user.modifying = true;
				ProfileService.saveProfile(user).then(function (data) {
					reviewProfileService.updateProfile(user).then(function (data) {
						changeut_msg();
					});
				});
			}
		}

		//Updated code	//userstory #1172
		//userstory #1172
		function exportData() {
			var date = new Date();
			var todays = (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear() + "_";
			vm.alldata;
			var nArray = [];
			adminService.loadAllUsers().then(function (data) {
				vm.alldata = data;
				vm.alldata.forEach(function (obj) {
					for (var j = 0; j < $scope.filteredItems.length; j++) {
						if (obj.email == $scope.filteredItems[j].email)
							nArray.push(obj);
					}
				});
				var res = alasql("SELECT pantherID,firstName,lastName,email,project,semester,department,college,skillItem,vipcredit,volunteer,independentstudy,rank,userType,appliedDate,RegDate,firstlogin_date INTO XLSX('" + todays + "Report.xlsx',{headers:true}) FROM ? ", [nArray]);

			});
		}

		function confirm_msg() {
			swal({
				title: "User Confirmed!",
				text: "User's account has been confirmed!",
				type: "info",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {
				$window.location.reload();
			});
		};

		function Reject_msg() {
			swal({
				title: "User Rejected!",
				text: "User's account has been deleted!",
				type: "info",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {
				$window.location.reload();
			});
		};

		function delete_msg() {
			swal({
				title: "User Deleted!",
				text: "User's account has been deleted!",
				type: "info",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {
				$window.location.reload();
			});
		};


		function changeut_msg() {
			swal({
				title: "Usertype Changed",
				text: "User's type has been changed!",
				type: "info",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {

			});
		};

		function changepro_msg() {
			swal({
				title: "User's Project Changed",
				text: "User's project has been changed!",
				type: "success",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {

			});
		};

		function semesterchange_msg() {
			swal({
				title: "Semester Properties have Changed",
				text: "",
				type: "success",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {

			});
		};

		function semestercreate_msg() {
			swal({
				title: "Semester has been Created",
				text: "",
				type: "success",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {

			});
		};

		function semesterdelete_msg() {
			swal({
				title: "Semester has been Deleted",
				text: "",
				type: "success",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {

			});
		};

		function defaultsemester_msg() {
			swal({
				title: "Default Semester has been updated!",
				text: "",
				type: "success",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {

			});
		};

		function changestat_msg() {
			swal({
				title: "Project Status Has Changed",
				text: "Project's status has been changed!",
				type: "info",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {

			});
		};

		function changeclear_msg() {
			swal({
				title: "User's Project Cleared",
				text: "User's project has been cleared!",
				type: "info",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {

			});
		};

		function savesettings_msg() {
			swal({
					title: "Settings Saved",
					text: "Preferences have been saved!",
					type: "info",
					confirmButtonText: "Continue",
					allowOutsideClick: true,
					timer: 10000,
				},
				function () {}
			);
		};

		function savesettings_msg_error() {
			swal({
					title: "Settings Error",
					text: "Incorrect deadline dates format",
					type: "error",
					confirmButtonText: "Continue",
					allowOutsideClick: true,
					timer: 10000,
				},
				function () {}
			);
		};

		function test_msg(test) {
			swal({
					title: "This is a test, anddd: " + test,
				},
				function () {}
			);
		};

		function cannotadd_msg() {
			swal({
					title: "Cannot Add Email",
					text: "Input is not a valid email address!",
					type: "warning",
					confirmButtonText: "Continue",
					allowOutsideClick: true,
					timer: 10000,
				},
				function () {}
			);
		}

		function cannotdelete_msg() {
			swal({
					title: "Cannot Delete",
					text: "You cannot delete the last email!",
					type: "warning",
					confirmButtonText: "Continue",
					allowOutsideClick: true,
					timer: 10000,
				},
				function () {}
			);
		};

		//Jesus's code: VIP 202
		//Passes the just changed semester column, then goes through every semester
		// on the term table in the db, and makes sure all the "defaultSemester" values
		// are false, except the one that was just changed to true
		function defaultSemesterCheck(changedTerm) {

			vm.terms.forEach(function (term, index) {
				if (term.status.defaultSemester && !(changedTerm._id == term._id)) {
					term.status.defaultSemester = false;
					ProjectService.editTerm(term, term._id).then(function (success) {

						resetSemSettings();
						return;
					})
				}
			})

		}

		//Change User's Project
		function ChangeUserProject() {
			var user = vm.cuser;
			var project = vm.cproject;
			if (user && project) {
				var formerProject;
				var name = user.firstName + " " + user.lastName;
				var email = user.email;
				for (i = 0; i < vm.projects.length; i++) {
					if (vm.projects[i].members.includes(email)) {
						formerProject = vm.projects[i];
					}
				}
				project.members[project.members.length] = email;
				project.members_detailed[project.members_detailed.length] = name;
				ProjectService.editProject(project, project._id);
				if (formerProject) {
					for (i = 0; i < formerProject.members_detailed.length; i++) {
						if (formerProject.members_detailed[i] == name) {
							formerProject.members_detailed.splice(i, 1);
						}
					}
					for (i = 0; i < formerProject.members.length; i++) {
						if (formerProject.members[i] == email) {
							formerProject.members.splice(i, 1);
						}
					}
					ProjectService.editProject(formerProject, formerProject._id);
				}
				changepro_msg();
			}
		};
		//Joe's User Story
		function ChangeProjectStatus() {
			//Get the project info based on the title being passed
			//Change status
			//Update DB
			var project = vm.cproject;

			if (project) {
				var selectedStatus = $scope.selectedStatus;
				if (selectedStatus == vm.status[0]) {
					selectedStatus = 'Active';
				} else {
					selectedStatus = 'Disabled';
				}
				project.status = selectedStatus;
				ProjectService.editProject(project, project._id);
			}
			changestat_msg();
		};
		//Joe's User Story
		function ChangeTermStatus() {
			var term = vm.cterm;

			var selectedTerm = $scope.selectedTerm.name;
			if (term) {
				var selectedTermStatus = $scope.selectedTermStatus;
				if (selectedTermStatus == vm.active[0]) {
					selectedTermStatus = 'Active';
				} else {
					selectedTermStatus = 'Disabled';
				}
				for (i = 0; i < vm.projects.length; i++) {
					if (vm.projects[i].semester == selectedTerm) {
						vm.projects[i].status = selectedTermStatus;
						ProjectService.editProject(vm.projects[i], vm.projects[i]._id);
					}
				}
				term.status = selectedTermStatus;
				ProjectService.editTerm(term, term._id);
			}
			changestat_msg();
		}

		function createNewSemester(n, s, e) {

			if (vm.currentSwitchStatus == null) {
				vm.currentSwitchStatus = false;
			}
			if (vm.viewableSwitchStatus == null) {
				vm.viewableSwitchStatus = false;
			}
			if (vm.applicableSwitchStatus == null) {
				vm.applicableSwitchStatus = false;
			}
			if (vm.proposableSwitchStatus == null) {
				vm.proposableSwitchStatus = false;
			}
			if (vm.defaultSwitchStatus == null) {
				vm.defaultSwitchStatus = false;
			}

			var termData = {
				name: n,
				start: new Date(s),
				end: new Date(e),
				active: true,
				status: {
					currentSemester: vm.currentSwitchStatus,
					viewable: vm.viewableSwitchStatus,
					openForProposal: vm.proposableSwitchStatus,
					openForApply: vm.applicableSwitchStatus,
					defaultSemester: vm.defaultSwitchStatus
				}
			};

			if (termData.status.defaultSemester) {
				vm.terms.forEach(function (term, index) {
					if (term.status.defaultSemester) {
						term.status.defaultSemester = false;
						ProjectService.editTerm(term, term._id).then(function (success) {

							resetSemSettings();
						})
					}
				})
			}
			ProjectService.createTerm(termData).then(function (success) {

				loadTerms();
				resetSemSettings();
				semesterrefresh();
				loadDefaultSemester();
				// semestercreate_msg();
			}, function (error) {});
			// $scope.selectedTerm = termData;
		}

		function setDefaultSemester(semester) {
			var term = semester[0];
			var user = vm.cuser;

			if (term && user) {
				user.selectedSemester = term;
				ProfileService.saveProfile(user).then(function (success) {
					updateSelectedSemesterQueries(term.name);
					vm.defaultSemester = term;
					for (var i = 0; i < vm.gridOptionsSemester.data.length; i++) {
						if (vm.gridOptionsSemester.data[i].status.currentSemester === true) {
							var notCurrent = vm.gridOptionsSemester.data[i];
							notCurrent._id = vm.gridOptionsSemester.data[i]._id;
							notCurrent.status.currentSemester = false;
							ProjectService.editTerm(notCurrent, notCurrent._id).then(function (success) {
								console.log("Successfully Edited Semester");
								semesterchange_msg();
								resetSemSettings();

							});
							break;
						}
					}
					term.status.currentSemester = true;
					ProjectService.editTerm(term, term._id).then(function (success) {
						console.log("Successfully Edited Semester");
						semesterchange_msg();
						resetSemSettings();
					});

					defaultsemester_msg();
				}, function (error) {});
			}
		}

		function editSemButton(semester) {
			vm.semesterToBeEdited = semester;
			if (semester) {
				$scope.semName = semester.name;
				$scope.startDate = semester.start;
				$scope.endDate = semester.end;
				vm.cStatus = semester.status.currentSemester;
				vm.vStatus = semester.status.viewable;
				vm.pStatus = semester.status.openForProposal;
				vm.aStatus = semester.status.openForApply;
				vm.defaultSemStatus = semester.status.DefaultSemester;
				vm.currentSwitchStatus = vm.cStatus;
				vm.viewableSwitchStatus = vm.vStatus;
				vm.proposableSwitchStatus = vm.pStatus;
				vm.applicableSwitchStatus = vm.aStatus;
				vm.defaultSwitchStatus = vm.defaultSemStatus;
			}
		}

		function makeSemesterChanges() {
			var semester = vm.semesterToBeEdited;

			var status = {
				currentSemester: vm.currentSwitchStatus,
				viewable: vm.viewableSwitchStatus,
				openForProposal: vm.proposableSwitchStatus,
				openForApply: vm.applicableSwitchStatus,
				defaultSemester: vm.defaultSwitchStatus
			}

			if (semester) {
				semester.name = $scope.semName;
				semester.start = $scope.startDate;
				semester.end = $scope.endDate;
				semester.status = status;

				ProjectService.editTerm(semester, semester._id).then(function (success) {
					console.log("Successfully Edited Semester");
					semesterchange_msg();
					resetSemSettings();
				}, function (error) {});
			}

		}

		function delSemButton(semester) {
			vm.semesterToBeDeleted = semester;
		}

		function deleteSemester() {
			var term = vm.semesterToBeDeleted;
			for (var i = 0; i < term.length; i++) {
				if (term[i]) {
					ProjectService.deleteTerm(term[i]._id).then(function (success) {
						console.log("Successfully Deleted Semester");
						delete $scope.selectedTerm;




					}, function (error) {});
				}
			}
			loadTerms();
			semesterdelete_msg();
			semesterrefresh();
		}

		function resetSemSettings() {
			delete $scope.semName;
			delete $scope.startDate;
			delete $scope.endDate;
			delete vm.cStatus;
			delete vm.vStatus;
			delete vm.pStatus;
			delete vm.aStatus;
			delete vm.defaultSemStatus;
			delete vm.currentSwitchStatus;
			delete vm.viewableSwitchStatus;
			delete vm.proposableSwitchStatus;
			delete vm.applicableSwitchStatus;
			delete vm.defaultSwitchStatus;
		}

		function resetSkiSettings() {
			delete vm.skills
		}

		//Remove a user from a project
		function ClearProject() {
			var user = vm.cuser;
			if (user) {
				var formerProject;
				var name = user.firstName + " " + user.lastName;
				var email = user.email;

				for (i = 0; i < vm.projects.length; i++) {
					if (vm.projects[i].members.includes(email)) {
						formerProject = vm.projects[i];
					}
				}

				var email_msg = {
					recipient: email,
					text: "Your current project has been cleared. For more information, please contact a PI.",
					subject: "Project Cleared",
					recipient2: vm.adminSettings.current_email,
					text2: name + " has been successfully removed from project '" + (formerProject ? formerProject : 'unknown') + "'.",
					subject2: "Removed user from project"
				};
				User.nodeEmail(email_msg);

				if (formerProject) {
					for (i = 0; i < formerProject.members_detailed.length; i++) {
						if (formerProject.members_detailed[i] == name) {
							formerProject.members_detailed.splice(i, 1);
						}
					}
					for (i = 0; i < formerProject.members.length; i++) {
						if (formerProject.members[i] == email) {
							formerProject.members.splice(i, 1);
						}
					}
					ProjectService.editProject(formerProject, formerProject._id);
				}
				changeclear_msg();
			}
		};

		var skillrefresh = function () {
			$scope.skillrefresh = true;
			$timeout(function () {
				$scope.skillrefresh = false;
			}, 0);
		};

		var courserefresh = function () {
			$scope.courserefresh = true;
			$timeout(function () {
				$scope.courserefresh = false;
			}, 0);
		};
		var userrefresh = function () {
			$scope.userrefresh = true;
			$timeout(function () {
				$scope.userrefresh = false;
			}, 0);
		};
		var semesterrefresh = function () {
			$scope.semesterrefresh = true;
			$timeout(function () {
				$scope.semesterrefresh = false;
			}, 0);
		};
		var projectrefresh = function () {
			$scope.projectrefresh = true;
			$timeout(function () {
				$scope.projectrefresh = false;
			}, 0);
		};

		//User Story FA18 | VIP-181, mvale080 (added message to show successful skill edit)
		function skillchange_msg() {
			swal({
				title: "Skill Properties have Changed",
				text: "",
				type: "success",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {

			});
		};

		//User Story FA18 | VIP-181, mvale080 (added function to store the skill to delete)
		function SkillDeleteButton(selectedSkill) {
			vm.skilltodelete = selectedSkill;
		};

		//User Story FA18 | VIP-181, mvale080 (added function to delete a skill)
		function DeleteSkill() {
			var deletedSkill = vm.skilltodelete;

			if (deletedSkill) {
				SkillsService.deleteSkill(deletedSkill._id).then(function (success) {
					console.log("Successfully Deleted Skill");
					resetSkiSettings();
					loadSkills();
					skilldelete_msg();
					SkillsService.retrieveSkills().then(function (data) {
						vm.gridOptionsSkill.data = data;
						skillrefresh();
					});
				}, function (error) {});

			}

		};

		//User Story FA18 | VIP-181, mvale080 (added message for successful delete)
		function skilldelete_msg() {
			swal({
				title: "Skill has been Deleted",
				text: "",
				type: "success",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {

			});
		};

		//User Story FA18 | VIP-181, mvale080 (added message for successful skill add)
		function skilladd_msg(skilladded) {
			swal({
				title: "Success",
				text: "Skill " + skilladded + " has been added to the database",
				type: "success",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {});
		}
		//User Story FA18 | VIP-191, mvale080 (added message for successful merge)
		function skillmerge_msg() {
			swal({
				title: "Success",
				text: "Skills haved been merged",
				type: "success",
				confirmButtonText: "Continue",
				allowOutsideClick: true,
				timer: 10000,
			}, function () {});
		}

		//User Story FA18 | VIP-181, mvale080 (added function to add a skill)
		vm.addSkill = function () {
			var errMsg = "";
			if (!$scope.addNewSkillInputSection) {
				errMsg += "\tSkill Missing\n";
				swal({
					title: "Error",
					text: errMsg,
					type: "error",
					confirmButtonText: "Continue",
					allowOutsideClick: true,
					timer: 10000,
				}, function () {});
			} else {
				var skilltoadd = $scope.addNewSkillInputSection;
				console.log("The skill to add is " + skilltoadd);
				var found = false;
				console.log("found is currently " + found);
				vm.skills.forEach(function (skilltocheck) {
					console.log("Now checking " + skilltocheck.skill);
					if (skilltocheck.skill == skilltoadd) {
						console.log("There is a match");
						found = true;
					}
				});
				if (!found) {
					var newSkill = {
						skill: skilltoadd,
						Approved: false
					};
					SkillsService.adminAddSkill(newSkill).then(function (data) {
						skilladd_msg(skilltoadd);
						$scope.addNewSkillInputSection = "";
						SkillsService.retrieveSkills().then(function (data) {
							vm.gridOptionsSkill.data = data;
							skillrefresh();
						});
					});
					loadSkills();
				} else {
					swal({
						title: "Error",
						text: errMsg,
						type: "error",
						confirmButtonText: "Continue",
						allowOutsideClick: true,
						timer: 10000,
					}, function () {});
				}

			}
		};

		//User Story FA18 | VIP-191, mvale080 (added functions to merge skills)
		/*
		Below is the system that merges two skills. Initially an empty list selection is stored in the controller. This list builds a list of skill object dependent
		on a checkbox. endMerge deletes the value of the list selection after merging is finished. checkoption finds the skill the user wants to keep and removes it
		from selection. Then for ever value of selection, that skill is deleted from the database, thus merging the skills.
		*/
		vm.selection = [];

		$scope.toggleSelection = function toggleSelection(skill) {
			var idx = vm.selection.indexOf(skill);

			// is currently selected
			if (idx > -1) {
				vm.selection.splice(idx, 1);
			}

			// is newly selected
			else {
				vm.selection.push(skill);
			}
		};
		vm.endMerge = function () {
			vm.selection = [];
		}

		vm.checkoption = function (selectedSkill) {
			if (selectedSkill != undefined) {
				console.log("Selected Skill " + selectedSkill);
				var inx = vm.selection.indexOf(selectedSkill);
				console.log("Index is " + inx);
				if (inx > -1) {
					vm.selection.splice(inx, 1);
				}
				console.log(vm.selection);
				vm.selection.forEach(function (skill) {
					SkillsService.deleteSkill(skill._id).then(function (success) {
						console.log("Successfully Deleted Skill");
					});
				});
				delete vm.selection;
				loadSkills();
				SkillsService.retrieveSkills().then(function (data) {
					vm.gridOptionsSkill.data = data;
					skillrefresh();
				});
				skillmerge_msg();
			} else {
				console.log("No selected skill");
				swal({
					title: "Error",
					text: errMsg,
					type: "error",
					confirmButtonText: "Continue",
					allowOutsideClick: true,
					timer: 10000,
				}, function () {});
			}
		};


	}
})();