app.ng.controller("App.Controller.About", ["$scope", "$rootScope",function ($scope, $rootScope) {

	

}]);
app.ng.controller("App.Controller.Admin", ["$scope", "$rootScope", "$http", "$state", function ($scope, $rootScope, $http, $state) {

    if (!$rootScope.isAdmin) {
        $state.go("403");
    }

    $scope.loadStages = function () {
        $rootScope.$broadcast('loaderStart', {});
        var url = '/Api/Stage/All'
        $http.get(url, {}).success(function (result) {
            $scope.stages = result;
            $rootScope.$broadcast('loaderEnd', {});
        });
    }


    $scope.loadStages();

    $rootScope.$on('indicatorTreeChange', function () {
        $scope.loadStages();
    });

}]);
app.ng.controller("App.Controller.Analysis", ["$scope", "$rootScope",function ($scope, $rootScope) {

	

}]);
app.ng.controller("App.Controller.ChangePassword", ["$scope", "$rootScope", "$http", "growl", function ($scope, $rootScope,$http,growl) {
	$scope.entity = {};
	$scope.ChangePassword = function() {
		
		if ($scope.entity.CurrentPassword != null && $scope.entity.NewPassword != null && $scope.entity.ConfirmPassword != null) {
			if ($scope.entity.NewPassword == $scope.entity.ConfirmPassword) {
				if ($scope.entity.NewPassword == $scope.entity.CurrentPassword) {
					growl.addErrorMessage("New password shouldn't be the same as current password");
					return false;
				}
				$rootScope.$broadcast('loaderStart', {});
				var url = '/Account/ChangeUserPassword';
				$http.post(url, $scope.entity).success(function (result) {
					$rootScope.$broadcast('loaderEnd', {});
					if (result != "") {
						growl.addErrorMessage(result);
					} else {
						growl.addSuccessMessage('Password changed successfully');
					}
					
				});
			} else {
				growl.addErrorMessage("Passwords Don't Match");
				return false;
			}
		}
		return false;
	}
}]);
app.ng.controller("App.Controller.Dashboard", ["$scope", "$rootScope",function ($scope, $rootScope) {

	

}]);
app.ng.controller("App.Controller.DocumentList", ["$scope", "$rootScope", "$http", "$upload", "urls", "$timeout", "growl", function ($scope, $rootScope, $http, $upload, urls, $timeout, growl) {

    $scope.urls = urls;


    if ($scope.$parent) {
        $scope.$watch('$parent.updateDocsTrigger', function (newValue, oldValue) {
            if (newValue !== oldValue) {
                $timeout($scope.getDocuments, 100);
            }
        }, true);
    }

    $scope.uploadFile = function ($files) {
        $rootScope.$broadcast('loaderStart', {});
        $scope.loadingDocs = [];
        for (var i = 0; i < $files.length; i++) {
            var file = $files[i];
            $scope.loadingDocs.push(i);
            $scope.upload = $upload.upload({
                url: '/Document/Upload',
                data: { entityGuid: $scope.entityGuid },
                file: file,
            }).progress(function (evt) {
                console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
            }).success(function (data, status, headers, config) {
                $scope.fragments = data;
                $scope.loadingDocs.pop();
                if (!$scope.loadingDocs.length) {
                    $rootScope.$broadcast('loaderEnd', {});
                    $scope.getDocuments();
                }
            });

        }
    }

    $scope.getDocuments = function () {
        var url = app.root + '/Api/Document/ForEntity';
        $http.get(url, { params: { guid: $scope.entityGuid } }).success(function (result) {
            $scope.documents = result;
        });
    }

    $timeout($scope.getDocuments, 100);

    $scope.deleteDocument = function (document) {
        if (confirm("Are you sure you want to delete this document?")) {
            var url = app.root + '/Api/Document/Delete';
            $http.post(url, document ).success(function (result) {
                $scope.getDocuments();
                growl.addSuccessMessage('Document deleted');
            });
        }
    }

}]);
app.ng.controller("App.Controller.Documents", ["$scope", "$rootScope", "urls", "$http", "$state", "routeInfo", "$uibModalInstance", "$upload", function ($scope, $rootScope, urls, $http, $state, routeInfo, $uibModalInstance, $upload) {

    if (!$scope.editMode) {
        $scope.editMode = routeInfo.editMode;
    }
    $scope.routeInfo = routeInfo;

    $scope.loadingDocs = [];
    $scope.statuses = [{ Id: 1, Name: "Draft" }, { Id: 2, Name: "Published" }];

    $scope.load = function () {
        $rootScope.$broadcast('loaderStart', {});
        if (routeInfo.processId) {
            $http.get(urls.document.api.getForProcess(routeInfo.processId), {}).success(function (result) {
                $scope.documents = result;
                $rootScope.$broadcast('loaderEnd', {});
            });
        }
    }
    $scope.load();


    $scope.uploadFile = function ($files) {
        $rootScope.$broadcast('loaderStart', {});
        $scope.loadingDocs = [];
        for (var i = 0; i < $files.length; i++) {
            var file = $files[i];
            $scope.loadingDocs.push(i);
            $scope.upload = $upload.upload({
                url: urls.document.upload(),
                data: { processId: routeInfo.processId },
                file: file,
            }).progress(function (evt) {
                console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
            }).success(function (data, status, headers, config) {
                $scope.fragments = data;
                $scope.loadingDocs.pop();
                if (!$scope.loadingDocs.length) {
                    $scope.load();
                }
            });

        }
    }

    $scope.update = function (document) {
        $rootScope.$broadcast('loaderStart', {});
        $http.post(urls.document.api.update(), document).success(function (result) {
            $rootScope.$broadcast('loaderEnd', {});
        });

    }

    $scope.deleteDocument = function (document) {
        if (confirm("Are you sure you want to delete this document?")) {
            $http.post(urls.document.api.delete(), document).success(function (result) {
                $scope.load();
            });
        }
    }

}]);
app.ng.controller("App.Controller.Guidance", ["$scope", "$rootScope",function ($scope, $rootScope) {

	

}]);
app.ng.controller("App.Controller.Home", ["$scope", "$rootScope", "$http", "urls", "$state", "$cookies", function ($scope, $rootScope, $http, urls, $state, $cookies) {
	$scope.urls = urls;

	
	var cookie = $cookies.get('icat-redirect')
	if (cookie) {
	    $cookies.remove('icat-redirect')
	    $state.go(cookie);
	}

}]);
app.ng.controller("App.Controller.IndicatorOverview", ["$scope", "$rootScope", "$http", function ($scope, $rootScope, $http) {

    $scope.loadOverview = function () {
        var url = app.root + '/Api/Indicator/Overview';
        $http.get(url, { params: { indicatorId: $scope.indicatorId, assessmentId: $scope.assessmentId, sectorId: $scope.sectorId } }).success(function (result) {
            $scope.overview = result;
            $rootScope.$broadcast('loaderEnd', {});
        });
    }

    $scope.loadOverview();

}]);
app.ng.controller("App.Controller.List", ["$scope", "$rootScope", "$http", "routeInfo", "$state", "growl", function ($scope, $rootScope, $http, routeInfo, $state, growl) {

    if (!$rootScope.loggedIn) {
        $state.go("403");
    }

    $scope.sort = function (field) {
        if ($scope.filter.SortBy == field) {
            $scope.filter.SortDescending = !$scope.filter.SortDescending;
        }
        else {
            $scope.filter.SortBy = field;
            $scope.filter.SortDescending = false;
        }
        $scope.load();
    }

    $scope.load = function () {
        $rootScope.$broadcast('loaderStart', {});
        var url = app.root + '/Api/' + routeInfo.entityName + '/Search';
        $http.get(url, { params: $scope.filter }).success(function (result) {
            $scope.entities = result.Entities;
            $scope.count = result.TotalCount;
            $rootScope.$broadcast('loaderEnd', {});
        });
    }

    $scope.pageChanged = function () {
        $scope.load();
    }

    $scope.resetFilter = function () {
        $scope.filter = { SortBy: 'Id', SortDescending: false, PageSize: 10, PageIndex: 1 };
        $scope.load();
    }
    $scope.resetFilter();


    $scope.delete = function (entity) {
        if (confirm("Are you sure you want to delete this item?")) {
            var url = '/Api/'+ routeInfo.entityName + '/Delete';
            $http.post(url, entity).success(function (result) {
                growl.addSuccessMessage('Item deleted');
                $scope.load();
            });
        }
    }


    $scope.clone = function (entity) {
        if (confirm("Are you sure you want to copy this item?")) {
            $rootScope.$broadcast('loaderStart', {});
            var url = '/Api/' + routeInfo.entityName + '/Clone';
            $http.post(url, entity).success(function (result) {
                $rootScope.$broadcast('loaderEnd', {});
                $scope.load();
                growl.addSuccessMessage('Item copied successfully')
            });
        }
    }

}]);
app.ng.controller("App.Controller.ManageUsers", ["$scope", "$rootScope", "$http", "urls", "growl",
	function ($scope, $rootScope, $http, urls, growl) {

    $scope.inviteStatuses = [
        "Created",
        "Accepted",
        "Rejected"
    ]

    $scope.userStatuses = [
        "Active",
        "Deactivated"
    ]

    $scope.resetUserFilter = function () {
        $scope.userFilter = { SortBy: 'Id', PageIndex: 1, PageSize: 10, Statuses: [] };
        $scope.searchUsers();
    }


    $scope.resetInviteFilter = function () {
        $scope.inviteFilter = { SortBy: 'Id', PageIndex: 1, PageSize: 10, Statuses: ['Created'] };
        $scope.searchInvites();
		}

		$scope.resetPendingUsersFilter = function () {
			$scope.PendingUsersFilter = { SortBy: 'Id', PageIndex: 1, PageSize: 10 };
			$scope.searchPendingUsers();
		}
   
    $scope.searchUsers = function () {
        $rootScope.$broadcast('loaderStart', {});
        $http.get(urls.user.api.search(), { params: $scope.userFilter }).success(function (result) {
            $scope.users = result.Users;
            $scope.userCount = result.TotalCount;
            $rootScope.$broadcast('loaderEnd', {});
        });
    }
  

    $scope.searchInvites = function () {
        $rootScope.$broadcast('loaderStart', {});
        $http.get(urls.user.api.searchInvites(), { params: $scope.inviteFilter }).success(function (result) {
            $scope.invites = result.Invites;
            $scope.inviteCount = result.TotalCount;
            $rootScope.$broadcast('loaderEnd', {});
        });
    }
   
		$scope.searchPendingUsers = function () {
			$rootScope.$broadcast('loaderStart', {});
			$http.get(urls.user.api.searchPendingUsers(), { params: $scope.PendingUsersFilter }).success(function (result) {
				$scope.PendingUsers = result.PendingUsers;
				$scope.PendingUsersCount = result.TotalCount;
				$rootScope.$broadcast('loaderEnd', {});
			});
		}

    $scope.reactivate = function (user) {
        if (confirm("Are you sure you want to reactivate this account?")) {
            $rootScope.$broadcast('loaderStart', {});
            $http.post(urls.user.api.reactivate(), user).success(function (result) {
				user.DateActivated = new Date();
	            user.StatusString = "Active";
				$rootScope.$broadcast('loaderEnd', {});
	            growl.addSuccessMessage('User reactivated successfully');
            });
        }
    }

		$scope.deactivate = function (user) {
			if (confirm("Are you sure you want to deactivate this account?")) {
				$rootScope.$broadcast('loaderStart', {});
				$http.post(urls.user.api.deactivate(), user).success(function(result) {
					user.DateActivated = null;
					user.StatusString = "Deactivated";
					$rootScope.$broadcast('loaderEnd', {});
					growl.addSuccessMessage('User deactivated successfully');
				});
			}
		}

		$scope.resendInvitation = function (user) {
			if (confirm("Are you sure you want to resend invitation for this account?")) {
				$rootScope.$broadcast('loaderStart', {});
				$http.post(urls.user.api.acceptInvite(), user).success(function (result) {
					$rootScope.$broadcast('loaderEnd', {});
					growl.addSuccessMessage('Invitation is resent successfully');
				});
			}
		}

    $scope.acceptInvite = function (invite) {
        if (confirm("Are you sure you want to activate this account?")) {
            $rootScope.$broadcast('loaderStart', {});
            $http.post(urls.user.api.acceptInvite(), invite).success(function (result) {
                invite.DateSent = new Date();
                invite.StatusString = 'Accepted'
                $rootScope.$broadcast('loaderEnd', {});
            });
        }
    }

    $scope.rejectInvite = function (invite) {
        if (confirm("Are you sure you want to reject this account?")) {
            $rootScope.$broadcast('loaderStart', {});
            $http.post(urls.user.api.rejectInvite(), invite).success(function (result) {
                invite.DateRejected= new Date();
                invite.StatusString = 'Rejected'
                $rootScope.$broadcast('loaderEnd', {});
            });
        }
    }

    $scope.resetUserFilter();
    $scope.resetInviteFilter();
	$scope.resetPendingUsersFilter();
}]);
app.ng.controller("App.Controller.Root", ["$scope", "$rootScope", "$http", "urls", "$timeout", "$sce", "$location", "growl", "appTranslator","$window",
	function ($scope, $rootScope, $http, urls, $timeout, $sce, $location, growl, appTranslator, $window) {

    $scope.isCollapsed = false;
    $scope.searchText = '';
	$scope.sce = $sce;
	$rootScope.preferredLanguage = "English";
	$scope.enums = window.enums;
	$rootScope.loggedIn = window.loggedIn;
	$rootScope.isAdmin = window.isAdmin;



    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {      
        $timeout($scope.trackPage, 0)
	});

	$scope.trackPage = function () {
        var model = { Url: window.location.href }
        $http.post(urls.pageLoad.api.track(), model).success(function () {

        });
    }



    $rootScope.$on('$stateChangeStart',
     function (event, toState, toParams, fromState, fromParams) {
         if ($rootScope.scoreDirty && !$rootScope.indicatorContent) {
             growl.addErrorMessage('As you have entered a score for this indicator, you must enter a justification')
             event.preventDefault();
         }
     })

    $scope.isActive = function (route) {
        return $location.url().indexOf(route) > -1;
    }

	$scope.getPreferredLanguage = function () {
		$rootScope.preferredLanguage = appTranslator.getCurrentLanguage();
		$scope.PreferredLanguageList =
			$scope.enums.PreferredLanguageType.filter(a => a.Name != $rootScope.preferredLanguage);
	}

	$scope.getPreferredLanguage();
	$scope.updateLanguage = function (option) {
		$rootScope.$broadcast('loaderStart', {});
		$rootScope.preferredLanguage = option.Name;
		$http.post(urls.user.api.updatePreferredLanguage(), { preferredLanguage: $scope.preferredLanguage }).success(function (result) {
			$rootScope.preferredLanguage = $scope.enums.PreferredLanguageType.find(t => t.Value === result.PreferredLanguage).Name;
			appTranslator.set($rootScope.preferredLanguage);
			$scope.PreferredLanguageList =
				$scope.enums.PreferredLanguageType.filter(a => a.Name != $rootScope.preferredLanguage);
			$rootScope.$broadcast('loaderEnd', {});
			$window.location.reload();
		});
	};
		$rootScope.assessmentLevels = $scope.enums.AssessmentLevel.filter(a => a.Value != 2);
		$rootScope.assessmentTypes = $scope.enums.AssessmentType;

	}]);
