myApp.controller("projectController", function ($scope, myFactory, exportUiGridService, $mdDialog, $http, appConfig, $timeout, $window, $mdSelect, $element) {
	$scope.records = [];
	$scope.empSearchId = "";
	$scope.parentData = {
		"projectId": "",
		"projectName": "",
		"account": "",
		"status": "",
		"action": "",
		"managerIds":[],
		"accountId":"",
		"domainId":"",
		"employeeId": "",
		"employeeName": "",
		"emailId":"",
		"role": "",
		"shift": "",
		"projectId":"",
		"projectName":"",
		"managerId":"",
		"managerName":"",
		"experience":"",
		"designation":"",
		"billableStatus":"",
		"mobileNumber":"",
		"startDate":"",
		"endDate":"",
		"newBillingStartDate":"",
	};

	$scope.managers = [];
	

	

	var getCellTemplate = '<p class="col-lg-12"><i class="fa fa-users fa-2x" aria-hidden="true" style="font-size:1.4em;margin-top:3px;cursor:pointer;"  ng-class="{ \'my-css-class\': grid.appScope.rowFormatter( row ) }" data-placement="center" title="View" onmouseenter="$(this).tooltip(\'show\')" ng-click="grid.appScope.getRowData(row,\'View\')" ></i>' +
		'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i ng-show="row.entity.status == \'Active\'" class="fa fa-pencil-square-o fa-2x" aria-hidden="true" style="font-size:1.5em;margin-top:3px;cursor:pointer;" data-placement="center" title="Edit" onmouseenter="$(this).tooltip(\'show\')" ng-click="grid.appScope.getRowData(row,\'Update\')"></i></p>' ;
	
//	'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-minus-circle fa-2x" aria-hidden="true" style="font-size:1.5em;margin-top:3px;cursor:pointer;" data-placement="left" title="Delete" onmouseenter="$(this).tooltip(\'show\')" ng-click="grid.appScope.getRowData(row,\'Delete\')"></i></p>'
	
	$scope.gridOptions = {

		paginationPageSizes: [10, 20, 30, 40, 50, 100],
		paginationPageSize: 10,
		pageNumber: 1,
		pageSize: 10,
		enableFiltering: true,
		columnDefs: [
			{ field: 'projectName', displayName: 'Project ', enableColumnMenu: false, enableSorting: true, enableFiltering: true },
			{ field: 'domain', displayName: 'Domain ', enableColumnMenu: false, enableSorting: true, enableFiltering: true },
			{ field: 'account', displayName: 'Account ', enableColumnMenu: false, enableSorting: true, enableFiltering: true },
			//{field : 'managerId',displayName: 'Manager ID ', enableColumnMenu: false, enableSorting: false},
			{ field: 'deliveryLeadIds', displayName: 'Delivery Lead / Lead ', cellTemplate: '<div ng-repeat= "item in row.entity[col.field]">{{item.employeeName}}<span ng-hide="$last">,</span></div>', enableColumnMenu: false, enableSorting: true, enableFiltering: false },
			{ field: 'status', displayName: 'Status ', enableColumnMenu: false, enableSorting: true, enableFiltering: false },
			{ name: 'Actions', displayName: 'Actions', cellTemplate: getCellTemplate, enableColumnMenu: false, enableSorting: false, enableFiltering: false, width: 130 }
		]
	};
	$scope.gridOptions.data = $scope.records;
	
	$scope.rowFormatter = function( row ) {
	    return (row.entity.status == 'Active');
	};
	  
	$scope.getRowData = function (row, action) {
		console.log(row.entity);
		$scope.parentData.projectId = row.entity.projectId;
		$scope.parentData.projectName = row.entity.projectName;
		$scope.parentData.account = row.entity.account;
		$scope.parentData.managerIds=row.entity.managerIds;
		$scope.parentData.domain = row.entity.domain;
		$scope.parentData.status = row.entity.status;
		$scope.parentData.accountId = row.entity.accountId;
		$scope.parentData.domainId = row.entity.domainId;
		$scope.parentData.deliveryLeadIds = row.entity.deliveryLeadIds;
		$scope.parentData.projectStartDate = row.entity.projectStartDate;
		$scope.parentData.projectEndDate = row.entity.projectEndDate;
		if (action == "Update")
			$scope.addProject(action, $scope.parentData);
		else if (action == "Delete")
			$scope.deleteRole(row);
		else if (action == "View")
			$scope.viewTeamDetails(action, $scope.parentData);
	}
	
//	function getColumnName() {
//		console.log($scope.gridOptions.data);
//			return 'managerIds';
//	}
	
	$scope.refreshPage = function () {
		$scope.empSearchId = "";
		$scope.getProjects();
		$scope.getManagerDetails();
	}
	getLeads = function(){
		
	}
	
	$scope.getProjects = function () {
		var role = myFactory.getEmpRole();
		var empId = myFactory.getEmpId();
		//var deliveryLeadEmpId = ((role == "Delivery Lead") ? empId : undefined);
		$http({
			method: "GET",
			url: appConfig.appUri + "projects/employeeId/"+empId
		}).then(function mySuccess(response) {
			if(response.data.length > 10){
	    		$scope.gridOptions.enablePaginationControls = true;
	    	}
	    	else{
	    		$scope.gridOptions.enablePaginationControls = false;
	    	}
			$scope.gridOptions.data = response.data.records;

		}, function myError(response) {
			showAlert("Something went wrong while fetching data!!!");
			$scope.gridOptions.data = [];
		});
	};
	$scope.getManagerDetails = function () {
		$http({
			method: "GET",
			url: appConfig.appUri + "employees/managers/"
		}).then(function mySuccess(response) {
			$scope.managers = response.data.records;
		}, function myError(response) {
			showAlert("Something went wrong while fetching data!!!");
			$scope.gridOptions.data = [];
		});
	};
	$scope.validateEmpId = function () {
		var searchId = $scope.empSearchId;
		if (searchId != "" && isNaN(searchId)) {
			showAlert('Please enter only digits');
			$scope.empSearchId = "";
			document.getElementById('empSearchId').focus();
		} else if (searchId != "" && (searchId.length < 5 || searchId.length > 5)) {
			showAlert('Employee ID should be 5 digits');
			$scope.empSearchId = "";
			document.getElementById('empSearchId').focus();
		} else if (searchId != "" && !checkEmpIdRange(searchId)) {
			showAlert('Employee ID should be in between ' + appConfig.empStartId + ' - ' + appConfig.empEndId);
			$scope.empSearchId = "";
			document.getElementById('empSearchId').focus();
		}
	};

	function checkEmpIdRange(searchId) {
		return parseInt(searchId) >= appConfig.empStartId && parseInt(searchId) <= appConfig.empEndId;
	}

	$scope.getEmployeeRole = function (type) {
		var searchId = $scope.empSearchId;
		if (searchId == "" && searchId.length == 0) {
			showAlert('Employee ID is mandatory');
			$scope.empSearchId = "";
			document.getElementById('empSearchId').focus();
		} else if (searchId != "" && !checkEmpIdRange(searchId)) {
			showAlert('Employee ID should be in between ' + appConfig.empStartId + ' - ' + appConfig.empEndId);
			$scope.empSearchId = "";
			document.getElementById('empSearchId').focus();
		} else {
			$scope.gridOptions.data = [];
			getEmployeeRoleData(searchId);
		}
	};

	function getEmployeeRoleData(empId) {
		$http({
			method: "GET",
			url: appConfig.appUri + "employees/employeeId/" + empId
		}).then(function mySuccess(response) {
			if (response.data != "" && response.data.length != 0) {
				$scope.gridOptions.data.push(response.data);
			}
		}, function myError(response) {
			showAlert("Something went wrong while fetching data!!!");
			$scope.refreshPage();
		});
	}

	function showAlert(message) {
		$mdDialog.show($mdDialog.alert().parent(
			angular.element(document.querySelector('#popupContainer')))
			.clickOutsideToClose(true).textContent(message).ariaLabel(
				'Alert Dialog').ok('Ok'));
	}

	$scope.addProject = function (action, userData) {
		$('#home').addClass('md-scroll-mask');
		userData.action = action;
		$mdDialog.show({
			controller: AddProjectController,
			templateUrl: 'templates/newProject.html',
			parent: angular.element(document.body),
			clickOutsideToClose: false,
			locals: { dataToPass: userData, gridOptionsData: $scope.gridOptions.data, managers: $scope.managers },
		})
			.then(function (result) {
				if (result == "Assign") { $scope.refreshPage(); showAlert('Project created successfully'); }
				else if (result == "Update") { $scope.refreshPage(); showAlert('Project updated successfully'); }
				else if (result == "Cancelled") console.log(result);
				else showAlert('Project assigning/updation failed!!!');
			});
	};
	$scope.viewTeamDetails = function (action, userData) {
		$('#home').addClass('md-scroll-mask');
		userData.action = action;
		$mdDialog.show({
			controller: AddProjectController,
			templateUrl: 'templates/projectTeamDetails.html',
			parent: angular.element(document.body),
			clickOutsideToClose: false,
			locals: { dataToPass: userData, gridOptionsData: $scope.gridOptions.data, managers: $scope.managers },
		})
			.then(function (result) {
				if (result == "Assign") {showAlert('Manager assigned successfully');}
				else if (result == "Update") showAlert('Manager updated successfully');
				else if (result == "Cancelled") console.log(result);
				else showAlert('Manager assigning/updation failed!!!');
			});
	};
	$scope.getUnAssignedEmployees = function (action, userData) {
		$('#home').addClass('md-scroll-mask');
		userData.action = action;
		$mdDialog.show({
			controller: AddProjectController,
			templateUrl: 'templates/projectNotAssignedDetails.html',
			parent: angular.element(document.body),
			clickOutsideToClose: false,
			locals: { dataToPass: userData, gridOptionsData: $scope.gridOptions.data, managers: $scope.managers },
		})
			.then(function (result) {
				if (result == "Assign") showAlert('Manager assigned successfully');
				else if (result == "Update") showAlert('Manager updated successfully');
				else if (result == "Cancelled") console.log(result);
				else showAlert('Manager assigning/updation failed!!!');
			});
	};
	$scope.getAllocatedEmployees = function (action, userData) {
		$('#home').addClass('md-scroll-mask');
		userData.action = action;
		$mdDialog.show({
			controller: AddProjectController,
			templateUrl: 'templates/projectAssignedDetails.html',
			parent: angular.element(document.body),
			clickOutsideToClose: false,
			locals: { dataToPass: userData, gridOptionsData: $scope.gridOptions.data, managers: $scope.managers },
		})
			.then(function (result) {
				if (result == "Assign") showAlert('Manager assigned successfully');
				else if (result == "Update") showAlert('Manager updated successfully');
				else if (result == "Cancelled") console.log(result);
				else showAlert('Manager assigning/updation failed!!!');
			});
	};
	$scope.cancel = function () {
		$mdDialog.hide();
	};

	$scope.deleteRole = function (row) {
		$('#home').addClass('md-scroll-mask');
		var confirm = $mdDialog.confirm()
			.clickOutsideToClose(true)
			.textContent('Are you sure you want to delete this project?')
			.ok('Ok')
			.cancel('Cancel');
		$mdDialog.show(confirm).then(function () {
			deleteUserRole(row.entity.projectId);
			$timeout(function () { updateGridAfterDelete(row) }, 500);
		}, function () {
			console.log("Cancelled dialog");
		});
	};

	function deleteUserRole(projectId) {
		var req = {
			method: 'DELETE',
			url: appConfig.appUri + "projects/" + projectId
		}
		$http(req).then(function mySuccess(response) {
			$scope.result = response.data;
			console.log($scope.result);
		}, function myError(response) {
			$scope.result = "Error";
		});
	}

	function deleteTeam(record){
		var urlRequest  = "";
		var loginEmpId = myFactory.getEmpId();
		urlRequest = appConfig.appUri+ "resources?loginEmpId="+loginEmpId;
	var req = {
		method : 'POST',
		url : urlRequest,
		headers : {
			"Content-type" : "application/json"
		},
		data : record
	}
	$http(req).then(function mySuccess(response) {
	$scope.result = "Success";
		$scope.objectId = response.data.id;
	}, function myError(response){
		$scope.result = "Error";
	});
	}
	function updateGridAfterDelete(row) {
		if ($scope.result == "Success" || $scope.result == "") {
			var index = $scope.gridOptions.data.indexOf(row.entity);
			$scope.gridOptions.data.splice(index, 1);
			showAlert('Project deleted successfully');
		} else if ($scope.result == "Error") {
			showAlert('Something went wrong while deleting the role.')
		}

	}

	function AddProjectController($scope, $mdDialog, dataToPass, gridOptionsData, managers, $window, $mdSelect) {
		console.log(managers,dataToPass);
		$scope.templateTitle = dataToPass.action;
		$scope.alertMsg = "";
		$scope.isDisabled = false;
		$scope.result = "";
		$scope.employee;
		$scope.projectModel;
		$scope.isSecondTab = false;
		$scope.prjctStses=["Active","Completed","On Hold","Proposed"];	
		$scope.billableStatuses = ["Billable", "Shadow", "Non-Billable", "Reserved", "Trainee"];
		$scope.employeeShifts = myFactory.getShifts();
		$scope.deliveryLeadIds = dataToPass.deliveryLeadIds;
		var allAccounts = myFactory.getAccounts();
		function getActiveAccounts(){
			var activeAccounts = [];
			for (var i in allAccounts){
				if(allAccounts[i].status == "Active" || allAccounts[i].status == "Y"){
					activeAccounts.push(allAccounts[i]);
				}
			}
			return activeAccounts;
		}
		$scope.accounts = getActiveAccounts();
		$scope.selectedTab = 0;
		$scope.deliveryLeadsSelectedList = [];
		$scope.employeeInTeam = [];
		$scope.employeeRoles = ["Lead","Employee"];
		$scope.accountId = dataToPass.accountId;
		$scope.domainId = dataToPass.domainId;
		$scope.domains = [];
		// code added

		$scope.searchTerm = "";
		$scope.updateSearch = function (e) {
			e.stopPropagation();
		}
		$scope.searchFilter = function (obj) {
			if($scope.searchTerm.length > 3){
	    		var re = new RegExp($scope.searchTerm, 'i');
				return !$scope.searchTerm || re.test(obj.employeeName);
	    	}
	    		return obj;	
		};
		
		var today = new Date();
		$scope.addTab = function () {
			if(! (new Date(dataToPass.projectEndDate) >  today) ){
				$mdDialog.show($mdDialog.alert({
					skipHide: true,
					title:"Attention",
			        textContent: 'Employee cannot be added to Completed Project',
			        ok: 'ok'
			      }));
			}
			else{
				if($scope.isSecondTab === false){
					$scope.templateTitle = "Add";
					$scope.employeeRole = undefined;
					$scope.empBillableStatus = undefined;
					$scope.newBillingStartDate = undefined;
					$scope.employeeShift = undefined;
					$scope.employeeModel = {};
					$('.md-datepicker-input')[0].value = null;
					$('.md-datepicker-input')[1].value = null;
					$('.md-datepicker-input')[2].value = null;
					$scope.startDate = (dataToPass.projectStartDate == null) ? null : new Date(dataToPass.projectStartDate);
					$scope.endDate =   (dataToPass.projectStartDate == null) ? null : new Date(dataToPass.projectEndDate);
					document.getElementsByClassName("md-tab")[1].style.visibility = "visible" ;
					document.getElementsByClassName("md-tab")[2].style.visibility = "hidden" ;
					$scope.isSecondTab = true;
					$scope.selectedTab = 1; 
					$scope.searchTerm = "";				
				}
			}
			
		};		
		var removeTab = function (action) {
			if(action == "Add"){
				if($scope.isSecondTab === true){			
					$('.md-select-value')[0].childNodes[0].innerHTML = null
					$('.md-select-value')[1].childNodes[0].innerHTML = null
					$('.md-select-value')[2].childNodes[0].innerHTML = null
					$('.md-select-value')[3].childNodes[0].innerHTML = null
					$('.md-datepicker-input')[0].value = null;
					$('.md-datepicker-input')[1].value = null;
					$('.md-datepicker-input')[2].value = null;
					$scope.employeeModel = {};
				}		
			}
			$scope.selectedTab = 0;
			document.getElementsByClassName("md-tab")[1].style.visibility = "hidden" ;
			document.getElementsByClassName("md-tab")[2].style.visibility = "hidden" ;
			$scope.isSecondTab = !$scope.isSecondTab;	
		};
		
		$window.addEventListener('click', function (e) {
		if (e.target.type !== 'search') {
			$mdSelect.hide();

		}

	});
		// code added

		$scope.clearSearchTerm = function () {
			console.log($scope.deliveryLeadsSelectedList);

			// $("#lead .lead-search .md-select-value span .md-text").css({
			//  'border': '1px solid #000',
			//  'padding': '1px',
			// }).append('<span class="glyphicon glyphicon-remove" style="margin-left: 5px;"></span>');
			// $(".leads-data").text($("#lead .lead-search .md-select-value span .md-text").text().append('<span class="glyphicon glyphicon-remove" style="margin-left: 5px;"></span>'));
		}

//		$scope.removeSelectedLead = function (item) {
//			var index = $scope.deliveryLeadsSelectedList.indexOf(item);
//			$scope.deliveryLeadsSelectedList.splice(index, 1);
//		}

		$scope.closeSelectBox = function () {
			$mdSelect.hide();
		}

		getSelectedDeliveryLeadIds = function () {
			var deliveryLeadIds = [];
			if($scope.deliveryLeadsSelectedList.name){
				managerIds.push($scope.deliveryLeadsSelectedList.id)
			}
			else{
				deliveryLeadIds.push($scope.deliveryLeadsSelectedList.employeeId)
			}
			
			return deliveryLeadIds;
		}
		
		
		$scope.getEmployeeDetails = function(){
			$http({
		        method : "GET",
		        url : appConfig.appUri + "employees/active/sortByName"
		    }).then(function mySuccess(response) {
		        $scope.employeeList =response.data;
		    }, function myError(response) {
		    	showAlert("Something went wrong while fetching data!!!");
		    	
		    });
		};
		function setDomain(action) {
			$scope.domains.forEach(function(domain){
				if(domain.domainId == dataToPass.domainId){
					$scope.domain = domain
				}
			})
			if($scope.domain.domainId != undefined){
				getManagersAssociatedToDomain($scope.domain.domainId,action);
			}
			else{
				$scope.managerDetails = managers;
			}
		}
		
		if (dataToPass.action == "Assign") {
			$scope.projectId = "";
			$scope.projectName = "";
			$scope.managerId = "";
			$scope.managerName = "";
			$scope.domains;
			$scope.isDisabled = false;
		} else if (dataToPass.action == "Update") {
			$scope.projectId = dataToPass.projectId;
			$scope.projectName = dataToPass.projectName;
			$scope.projectStartDate = (dataToPass.projectStartDate == null) ? null : new Date(dataToPass.projectStartDate);
			$scope.projectEndDate = (dataToPass.projectEndDate == null) ? null : new Date(dataToPass.projectEndDate);
//			$scope.managerId = dataToPass.managerId;
//			$scope.managerName = dataToPass.managerName;
//			var accounts1 = myFactory.getAccounts();
			for (var i = 0; i < $scope.accounts.length; i++) {
				if ($scope.accounts[i].accountName == dataToPass.account) {
					$scope.account = $scope.accounts[i];
				}
			}
			getDomainsAssoicatedToAccount($scope.account.accountId,dataToPass.action);
			$scope.projectStatus = dataToPass.status;
			$scope.managerModel = {
				'employeeName': dataToPass.managerName,
				'employeeId': dataToPass.managerId
			};
			
			$scope.isDisabled = true;
		} else if (dataToPass.action == "View") {
			$scope.projectId = dataToPass.projectId;
			$scope.projectName = dataToPass.projectName;
			$scope.account = dataToPass.account;
			$scope.managerIds=dataToPass.managerIds;
			$scope.projectStatus = dataToPass.status;
			$scope.domain = dataToPass.domain;
			$scope.managerModel = {
				 'employeeName': dataToPass.managerName,
				 'employeeId': dataToPass.managerId
			};
			$scope.projectModel = {
				 'projectName': dataToPass.projectName,
				 'projectId': dataToPass.projectId
		    };
			$scope.status = "Active";
			//$scope.isSecondTab = ($scope.projectId == 'Nisum0000');
			
			var employeeModel = $scope.employeeModel;
			var getCellTemplate1 = '<p class="col-md-6 col-md-offset-3"><i class="fa fa-pencil-square-o fa-2x" aria-hidden="true" style="font-size:1.5em;margin-top:3px;cursor:pointer;" ng-click="grid.appScope.getRowData(row,\'UpdateTeam\')"></i><p>'
			//'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-minus-circle fa-2x" aria-hidden="true" style="font-size:1.5em;margin-top:3px;cursor:pointer;" ng-click="grid.appScope.getRowData(row,\'Delete\')"></i></p>';
			
			var getCellActiveTemplate = '<div ng-show="COL_FIELD==true"><p class="col-lg-12">Y</P></div><div ng-show="COL_FIELD==false"><p class="col-lg-12">N</p></div>';
			$scope.gridOptions = {
				paginationPageSizes: [10, 20, 30, 40, 50, 100],
				paginationPageSize: 10,
				pageNumber: 1,
				pageSize: 10,
				enableFiltering:true,
				columnDefs: [
					{ field: 'employeeId', displayName: 'Emp ID', enableColumnMenu: true, enableSorting: true, width: 100, enableFiltering:true},
					{ field: 'employeeName', displayName: 'Emp Name ', enableColumnMenu: false, enableSorting: false,enableFiltering:true },
//					{ field: 'emailId', displayName: 'Email Id ', enableColumnMenu: false, enableSorting: false },
//					{ field: 'experience', displayName: 'Exp', enableColumnMenu: true, enableSorting: true, width: 80 },
					{field: 'role', displayName:'Role', enableColumnMenu: true, enableSorting: false,enableFiltering:false},
					{ field: 'designation', displayName: 'Designation ', enableColumnMenu: false, enableSorting: false,enableFiltering:false },
//					{ field: 'active', displayName: 'Status ', enableColumnMenu: false, enableSorting: false, cellTemplate: getCellActiveTemplate },
					{ field: 'billableStatus', displayName: 'Billability ', enableColumnMenu: false, enableSorting: false ,enableFiltering:false},
					{name : 'Actions', displayName: 'Actions',cellTemplate: getCellTemplate1, enableColumnMenu: false, enableSorting: false, width:100,enableFiltering: false} 
				]
			};
			$scope.isDisabled = true;
			if($scope.isSecondTab){
				$scope.gridOptions.columnDefs[5].visible = false;
			}
			$http({
				method: "GET",
				url: appConfig.appUri + "resources/project/"+ $scope.projectId + "?status=" + $scope.status
			}).then(function mySuccess(response) {
				if(response.data.length > 10){
		    		$scope.gridOptions.enablePaginationControls = true;
		    	}
		    	else{
		    		$scope.gridOptions.enablePaginationControls = false;
		    	}
				$scope.gridOptions.data = response.data;
				  for(i=0;i<response.data.length;i++){
			    		if(response.data[i].role == 'Lead'){
				    		  $scope.gridOptions.data[i].role = "Lead";
				    	  }else{
				    		  $scope.gridOptions.data[i].role = "Individual Contributor"; 
				    	  }	
			    	}
			}, function myError(response) {
				showAlert("Something went wrong while fetching data!!!");
				$scope.gridOptions.data = [];
			});
			$scope.parentData = {
					"employeeId":"",
					"projectId": "",
					"projectName": "",
					"account": "",
					"status": "",
					"action": "",
					"managerIds":[],
					"accountId":"",
					"domainId":"",
					"employeeId": "",
					"employeeName": "",
					"emailId":"",
					"role": "",
					"shift": "",
					"projectId":"",
					"projectName":"",
					"managerId":"",
					"managerName":"",
					"experience":"",
					"designation":"",
					"billableStatus":"",
					"mobileNumber":"",
					"startDate":"",
					"endDate":"",
					"newBillingStartDate":"",
				};

			$scope.getRowData = function(row, action){
				console.log('row selected',row);
				console.log('action',action);
				$scope.parentData.employeeId = row.entity.employeeId;
				$scope.parentData.employeeName = row.entity.employeeName;
				$scope.parentData.emailId = row.entity.emailId;
				$scope.parentData.id = row.entity.id;
				$scope.parentData.role = row.entity.role;
				$scope.parentData.shift = row.entity.shift;
				$scope.parentData.projectId = row.entity.projectId;
				$scope.parentData.projectName = row.entity.projectName;
				$scope.parentData.experience = row.entity.experience;
				$scope.parentData.designation = row.entity.designation;
				$scope.parentData.billableStatus = row.entity.billableStatus;
				$scope.parentData.shift = row.entity.shift;
				$scope.parentData.mobileNumber = row.entity.mobileNumber;
				$scope.parentData.employeeModel = {}
				$scope.parentData.newBillingStartDate = row.entity.newBillingStartDate;
				$scope.parentData.startDate = new Date(row.entity.startDate);
				$scope.parentData.endDate = new Date(row.entity.endDate);
				if(action == "UpdateTeam"){
					$scope.updateTeamMate(action, $scope.parentData);
				}
				if(action == "Delete"){
					console.log("deleted");
					$scope.deleteTeamMate(row);
					
				}
//				else if(action == "Delete"){
//					$scope.deleteRole(row,$scope.parentData.id);
//			     }else if(action=="ViewTeamDetail"){
//			    	 
//			    	 $scope.viewTeamDetail(action, $scope.parentData);
//			    		
//			     }else if(action=="ViewBillability"){
//			    	 
//			    	 $scope.ViewBillability(action, $scope.parentData);
//			    		
//			     }	
		} 
			document.addEventListener("DOMSubtreeModified", function(e) {
				if(document.getElementsByClassName("md-tab")[1] && (document.getElementsByClassName("md-tab")[1].style.visibility === "")){
					document.getElementsByClassName("md-tab")[1].style.visibility = "hidden" ;
				}
				if(document.getElementsByClassName("md-tab")[2] && (document.getElementsByClassName("md-tab")[2].style.visibility === "")){
					document.getElementsByClassName("md-tab")[2].style.visibility = "hidden" ;
				}
			}, false);
			
			$scope.updateTab = function () {
			//	if($scope.isSecondTab == false){
				    $scope.isSecondTab = !$scope.isSecondTab;
					$scope.templateTitle = "Update";
					document.getElementsByClassName("md-tab")[1].style.visibility = "hidden" ;
					document.getElementsByClassName("md-tab")[2].style.visibility = "visible" ;
					$scope.selectedTab = 2; 
					$scope.searchTerm = "";
					$scope.alertMsg = "";
//				}	
			};
			
			$scope.getTeamMates = function(){
				getProjectDetails($scope.projectId,$scope.status);
			}
			$scope.updateTeamMate = function(action, userData){
				console.log(userData);
				$scope.updateTab();
				$scope.id = userData.id;
				$scope.employeeModel = {
						'employeeName': userData.employeeName,
						'employeeId': userData.employeeId,
						'emailId':userData.emailId,
						'designation': userData.designation
					};
					
//				$scope.employeeModel.employeeId = userData.employeeId;
//				$scope.employeeModel.employeeName = userData.employeeName;
//				$scope.employeeModel.emailId = userData.emailId;
				$scope.empBillableStatus = userData.billableStatus;
				if(userData.role == "Individual Contributor"){
					$scope.employeeRole = "Employee";
				}else{
					$scope.employeeRole = "Lead";
				}
				//$scope.employeeRole = userData.role;
				$scope.employeeShift = userData.shift;
				$scope.newBillingStartDate = new Date(userData.newBillingStartDate);
				$scope.startDate = new Date(userData.startDate);
				$scope.endDate = new Date(userData.endDate);
				//$scope.addTab();
				//$('#home').addClass('md-scroll-mask');
				userData.action = action;
//				$mdDialog.show({
//				      controller: AddProjectController,
//				      templateUrl: 'templates/UpdateTeamMate.html',
//				      parent: angular.element(document.body),
//				      clickOutsideToClose:false,
//				      locals:{dataToPass: userData, gridOptionsData: $scope.gridOptions.data, employees: $scope.employees},
//				    })
//				    .then(function(result) {
//				    	console.log("result");
////				    	if(result == "Add") showAlert('New Teammate assigned successfully');
////				    	else if(result == "Update") {
////				    		$scope.refreshPage();
////				    		showAlert('Teammate updated successfully');
////				    	
////				    	}
////				    	else if(result == "Cancelled") console.log(result);
////				    	else showAlert('Teammate assigning/updation failed!!!');
//				    });
			};
			$scope.deleteTeamMate = function (row) {
				console.log(row);
				$scope.id = row.entity.id;
				$scope.employeeId = row.entity.employeeId;
				$scope.projectId = row.entity.projectId;
				var record = {"id":$scope.id, "employeeId":$scope.employeeId, "projectId":$scope.projectId }
				$mdDialog.show($mdDialog.confirm({
					skipHide: true,
					textContent: 'Are you sure you want to inactivate this teamMate?',
					ok: 'ok',
					cancel:'cancel'
				  })).then(function(){
					  deleteTeam(record);
					  $timeout(function(){
						  getProjectDetails($scope.projectId);
						$mdDialog.show($mdDialog.alert({
								skipHide: true,
						        textContent: 'Employee Inactivated',
						        ok: 'ok'
						      }));
						},500);
			    })
			};
		}else if (dataToPass.action == "UnAssigned") {
			$scope.gridOptions = {
				paginationPageSizes: [10, 20, 30, 40, 50, 100],
				paginationPageSize: 10,
				pageNumber: 1,
				pageSize: 10,
				columnDefs: [
					{ field: 'employeeId', displayName: 'Emp ID', enableColumnMenu: true, enableSorting: true, width: 100 },
					{ field: 'employeeName', displayName: 'Empl Name ', enableColumnMenu: false, enableSorting: false },
					{ field: 'emailId', displayName: 'Email Id ', enableColumnMenu: false, enableSorting: false },
				]
			};
			$scope.isDisabled = true;
			$http({
				method: "GET",
				url: appConfig.appUri + "resources/getUnAssignedEmployees"
			}).then(function mySuccess(response) {
				$scope.gridOptions.data = response.data;
			}, function myError(response) {
				showAlert("Something went wrong while fetching data!!!");
				$scope.gridOptions.data = [];
			});
		} else if (dataToPass.action == "allocated") {
			var getCellTemplate = '<p class="col-lg-12"><i class="fa fa-pencil-square-o fa-2x" aria-hidden="true" style="font-size:1.5em;margin-top:3px;cursor:pointer;" ng-click="grid.appScope.getRowData(row,\'Update\')"></i>'+
			'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-minus-circle fa-2x" aria-hidden="true" style="font-size:1.5em;margin-top:3px;cursor:pointer;" ng-click="grid.appScope.getRowData(row,\'Delete\')"></i></p>';
			
			$scope.gridOptions = {
				paginationPageSizes: [10, 20, 30, 40, 50, 100],
				paginationPageSize: 10,
				pageNumber: 1,
				pageSize: 10,
				columnDefs: [
					{ field: 'employeeId', displayName: 'Emp ID', enableColumnMenu: true, enableSorting: true, width: 100 },
					{ field: 'employeeName', displayName: 'Empl Name ', enableColumnMenu: false, enableSorting: false },
					{ field: 'emailId', displayName: 'Email Id ', enableColumnMenu: false, enableSorting: false },
					{ field: 'projectName', displayName: 'Project ', enableColumnMenu: false, enableSorting: false },
					{ field: 'managerName', displayName: 'Manager ', enableColumnMenu: false, enableSorting: false },
					{ field: 'experience', displayName: 'Exp', enableColumnMenu: true, enableSorting: true, width: 50 },
					{ field: 'designation', displayName: 'Designation ', enableColumnMenu: false, enableSorting: false },
					{ field: 'billableStatus', displayName: 'Billability ', enableColumnMenu: false, enableSorting: false },
				
				],
				enableGridMenu: true,
				enableSelectAll: true,
				exporterMenuExcel: false,
				exporterMenuCsv: false,
				exporterCsvFilename: 'Allocated.csv',
				exporterExcelFilename: 'AllocatedResources',
				exporterPdfDefaultStyle: { fontSize: 9 },
				exporterPdfTableStyle: { margin: [30, 30, 30, 30] },
				exporterPdfTableHeaderStyle: { fontSize: 10, bold: true, italics: true, color: 'red' },
				exporterPdfHeader: { text: "Allocated Resources", style: 'headerStyle' },
				exporterPdfFooter: function (currentPage, pageCount) {
					return { text: currentPage.toString() + ' of ' + pageCount.toString(), style: 'footerStyle' };
				},
				exporterPdfCustomFormatter: function (docDefinition) {
					docDefinition.styles.headerStyle = { fontSize: 22, bold: true };
					docDefinition.styles.footerStyle = { fontSize: 10, bold: true };
					return docDefinition;
				},
				exporterPdfOrientation: 'portrait',
				exporterPdfPageSize: 'LETTER',
				exporterPdfMaxGridWidth: 500,
				exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
				onRegisterApi: function (gridApi) {
					$scope.gridApi = gridApi;
				},
				gridMenuCustomItems: [{
					title: 'Export all data as EXCEL',
					action: function ($event) {
						exportUiGridService.exportToExcel('sheet 1', $scope.gridApi, 'all', 'all');
					},
					order: 110
				},
				{
					title: 'Export visible data as EXCEL',
					action: function ($event) {
						exportUiGridService.exportToExcel('sheet 1', $scope.gridApi, 'visible', 'visible');
					},
					order: 111
				}
				]
			};
			$scope.isDisabled = true;
			$http({
				method: "GET",
				url: appConfig.appUri + "resources/projects"
			}).then(function mySuccess(response) {
				$scope.gridOptions.data = response.data;
			}, function myError(response) {
				showAlert("Something went wrong while fetching data!!!");
				$scope.gridOptions.data = [];
			});
		}
		$scope.getManagers = function () {
			if ($scope.managerModel !== undefined) {
				return $scope.managerModel.employeeName;
			} else {
				return "Please select a manager";
			}
		};
		$scope.getProjectStatus = function () {
			if ($scope.projectStatus !== undefined) {
				return $scope.projectStatus;
			} else {
				return "Please select project status";
			}
		};
		$scope.changeEmpBillableStatus = function(){
			$scope.newBillingStartDate = null;
			if($scope.templateTitle == "Add"){
				$('.md-datepicker-input')[0].value = null;
			}
			else{
				$('.md-datepicker-input')[3].value = null;
			}
		}
		
		var noDomainError = function(){
			$mdDialog.show($mdDialog.alert({
				title: 'Error',
				skipHide: true,
		        textContent: 'No domain added to this account',
		        ok: 'ok'
		      }));
		};
		
		function getDomainsAssoicatedToAccount(id,action){
			$http({
		        method : "GET",
		        url : appConfig.appUri + "domains/"+id
		    }).then(function mySuccess(response) {
		    	var result = response.data;
		    	if(result != "" || result.length != 0){
		    		$scope.domains  = result;
		    	}
		    	else{
//		    		$scope.domains  = [
//		    			{domainName: $scope.account.accountName}
//		    		]
		    		noDomainError();
		    		$scope.domains = [];
		    		$scope.managerDetails = [];
		    	}
		    	if(action == "Update"){
		    		setDomain(action);
		    	}
		    	
		    }, function myError(response) {

		    });
		}
		
		$scope.onAccountChange = function (){
			if ($scope.account !== undefined) {
				getDomainsAssoicatedToAccount($scope.account.accountId);
			}
			$scope.domain = undefined;
			$scope.domains = [];
			$scope.deliveryLeadsSelectedList = {};
			$scope.managerDetails = [];
			$scope.projectStatus = undefined;
		}
		
		$scope.onDomainChange = function (newVal, oldVal){
			
			if(oldVal != ""){
				if(newVal.domainName != (JSON.parse(oldVal)).domainName){
					if($scope.domain.domainId != undefined){
						getManagersAssociatedToDomain($scope.domain.domainId);
					}
					$scope.deliveryLeadsSelectedList = {};
					$scope.managerDetails = [];
					$scope.projectStatus = undefined;	
			}
			}
			else{
				if($scope.domain.domainId != undefined){
					getManagersAssociatedToDomain($scope.domain.domainId);
				}
				$scope.deliveryLeadsSelectedList = {};
				$scope.managerDetails = [];
				$scope.projectStatus = undefined;
			}
					
		}
		
		function setDeliveryLead(){
			$scope.managerDetails.forEach(function(deliveryLead){
				if(deliveryLead.employeeId == dataToPass.deliveryLeadIds[0].employeeId){
					$scope.deliveryLeadsSelectedList = deliveryLead;
				}
			});
		}
		
		$scope.getAccountText = function () {
			if ($scope.account !== undefined) {
				return $scope.account.accountName;
			} else {
				return "Please select account";
			}
		};
		
		$scope.getDomainText = function () {
			if($scope.domain != undefined){
				return $scope.domain.domainName;
			}
			else{
	    		return "Please select domain";
	    	}
			
		};
		
		$scope.getSelectedDeliveryLead = function () {		
			if (Object.keys($scope.deliveryLeadsSelectedList).length > 1 ) {
					return $scope.deliveryLeadsSelectedList.employeeName;
			} else {
					return "Please select a Delivery lead";
			}
		}
		
		
		function getManagersAssociatedToDomain(id,action){
			$http({
		        method : "GET",
		        url : appConfig.appUri + "employees/deliveryLeads/"+id
		    }).then(function mySuccess(response) {
		    	var result = response.data.records;
		    	if(result != "" || result.length != 0){
		    		$scope.managerDetails  = result;
		    	}
		    	if(action == "Update"){
		    		setDeliveryLead();		    	
		    	}
		    	if (action != "Update"){
		    		if(result.length == 1){
		    			$scope.deliveryLeadsSelectedList = result[0];
		    		}
		    	}
		    	
		    }, function myError(response) {
//		    	showProgressDialog("Something went wrong redirecting to login page!!!");
		    });
		}
		
		
		$scope.validateEmpId = function () {
			var searchId = $scope.empId;
			if (searchId != "" && isNaN(searchId)) {
				$scope.alertMsg = "Please enter only digits";
				document.getElementById('empId').focus();
			} else if (searchId != "" && ((searchId.length > 0 && searchId.length < 5) || searchId.length > 5)) {
				$scope.alertMsg = "Employee ID should be 5 digits";
				document.getElementById('empId').focus();
			} else if (searchId != "" && !checkRoleEmpIdRange(searchId)) {
				$scope.alertMsg = 'Employee ID should be in between ' + appConfig.empStartId + ' - ' + appConfig.empEndId;
				document.getElementById('empId').focus();
			} else if (searchId != "" && checkRoleExistence(searchId)) {
				$scope.alertMsg = 'Employee ID is already assigned a role';
				document.getElementById('empId').focus();
			} else {
				$scope.alertMsg = "";
			}
		};

		function checkRoleEmpIdRange(searchId) {
			return parseInt(searchId) >= appConfig.empStartId && parseInt(searchId) <= appConfig.empEndId;
		}

		function checkRoleExistence(searchId) {
			for (var i in gridOptionsData) {
				if (gridOptionsData[i].employeeId == searchId) {
					return true;
				}
			}
			return false;
		}

		$scope.validateEmailId = function () {
			var emailId = $scope.empEmail;
			if (emailId != "" && !validateEmail(emailId)) {
				$scope.alertMsg = "Please enter a valid nisum email id";
				document.getElementById('empEmail').focus();
			} else {
				$scope.alertMsg = "";
			}
		}

		function validateEmail(emailId) {
			var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			if (re.test(emailId)) {
				if (emailId.indexOf("@nisum.com", emailId.length - "@nisum.com".length) !== -1) {
					return true;
				}
			}
			return false;
		}
		
		
		$scope.currentBillabilityDateChange = function(){
			$scope.startDate = $scope.newBillingStartDate ;
		}
		isDataUpdated = function () {
			 console.log(dataToPass);
			if (dataToPass.action == "Update") {
				$scope.previousData = {
					ProjectID: dataToPass.projectId,
					ProjectName: dataToPass.projectName,
					Account: dataToPass.account,
					Domain: dataToPass.domain,
					ProjectStatus: dataToPass.status,
					StartDate:new Date(dataToPass.projectStartDate),
					EndDate:new Date(dataToPass.projectEndDate)
				}
			   console.log($scope.projectStartDate);
				$scope.currentData = {
					ProjectID: $scope.projectId,
					ProjectName: $scope.projectName,
					Account: $scope.account.accountName,
					Domain: $scope.domain.domainName,
					ProjectStatus: $scope.projectStatus,
					StartDate:$scope.projectStartDate,
					EndDate:$scope.projectEndDate
				}
				var predata = JSON.stringify($scope.previousData);
				var curdata = JSON.stringify($scope.currentData);
				var exsistingMangersList = dataToPass.deliveryLeadIds;
				var temp = [];
				temp.push($scope.deliveryLeadsSelectedList);
				var currentMangersList = temp;
				var managerCheck = false;
				if (exsistingMangersList.length === currentMangersList.length) {
					var temp1 = [];
					var temp2 = [];

					for (var i in exsistingMangersList) {
						temp1.push(exsistingMangersList[i].employeeId);
					}
					for (var j in currentMangersList) {
						temp2.push(currentMangersList[j].employeeId);
					}
					for (var k = 0; k < exsistingMangersList.length; k++) {
						if (temp2.indexOf(temp1[k]) > -1) {
							managerCheck = true;
						} else {
							managerCheck = false;
						}
					}
				} else {
					managerCheck = false;
				}
				if (predata === curdata && managerCheck) {
					//$mdDialog.hide('Cancelled'); 
					return false;
				}
				return true
			}

		}
		$scope.validateFields = function (action) {
			var project = $scope.projectId;
			var projectName = $scope.projectName;
			var account = $scope.account;
			var managerId=$scope.managerId;
			var managerName=$scope.managerName;
			var employeeModel = $scope.employeeModel;
			var projectModel = $scope.projectModel;
			var newBillingStartDate = $scope.newBillingStartDate
			
			if(action === "Add" || action =="Update"){
				if(employeeModel == undefined || employeeModel.employeeName == undefined){
					$scope.alertMsg = "Please select a employee";
					angular.element(document.getElementById('selectEmp')).focus();
				}else if($scope.employeeRole == undefined){
					 $scope.alertMsg = "Please select a employee role";
					 angular.element(document.getElementById('empRole')).focus();
				}else if($scope.employeeShift == undefined){
					$scope.alertMsg = "Please select a employee shift";
					 angular.element(document.getElementById('empShift')).focus();
				}
				else if($scope.empBillableStatus == undefined){
				    $scope.alertMsg = "Please select a billable status";
				    angular.element(document.getElementById('empBillableStatus')).focus();
				}else if($scope.startDate == undefined) {
				    $scope.alertMsg = "Please select Start Date";
				    angular.element(document.getElementById('startDate')).focus();
				}
				 else if($scope.endDate == undefined) {
	                 $scope.alertMsg = "Please select End Date";
	                 angular.element(document.getElementById('endDate')).focus();
				 }
				else if($scope.newBillingStartDate == undefined){
	            	 $scope.alertMsg = "Please select new Billing StartDate";
	            	 angular.element(document.getElementById('newBillingStartDate')).focus();
	            }
				else if(employeeModel != undefined && projectModel != undefined && action == "Add" && getExistingRecordProjectStatus(employeeModel.employeeId, projectModel.projectName)){
					$scope.alertMsg = "Employee is already assigned to the selected project";
					return false;
				}
				else if(!(($scope.newBillingStartDate >= new Date(dataToPass.projectStartDate)) && ($scope.newBillingStartDate <= $scope.endDate))){
						$scope.alertMsg = $scope.empBillableStatus + " start date should be in between start date and end date";
				} 
				else if (!(($scope.newBillingStartDate >= $scope.startDate) && ($scope.newBillingStartDate <= $scope.endDate)) && action == "Update"){
						$scope.alertMsg = $scope.empBillableStatus + " start date should be in between start date and end date";
				}else if($scope.endDate > new Date(dataToPass.projectEndDate)){
					$scope.alertMsg = "End date should not exceed project end date";
				}
				else {
					$scope.alertMsg = "";
					var record = {"id":$scope.id,"employeeId":employeeModel.employeeId, "employeeName":employeeModel.employeeName, "emailId": employeeModel.emailId, "designation":employeeModel.designation,"projectId":project,"projectName":projectName,"managerId":managerId,"managerName":managerName,"mobileNumber":employeeModel.mobileNumber,"active":true,"billableStatus":$scope.empBillableStatus,"startDate":$scope.startDate,"endDate":$scope.endDate,"account":account,"role":$scope.employeeRole,"newBillingStartDate":newBillingStartDate,"accountId":$scope.accountId,"domainId":$scope.domainId,"shift":$scope.employeeShift,"projectStartDate":$scope.startDate,"projectEndDate":$scope.endDate};
					if(action == "Add"){
						addRecord(record,action);	
						$scope.myForm.$setPristine();					
					} else if (action == "Update") {
						if ($scope.DataUpdate() != true) {
							$mdDialog.show($mdDialog.alert({
								skipHide: true,
								title: 'Attention',
								textContent: 'There is no data change to Update',
								ok: 'ok'
							}))
						}
						else {
							updateTeamRecord(record, action);
						}

					}
				}
			}
		};
		$scope.validateProjectFields = function (action){
			var domain = $scope.domain;
			var account = $scope.account;
			var projectName = $scope.projectName;
			var deliveryLeadsSelectedList = $scope.deliveryLeadsSelectedList;
			var projectStartDate = $scope.projectStartDate;
			var projectEndDate = $scope.projectEndDate;
			var projectStatus =  $scope.projectStatus; 

			if (action == "Assign" || action == "Update")
			if (projectName == "") {
				$scope.alertMsg = "Project Name is mandatory";
				document.getElementById('projectName').focus();
			}else if(projectName !="" && !validateTextFields(projectName)){
				$scope.alertMsg = "Please enter alphabets only";
				document.getElementById('projectName').focus();
			}else if (account == undefined || account == "") {
				$scope.alertMsg = "Account is mandatory";
				document.getElementById('account').focus();
	
			} else if (domain == undefined || domain == "") {
				$scope.alertMsg = "Domain is mandatory";
				document.getElementById('domain').focus();
			}
			 else if(deliveryLeadsSelectedList.employeeName == undefined || deliveryLeadsSelectedList.employeeName == ""){
				$scope.alertMsg = "Please select a Delivery Lead";
			 document.getElementById('deliveryLead').focus();
			 }
			 else if(projectStatus == undefined){
				$scope.alertMsg = "Please select a Project Status";
				 document.getElementById('projectStatus').focus();
				 }
			 else if (projectStartDate == undefined){
				 $scope.alertMsg = "Please select project start date";
				 document.getElementById('projectStartDate').focus();
			 }
			 else if (projectEndDate == undefined){
				 $scope.alertMsg = "Please select project end date";
				 document.getElementById('projectEndDate').focus();
			 }
			 else if (projectStartDate >= projectEndDate){
				 $scope.alertMsg = "Start date should not be greater than end date";
			 }
			else {
				$scope.alertMsg = "";
				console.log($scope.projectStatus,$scope.domain.domainId);
				var record = { "projectId": $scope.projectId, "projectName": $scope.projectName,"account": $scope.account.accountName, "domain": $scope.domain.domainName, "accountId":$scope.account.accountId, "domainId": $scope.domain.domainId, "managerIds": [], "deliveryLeadIds":getSelectedDeliveryLeadIds(), "status": $scope.projectStatus, "projectStartDate": $scope.projectStartDate, "projectEndDate": $scope.projectEndDate };
				console.log(record);
				if(action == "Update"){
					if (isDataUpdated() != true) {
						$mdDialog.show($mdDialog.alert({
							skipHide: true,
							title: 'Attention',
							textContent: 'There is no data change to Update',
							ok: 'ok'
						}))
					}
					else {
						addOrUpdateProject(record, $scope.templateTitle);
//						$timeout(function () { updateGrid($scope.templateTitle, record) }, 500);
					}
				}else{
					addOrUpdateProject(record, $scope.templateTitle);
//					$timeout(function () { updateGrid($scope.templateTitle, record) }, 500);
				}	
		}}
		$scope.cancel = function () {
			var showConfirmDialog = false;
			if (dataToPass.action == "Update") {
				if ($scope.domain != undefined) {
					if (isDataUpdated() != true) {
						$mdDialog.hide('Cancelled');
					}
					else {
						$mdDialog.show($mdDialog.confirm({
							skipHide: true,
							textContent: 'Are you sure you want to cancel this?',
							ok: 'ok',
							cancel: 'cancel'
						})).then(function () {
							$mdDialog.hide('Cancelled');
						})
					}
				}
				else {
					$mdDialog.show($mdDialog.confirm({
						skipHide: true,
						textContent: 'Are you sure you want to cancel this?',
						ok: 'ok',
						cancel: 'cancel'
					})).then(function () {
						$mdDialog.hide('Cancelled');
					})
				}

			}
			if (dataToPass.action == "Assign") {
				var totalFields = $scope.myForm.$$controls;
				for (key in totalFields) {
					console.log("Model value of" + key + " ==>" + totalFields[key].$modelValue)
					if (totalFields[key].$modelValue !== '' && totalFields[key].$modelValue !== undefined && totalFields[key].$modelValue.length !== 0) {
						console.log("Came here!");
						showConfirmDialog = true;
					}
				}
				if (showConfirmDialog) {
					$mdDialog.show($mdDialog.confirm({
						skipHide: true,
						textContent: 'Are you sure you want to cancel this?',
						ok: 'ok',
						cancel: 'cancel'
					})).then(function () {
						$mdDialog.hide('Cancelled');
					})
				}
				else {
					$mdDialog.hide('Cancelled');
				}
			}
		};
		    $scope.cancelDialog = function() {
			$mdDialog.hide('Cancelled');
		       };
		$scope.DataUpdate = function () {
			var data = $scope.parentData;
			if (data.role == "Individual Contributor") {
				var roleselected = "Employee";
			} else {
				roleselected = data.role;
			}
			$scope.previousData = {
				Role: roleselected,
				Shift: data.shift,
				Billabilitystatus: data.billableStatus,
				newBilligStartDate: new Date(data.newBillingStartDate),
				Startdate: data.startDate,
				Enddate: data.endDate
			},
				$scope.currentData = {
					Role: $scope.employeeRole,
					Shift: $scope.employeeShift,
					Billabilitystatus: $scope.empBillableStatus,
					newBilligStartDate: $scope.newBillingStartDate,
					Startdate: $scope.startDate,
					Enddate: $scope.endDate
				}
			var predata = JSON.stringify($scope.previousData);
			var curdata = JSON.stringify($scope.currentData);
			if (predata == curdata) {
				return false;
			}
			return true;
		}
		$scope.cancelTab = function () {
			if (dataToPass.action == "View") {
				if ($scope.templateTitle == "Update") {
					if ($scope.DataUpdate() == false) {
						removeTab("cancel");
					}
					else {
						$mdDialog.show($mdDialog.confirm({
							skipHide: true,
							textContent: 'Are you sure you want to cancel this?',
							ok: 'ok',
							cancel: 'cancel'
						})).then(function () {
							removeTab("cancel");
							$scope.myForm.$setPristine();
						})
					}

				}
				if ($scope.templateTitle == "Add") {
					console.log($scope.myForm);
					if ($scope.myForm.$dirty) {
						$mdDialog.show($mdDialog.confirm({
							skipHide: true,
							textContent: 'Are you sure you want to cancel this?',
							ok: 'ok',
							cancel: 'cancel'
						})).then(function () {
							removeTab("cancel");
							$scope.myForm.$setPristine();
						})
					}
					else {
						removeTab("cancel")

					}
				}
			}
		};
		
		$scope.getEmployeeSelected = function(){
			if ($scope.employeeModel != undefined ) {
				if(Object.keys($scope.employeeModel).length > 1){
					$scope.employee=$scope.employeeModel;
					return $scope.employeeModel.employeeName;
				}
				else {
					return "Please select a employee";
				}
				
			} else {
				return "Please select a employee";
			}
		};
		$scope.getSelectedEmpRole = function(){
            if ($scope.employeeRole != undefined ) {
                return $scope.employeeRole;
            } else {
                return "Please select a employee role";
            }
        }
		$scope.getSelectedEmpShift = function(){
            if ($scope.employeeShift != undefined ) {
                return $scope.employeeShift;
            } else {
                return "Please select a employee shift";
            }
        }
		
//		$scope.getProjectSelected = function(){
//			if ($scope.projectModel !== undefined) {
//				$scope.project=$scope.projectModel;
//				return $scope.projectModel.projectName;
//			} else {
//				return "Please select a project";
//			}
//		};
		$scope.getSelectedBillableStatus = function(){
            if ($scope.empBillableStatus != undefined ) {
                return $scope.empBillableStatus;
            } else {
                return "Please select a billable status";
            }
        };
		
		function updateGrid(action, record) {
			if ($scope.alertMsg == "") {
				if ($scope.result == "Success") {
					if (action == "Assign") {
						gridOptionsData.push(record);
						$mdDialog.hide(action);
					} else if (action == "Update") {
						var existingRecord = getRowEntity($scope.projectId);
						var index = gridOptionsData.indexOf(existingRecord);
						gridOptionsData[index] = record;
						$mdDialog.hide(action);

					}
					else if(action == "Add"){
						$scope.gridOptions.data.push(record);
						console.log($scope.gridOptions.data);
						for(i=0;i<$scope.gridOptions.data.length;i++){
				    		if($scope.gridOptions.data[i].role == 'Lead'){
					    		  $scope.gridOptions.data[i].role = "Lead";
					    	  }else{
					    		  $scope.gridOptions.data[i].role = "Individual Contributor"; 
					    	  }	
				    	}
					}
				} else {
					$mdDialog.hide("Error");
				}

			}
		}

		function addRecord(record, action){
			var urlRequest  = "";
			var loginEmpId = myFactory.getEmpId();
				urlRequest = appConfig.appUri+ "addEmployeeToTeamWithCheck?loginEmpId="+loginEmpId;
			var req = {
				method : 'POST',
				url : urlRequest,
				headers : {
					"Content-type" : "application/json"
				},
				data : record
			}
			$http(req).then(function mySuccess(response) {
			$scope.result = "Success";
			var titleOfModel = "Attention";
//				$scope.objectId = response.data.id;
			if(response.data =="TeamMate added successfuly"){
				titleOfModel = "";
				$timeout(function(){
					updateGrid(action,record);
					removeTab('Add');
				},500);
			}
				$mdDialog.show($mdDialog.alert({
					skipHide: true,
					title:titleOfModel,
			        textContent: response.data,
			        ok: 'ok'
			      }));
			
			}, function myError(response){
				$scope.result = "Error";
			});
		}
		function getProjectDetails(projectId,status){
			$http({
				method: "GET",
				url: appConfig.appUri + "resources/project/"+ $scope.projectId + "?status=" + $scope.status
			}).then(function mySuccess(response) {
				$scope.gridOptions.data = response.data;
				if(status == "InActive" || status == "Both"||  dataToPass.status == "InActive"){
		    		$scope.gridOptions.columnDefs[5].visible = false;
		    	}
		    	else{
		    		$scope.gridOptions.columnDefs[5].visible = true;
		    	}
				for(i=0;i<$scope.gridOptions.data.length;i++){
		    		if($scope.gridOptions.data[i].role == 'Lead'){
			    		  $scope.gridOptions.data[i].role = "Lead";
			    	  }else{
			    		  $scope.gridOptions.data[i].role = "Individual Contributor"; 
			    	  }	
		    	}
			}, function myError(response) {
				showAlert("Something went wrong while fetching data!!!");
				$scope.gridOptions.data = [];
			});
		}
		function updateTeamRecord(record, action){
			var urlRequest  = "";
			var loginEmpId = myFactory.getEmpId();
			urlRequest = appConfig.appUri+ "resources?loginEmpId="+loginEmpId;
		var req = {
			method : 'PUT',
			url : urlRequest,
			headers : {
				"Content-type" : "application/json"
			},
			data : record
		}
		$http(req).then(function mySuccess(response) {
			console.log("Hi I am Here");
		$scope.result = "Success";
		if(response.data == "TeamMate updated successfuly" || response.data.includes("Resource Successfully moved from") ){
			$timeout(function () {
				getProjectDetails($scope.projectId, $scope.status);
				removeTab('Add');
			}, 500);
		}
			$mdDialog.show($mdDialog.alert({
				skipHide: true,
				textContent: response.data,
				ok: 'ok'
			})).then(function () {
				$scope.myForm.$setPristine();
			})
//			$scope.objectId = response.data.id;
			
		}, function myError(response){
			$scope.result = "Error";
		});
			
		}

		function addOrUpdateProject(record, action) {
			var urlRequest = "";
			var requestMethod = "";
			var loginEmpId = myFactory.getEmpId();
			if (action == "Assign") {
				urlRequest = appConfig.appUri + "projects?loginEmpId="+loginEmpId;
				requestMethod = 'POST';
			} else if (action == "Update") {
				urlRequest = appConfig.appUri + "projects/"+record.projectId+"?loginEmpId="+loginEmpId;
				requestMethod = 'PUT';
			}
			var req = {
				method: requestMethod,
				url: urlRequest,
				headers: {
					"Content-type": "application/json"
				},
				data: record
			}
			$http(req).then(function mySuccess(response) {
				console.log(response.data);
				if(response.data.message == "Project name already exist !!! try with new"){
					$mdDialog.show($mdDialog.alert({
						skipHide: true,
						title:'Attention',
				        textContent: response.data.message,
				        ok: 'ok'
				      }));
				}
				else{
					$scope.result = "Success";
					$timeout(function () { updateGrid($scope.templateTitle, record) }, 500);
				}
				
			}, function myError(response) {
				$scope.result = "Error";
			});
		}

		function getRowEntity(empId) {
			for (var i = 0; i < gridOptionsData.length; i++) {
				var record = gridOptionsData[i];
				if (record.projectId == empId) {
					return record;
				}
			}
		}
		
		function getExistingRecordProjectStatus(empId, projectName){
			for(var i=0;i<$scope.gridOptions.data.length;i++){
				var record = $scope.gridOptions.data[i];
				if(record.employeeId == empId){
					if(record.active == true && record.projectName == projectName)
						return true;
				}
			}
			return false;
		}
		function validateTextFields(name){
			var pattern = /^[a-zA-Z\s]*$/;
			if(pattern.test(name)){
				return true;
			}
			return false;
		}
	}
});