app.ng.controller("App.Controller.Stages", ["$scope", "$rootScope", "$http", "$uibModal", function ($scope, $rootScope, $http, $uibModal) {


    $scope.load = function () {
        $rootScope.$broadcast('loaderStart', {});
        var url = '/Api/Stage/All'
        $http.get(url, {}).success(function (result) {
            $scope.stages = result;
            $rootScope.$broadcast('loaderEnd', {});
        });
    }


    $scope.load();

    $scope.selectStage = function (stage) {
        $scope.selectedStage = stage;
    }

    $scope.addIndicator = function () {
        $scope.selectedStage.Indicators.push({ editing: true });
    }

    $scope.editIndicator = function (indicator) {
        indicator.editing = true;
    }

    $scope.saveIndicator = function (indicator) {
        indicator.editing = false;
        $scope.saveStage($scope.selectedStage);
    }

    $scope.saveStage = function (stage) {
        var url = '/Api/Stage/Update'
        $http.post(url, stage).success(function (result) {
            $scope.selectedStage = result;
            $rootScope.$broadcast('loaderEnd', {});
        });
    }

    $scope.addAction = function (indicator) {
        indicator.Actions.push({ editing: true });
    }

    $scope.saveAction = function (action) {
        action.editing = false;
        $scope.saveStage($scope.selectedStage);
    }


    $scope.showGuidance = function (indicator) {

        var modalInstance = $uibModal.open({
            templateUrl: app.root + "/Scripts/Templates/GuidanceEditor.html",
            controller: 'App.Controller.GuidanceEditor',
            backdrop: 'static',
            windowClass: 'guidance-dialog',
            size: 'lg',
            resolve: {
                options: function () {
                    return { indicatorId: indicator.Id, readOnly: false }
                }
            }
        });
        modalInstance.result.then(function (changedIndicator) {
            indicator.Guidance = changedIndicator.Guidance;
            indicator.BestCase = changedIndicator.BestCase;
            indicator.WorstCase = changedIndicator.WorstCase;
           
            $scope.saveStage($scope.selectedStage);
        });

    }
}]);
app.ng.controller("App.Controller.Support", ["$scope", "$rootScope", "$translate", function ($scope, $rootScope, $translate) {

    $scope.questions = [
		{
			Question: $translate.instant("SUPPORT.QUESTIONS.QUESTION_1"),
			Answer: $translate.instant("SUPPORT.QUESTIONS.ANSWER_1")
		},
	    {
			Question: $translate.instant("SUPPORT.QUESTIONS.QUESTION_2"),
			Answer: $translate.instant("SUPPORT.QUESTIONS.ANSWER_2")
		},
	    {
			Question: $translate.instant("SUPPORT.QUESTIONS.QUESTION_3"),
			Answer: $translate.instant("SUPPORT.QUESTIONS.ANSWER_3")
		},
	    {
			Question: $translate.instant("SUPPORT.QUESTIONS.QUESTION_4"),
			Answer: $translate.instant("SUPPORT.QUESTIONS.ANSWER_4")
		},
	    {
			Question: $translate.instant("SUPPORT.QUESTIONS.QUESTION_5"),
			Answer: $translate.instant("SUPPORT.QUESTIONS.ANSWER_5")
		},
	    {
			Question: $translate.instant("SUPPORT.QUESTIONS.QUESTION_6"),
			Answer: $translate.instant("SUPPORT.QUESTIONS.ANSWER_6")
	    }
    ];

    $scope.toggle = function (question) {
        if (!question.expanded) {
            question.expanded = true;
        }
        else {
            question.expanded = false;
        }
    }

}]);
