app.ng.controller("App.Controller.Assessment.Analysis", ["$scope", "$rootScope", "$http", "$state", "routeInfo", "entityController", "$timeout", function ($scope, $rootScope, $http, $state, routeInfo, entityController, $timeout) {

	angular.extend($scope, entityController);

	$scope.loadRecommendations = function () {
	    var url = app.root + ($scope.assessment.Archived ? '/Api/Assessment/ArchivedRecommendationOverview' : '/Api/Assessment/RecommendationOverview');
		$http.get(url, { params: { assessmentId: routeInfo.entityId } }).success(function (result) {
			$scope.stageRecommendationsOverview = result;
			$rootScope.$broadcast('loaderEnd', {});
		});
	}

	$scope.loadOverview = function () {
		$rootScope.$broadcast('loaderStart', {});
		var url = app.root + ($scope.assessment.Archived ? '/Api/Assessment/ArchivedOverview' : '/Api/Assessment/Overview');
		$http.get(url, { params: { assessmentId: routeInfo.entityId, includeStagesOverview: true, includeIndicatorsOverview: true } }).success(function (result) {
			$scope.assessmentOverview = result;
			$scope.stages = result.Stages;
			$scope.stagesNames = $scope.stages.map(function (e) { return e.Name; });
			$scope.loadRecommendations();		
        });
    }


	$scope.init = function () {
	    if (!$scope.assessment) {
	        $timeout($scope.init, 200);
	        return;
	    }
	    $scope.loadOverview();
	}
	$timeout($scope.init, 0);
	
	$scope.legendPosition = "right";
	$scope.Difference = function (status, effectiveness) {
		var diff = status - effectiveness;
		return isNaN(diff) ? null : Math.round(diff * 100) / 100;
	}
	$scope.MinimizeToFive = function(num) {
		return Math.round((num/100*5) * 100) / 100
	}
}]);
app.ng.controller("App.Controller.Assessment.DataMapping", ["$scope", "$rootScope", "$http", "$state", "routeInfo", "entityController", "$timeout", "growl", function ($scope, $rootScope, $http, $state, routeInfo, entityController, $timeout, growl) {

    $scope.enums = window.enums;
    angular.extend($scope, entityController);
    $scope.thisYear = moment().get('year');

    $scope.loadDataMappings = function () {
        $rootScope.$broadcast('loaderStart', {});
        var url = app.root + '/Api/DataMapping/ForAssessment?assessmentId=' + routeInfo.entityId;
        $http.get(url, {}).success(function (result) {
            $scope.dataMapping = result;
            $scope.createAnswers();
            $scope.calculateTotals();
            $scope.generateChartData();
            $rootScope.$broadcast('loaderEnd', {});
        });
    }
    $scope.loadDataMappings();

    $scope.createAnswers = function () {
        _.each($scope.dataMapping.DataCategories, function (category) {
            _.each(category.DataItems, function (item) {
                if (!item.DataAnswers.length) {
                    item.DataAnswers.push({ DataItemId: item.Id, AssessmentId: routeInfo.entityId });
                }
            })
        })
    }

    $scope.saveMapping = function () {
        $rootScope.$broadcast('loaderStart', {});
        var url = app.root + '/Api/DataMapping/Update';
        $http.post(url, $scope.dataMapping).success(function (result) {
            $rootScope.$broadcast('loaderEnd', {});
            growl.addSuccessMessage('Data mapping saved successfully.')
        });
    }

    $scope.getScore = function (enumName, enumValue) {
        var enumObject = enums[enumName];
        var value = _.where(enumObject, { Value: enumValue })[0];
        if (value) {
            return value.Score;
        }
        return null;
    }

    $scope.getAgeScore = function (answer) {
        
        var age = $scope.thisYear - answer.YearLastUpdated;
        if (age < 3)
            return $scope.getScore('DataAge', 1);
        else if (age < 7)
            return $scope.getScore('DataAge', 2);
        else
            return $scope.getScore('DataAge', 3);
    }

    $scope.updateDataScore = function (answer) {

        if (!answer.Available)
            answer.DataScore = 0
        else {

            answer.DataScore =
                $scope.getScore('GranularityLevel', answer.Granularity)
                + $scope.getScore('ConfidenceLevel', answer.Confidence)
                + $scope.getScore('SegregationLevel', answer.Segregation)
                + $scope.getAgeScore(answer);

            answer.AgeScore = $scope.getAgeScore(answer);
            var ageEnumValue = _.where(enums.DataAge, { Score: answer.AgeScore })[0];
            answer.AgeString = ageEnumValue.Name;
        }

        $scope.calculateTotals();
        $scope.generateChartData();
    }

    $scope.calculateTotals = function () {

        _.each($scope.dataMapping.DataCategories, function (category) {
            var categoryScore = 0;
            var max = 0;
            _.each(category.DataItems, function (item) {
                if (category.HasApplicability && !item.DataAnswers[0].Applicable) {
                    // Add nothing to score or max if not applicable
                }
                else {
                    if (item.DataAnswers.length && item.DataAnswers[0].DataScore && item.DataAnswers[0].Available) {
                        categoryScore += item.DataAnswers[0].DataScore;
                    }

                    max += category.MaximumScore;
                }
            });
            category.TotalPoints = categoryScore;
            category.TotalScore = categoryScore * 5 / max;
        })
    }

    $scope.generateChartData = function () {
        $scope.radarData = null;
        var data = { Labels: [], Series: [], Values: [] };

        data.Series.push("Sector scores");
        var valArray = [];
        _.each($scope.dataMapping.DataCategories, function (category) {
            data.Labels.push(category.Name);
            valArray.push(category.TotalScore.toFixed(2));
        });
        data.Values.push(valArray)
        $scope.radarData = data;
    }
}]);
app.ng.controller("App.Controller.Assessment.Details",
	["$scope", "$rootScope", "$http", "$state", "routeInfo", "entityController", "$mdDialog", "growl",
function ($scope, $rootScope, $http, $state, routeInfo, entityController, $mdDialog, growl) {
    if (!$rootScope.loggedIn) {
        $state.go("403");
    }
    angular.extend($scope, entityController);
	
	$scope.entity = entityController.load().then(function (entity) {
		$scope.entity = entity;
		$scope.preAssessment = $scope.entity.Id == null;
		$scope.$parent.preAssessment = $scope.preAssessment;
	});
    $scope.addAccess = function () {
        if (!$scope.entity.AssessmentAccesses) {
            $scope.entity.AssessmentAccesses = [];
        }

        $scope.entity.AssessmentAccesses.push({ editing: true, IsDeleted:false });
    }

    $scope.loadLookups = function () {
	    var url = '/Api/User/All';
	    $http.get(url, {}).success(function(result) {
		    $scope.allUsers = result;
	    });
    }
    $scope.loadLookups();

    $scope.getUsers= function (val) {
        if (val) {
            val = val.toLowerCase();
        }
	    return _.filter($scope.allUsers,
		    function(user) {
			    return user && (user.Name.toLowerCase().indexOf(val) > -1 || user.Email.toLowerCase().indexOf(val) > -1);
		    });
    };

	$scope.accessTypes = $scope.enums.AccessType;

    $scope.deleteAccess = function (access) {
        access.IsDeleted = true;
    }

	$scope.saveAssessment = function (formValid) {
		if (formValid) {
			if ($scope.entity.Sectors != null
				&& $scope.entity.Sectors.filter(a => !a.IsDeleted && a.Name != null && a.Name != "").length > 0) {
				$scope.save($scope.entity).then(function(result) {
					$scope.entity = result;
					$rootScope.$broadcast('assessmentChanged');
				});
			} else {
				growl.addErrorMessage("Please add at least one sector/ministry");
			}
		}
    }

    $scope.delete = function () {
        if (confirm("Are you sure you want to delete this assessment?")) {
	        var url = '/Api/Assessment/Delete';
	        $http.post(url, $scope.entity).success(function(result) {
		        $state.go('Assessments');
	        });
        }
    }

    $scope.archive = function () {
        if (confirm("Are you sure you want to archive this assessment? No more changes will be permitted after this step.")) {
            $rootScope.$broadcast('loaderStart', {});
            var url = '/Api/Assessment/Archive';
            $http.post(url, $scope.entity).success(function (result) {
                $state.reload();
                $rootScope.$broadcast('loaderEnd', {});
            });
        }
    }

    $scope.unarchive = function () {
        if (confirm("Are you sure you want to unarchive this assessment? Changes will be permitted and any new questions will be added to this assessment.")) {
            $rootScope.$broadcast('loaderStart', {});
            var url = '/Api/Assessment/Unarchive';
            $http.post(url, $scope.entity).success(function (result) {
                $state.reload();
                $rootScope.$broadcast('loaderEnd', {});
            });
        }
    }

    $scope.addSector = function () {
        if (!$scope.entity.Sectors) {
            $scope.entity.Sectors = [];
        }

	    $scope.entity.Sectors.push({ AssessmentId: $scope.entity.Id, IsDeleted: false });
    }

    $scope.clone = function () {
        if (confirm("Are you sure you want to clone this assessment?")) {
            $rootScope.$broadcast('loaderStart', {});
            var url = '/Api/Assessment/Clone';
	        $http.post(url, $scope.entity).success(function(result) {
		        $rootScope.$broadcast('loaderEnd', {});
		        $state.go('Assessment.Details', { entityId: result.Id });
	        });
        }
	}

	$scope.skipPreAssessement = function() {
	    $scope.preAssessment = false;
	    $scope.$parent.preAssessment = $scope.preAssessment;
	}

	$scope.showSectorsHelp = function (ev) {
		$mdDialog.show({
				controller: DialogController,
				templateUrl: 'Scripts/Templates/Assessment/SectorsAndMinistriesInfo.html',
				parent: angular.element(document.body),
				targetEvent: ev,
				clickOutsideToClose: true,
				fullscreen: $scope.customFullscreen
			});
	}

	$scope.showCollaboratorsHelp = function (ev) {
				$mdDialog.show({
						controller: DialogController,
						templateUrl: 'Scripts/Templates/Assessment/CollaboratorsInfo.html',
						parent: angular.element(document.body),
						targetEvent: ev,
						clickOutsideToClose: true,
						fullscreen: $scope.customFullscreen 
					});
			}

			function DialogController($scope, $mdDialog) {
				$scope.hide = function () {
					$mdDialog.hide();
				};

				$scope.cancel = function () {
					$mdDialog.cancel();
				};

				$scope.answer = function (answer) {
					$mdDialog.hide(answer);
				};
			}
}]);
app.ng.controller("App.Controller.Assessment.Home", ["$scope", "$rootScope", "$http", "$state", "routeInfo", "entityController", "$timeout", function ($scope, $rootScope, $http, $state, routeInfo, entityController, $timeout) {

    if (!$rootScope.loggedIn) {
        $state.go("403");
    }

    $scope.loadOverview = function () {

        if (!$scope.assessment) {
            $timeout($scope.loadOverview, 200);
            return;
        }

        $rootScope.$broadcast('loaderStart', {});
        var url = app.root + ($scope.assessment.Archived ? '/Api/Assessment/ArchivedOverview' : '/Api/Assessment/Overview');
        $http.get(url, { params: { assessmentId: routeInfo.entityId, includeStagesOverview: true, includeIndicatorsOverview: true } }).success(function (result) {
            $scope.assessmentOverview = result;
            $rootScope.$broadcast('loaderEnd', {});
        }).error(function(err){
            $rootScope.$broadcast('loaderEnd', {});
        });
    }

    $timeout($scope.loadOverview, 0);

}]);
app.ng.controller("App.Controller.Assessment.Indicator", ["$scope", "$rootScope", "$http", "$state", "routeInfo", "entityController", "$timeout", "growl", "$uibModal", "$sce", "$location", function ($scope, $rootScope, $http, $state, routeInfo, entityController, $timeout, growl, $uibModal, $sce, $location) {

    $scope.routeInfo = routeInfo;
    $scope.sce = $sce;
    $scope.recommendationTypes = enums.RecommendationType;
    $scope.questionsLoaded = false;

    angular.extend($scope, entityController);

	$scope.$on('$stateChangeStart',
		function(event) {
			if ($scope.dirty) {
				if (!confirm("you have unsaved changes, are you sure you want to leave this page?")) {
					event.preventDefault();
					return false;
				}
			}
		});

    if (routeInfo.subIndicatorId) {
        $scope.indicatorId = routeInfo.subIndicatorId;
    }
    else {
        $scope.indicatorId = routeInfo.indicatorId;
    }

    $scope.init = function () {
        if (!$scope.assessment) {
            $timeout($scope.init, 200);
            return;
        }

        if ($scope.assessment.Archived) {
            $scope.loadArchivedIndicator();
            $scope.loadArchivedAnswers();
        }
        else {
            entityController.load($scope.indicatorId, 'Indicator').then(function (indicator) {
                $scope.indicator = indicator;
                $scope.postLoad(indicator, false);
                $scope.loadAnswers();
            });
        }
    }

    $timeout($scope.init, 0)


    $scope.loadArchivedIndicator = function () {
        var url = app.root + '/Api/Assessment/IndicatorForArchivedAssessment';
        $http.get(url, { params: { assessmentId: $scope.assessment.Id, indicatorId: $scope.indicatorId } }).success(function (result) {
            $scope.postLoad(result, true);
        });
    }

    $scope.postLoad = function (indicator, isArchived) {
        $scope.indicator = indicator;
        $timeout($scope.initButtons, 0);
        if (isArchived) {
            $scope.loadArchivedQuestions();
            $scope.loadArchivedOverview();
        }
        else {
            $scope.loadQuestions();
            $scope.loadOverview();
        }
        if (indicator.RepeatedPerSector) {
            var sector = routeInfo.sectorId != null ? routeInfo.sectorId : $scope.assessment.Sectors[0].Id;
            if (sector != null) {
                $scope.sector = _.where($scope.assessment.Sectors, { Id: parseInt(sector, 10) })[0];
                $location.search('sectorId', sector);
            }
        }
    }

    $scope.initButtons = function () {
        var index = _.findIndex($scope.stage.Indicators, { Id: $scope.indicator.Id });
        $scope.canGoNext = index < $scope.stage.Indicators.length - 1;
        $scope.canGoPrevious = index > 0;
    }

    $scope.loadAnswers = function () {
        var url = app.root + '/Api/Indicator/Answers';
        $http.get(url, { params: { indicatorId: $scope.indicatorId, assessmentId: routeInfo.entityId, sectorId: routeInfo.sectorId } }).success(function (result) {
            $scope.indicators = result;

            if (result.length) {
                $scope.answer = result[0];
                //Need to manually set in case of legacy data
                $scope.answer.SectorId = routeInfo.sectorId
            }
            else {
                $scope.answer = { AssessmentId: routeInfo.entityId, IndicatorId: $scope.indicatorId, SectorId: routeInfo.sectorId };
                $scope.saveAnswer(true, false);
            }

            $rootScope.indicatorContent = $scope.answer.Content;
            $rootScope.scoreDirty = $scope.answer.Score != null;

            $scope.$watch('answer.Score', function (newValue, oldValue) {
                if (newValue != oldValue) {
                    $scope.saveAnswer(false, true);
                    if (newValue) {
                        $rootScope.scoreDirty = true;
                    }
                }
            });

            $scope.$watch('answer.Content', function (newValue, oldValue) {
                if (newValue != oldValue) {
	                $scope.dirty = true;
                }
            });

            $scope.synchActions();

            $rootScope.$broadcast('loaderEnd', {});

        });
    }

    $scope.loadArchivedAnswers = function () {
        var url = app.root + '/Api/Indicator/AnswersForArchivedAssessment';
        $http.get(url, { params: { indicatorId: $scope.indicatorId, assessmentId: routeInfo.entityId, sectorId: routeInfo.sectorId } }).success(function (result) {
            $scope.indicators = result;

            if (result.length) {
                $scope.answer = result[0];
               
                //Need to manually set in case of legacy data
                $scope.answer.SectorId = routeInfo.sectorId
            }
            $rootScope.$broadcast('loaderEnd', {});
        });
    }


    $scope.saveAnswer = function (hideSuccess, reloadChart) {
        var url = app.root + '/Api/Indicator/UpdateAnswer';

        var checkedActions = [];
        _.each($scope.indicator.Actions, function (action) {
            if (action.Checked) {
                checkedActions.push({ ActionId: action.Id, IndicatorAssessmentId: $scope.answer.Id });
            }
        });

        $scope.answer.IndicatorAssessmentActions = checkedActions;

        $http.post(url, $scope.answer).success(function (result) {
            $scope.answer = result;
            $scope.answer.DateModified = result.DateModified;
	        $scope.dirty = false;
            if (!hideSuccess) {
                growl.addSuccessMessage('Answers saved successfully');
            }
            $rootScope.$broadcast('loaderEnd', {});
            if (reloadChart) {
                $rootScope.$broadcast('indicatorUpdated', {});
            }
        });

    }

    $scope.synchActions = function () {
        _.each($scope.answer.IndicatorAssessmentActions, function (action) {
            var matchingAction = _.where($scope.indicator.Actions, { Id: action.ActionId });
            if (matchingAction.length) {
                matchingAction[0].Checked = true;
            }
        })
    }

    $scope.showGuidance = function () {
        var modalInstance = $uibModal.open({
            templateUrl: "/Scripts/Templates/Controls/GuidanceEditor.html",
            controller: 'App.Controller.GuidanceEditor',
            windowClass: 'guidance-dialog',
            size: 'lg',
            resolve: {
                options: function () {
                    return { indicatorId: $scope.indicator.Id, readOnly: true }
                }
            }
        });
        modalInstance.result.then(function (item) {

        });
    }

    $scope.showDataSources = function () {
        var modalInstance = $uibModal.open({
            templateUrl: app.root + "/Scripts/Templates/Indicator/DataSources.html",
            windowClass: 'guidance-dialog',
            size: 'lg',
            scope: $scope,
            resolve: {}
        });
    }

    $scope.showSupportingInfo = function () {
        var modalInstance = $uibModal.open({
            templateUrl: app.root + "/Scripts/Templates/Indicator/SupportingInfo.html",
            windowClass: 'guidance-dialog',
            size: 'lg',
            scope: $scope,
            resolve: {}
        });
    }

    $scope.loadPrevious = function () {
		if ($scope.dirty) {
            $scope.saveAnswer(true, false);
        }
		var index = _.findIndex($scope.stage.Indicators, { Id: $scope.indicator.Id });
        if (index > 0) {
            var toGo = $scope.stage.Indicators[index - 1];
            $state.go('Assessment.Stages.Detail.Indicator', { stageId: $scope.indicator.StageId, indicatorId: toGo.Id });
        }
    }

    $scope.loadNext = function () {
		if ($scope.dirty) {
            $scope.saveAnswer(true, false);
        }
		var index = _.findIndex($scope.stage.Indicators, { Id: $scope.indicator.Id });
        if (index < $scope.stage.Indicators.length - 1) {
            var toGo = $scope.stage.Indicators[index + 1];
            $state.go('Assessment.Stages.Detail.Indicator', { stageId: $scope.indicator.StageId, indicatorId: toGo.Id });
        }
    }


    $scope.clearScore = function () {
        $scope.answer.Score = null;
        $rootScope.scoreDirty = null;
    }

    $scope.answerChanged = function (question) {
        var url = '/Api/Indicator/UpdateQuestionAnswer';
        var model = { Answer: question.Answer, AssessmentId: routeInfo.entityId, IndicatorQuestionId: question.Id, SectorId: routeInfo.sectorId, IndicatorId: $scope.indicatorId }
        $rootScope.$broadcast('loaderStart', {});
        $http.post(url, model).success(function () {
            $rootScope.$broadcast('loaderEnd', {});
            $rootScope.$broadcast('indicatorUpdated', {});
        });
    }

    $scope.mainAnswerChanged = function () {
        var url = '/Api/Indicator/UpdateMainAnswer';
        var model = { Id: $scope.answer.Id, IndicatorApplies: $scope.answer.IndicatorApplies, SectorId: routeInfo.sectorId }
        $http.post(url, model).success(function () {
            $rootScope.$broadcast('loaderEnd', {});
            $rootScope.$broadcast('indicatorUpdated', {});
        });

    }

    $scope.loadQuestions = function () {
        var url = '/Api/Indicator/GetQuestionsAndAnswers';
        $http.get(url, { params: { assessmentId: routeInfo.entityId, indicatorId: $scope.indicatorId, sectorId: routeInfo.sectorId } }).success(function (results) {
            $scope.questions = results;
            $scope.questionsLoaded = true;
        });
    }

    $scope.loadArchivedQuestions = function () {
        var url = '/Api/Assessment/QuestionsForArchivedAssessment';
        $http.get(url, { params: { assessmentId: routeInfo.entityId, indicatorId: $scope.indicatorId, sectorId: routeInfo.sectorId } }).success(function (results) {
            $scope.questions = results;
            $scope.questionsLoaded = true;
        });
    }

    $scope.loadOverview = function () {
        var url = app.root + '/Api/Indicator/Overview';
        var indicatorId = $scope.indicator.ParentIndicatorId ? $scope.indicator.ParentIndicatorId : $scope.indicator.Id;
        $http.get(url, { params: { indicatorId: indicatorId, assessmentId: routeInfo.entityId, sectorId: routeInfo.sectorId } }).success(function (result) {
			$scope.indicatorOverview = result;
			$scope.indicatorName = result.Name;
            $rootScope.$broadcast('loaderEnd', {});
        });
    }

    $scope.loadArchivedOverview = function () {
        var url = app.root + '/Api/Indicator/ArchivedOverview';
        var indicatorId = $scope.indicator.ParentIndicatorId ? $scope.indicator.ParentIndicatorId : $scope.indicator.Id;
        $http.get(url, { params: { indicatorId: indicatorId, assessmentId: routeInfo.entityId, sectorId: routeInfo.sectorId } }).success(function (result) {
            $scope.indicatorOverview = result;
            $scope.indicatorName = result.Name;
            $rootScope.$broadcast('loaderEnd', {});
        });
    }

    if ($rootScope.indicatorUpdatedListener) {
        $scope.indicatorUpdatedListener();
    }

    $rootScope.indicatorUpdatedListener = $rootScope.$on('indicatorUpdated', function () {
        $scope.indicatorOverview = null;
        $scope.loadOverview();
    });

    $scope.addRecommendation = function () {
        if (!$scope.answer.Recommendations) {
            $scope.answer.Recommendations = [];
        }
        $scope.answer.Recommendations.push({ IsDeleted: false, IndicatorAssessmentId: $scope.answer.Id, editing: true, SectorId: routeInfo.sectorId });
    }


    $scope.saveRecommendation = function (recommendation) {
        if (!recommendation.Text || !recommendation.Type) {
            growl.addErrorMessage("Please enter recommendation text and type")
        }
        else {
            var url = '/Api/Indicator/UpdateRecommendation';
            $http.post(url, recommendation).success(function (result) {
                recommendation.Id = result.Id;
                recommendation.TypeString = result.TypeString;
                recommendation.editing = false;
            });
        }
    }

    $scope.deleteRecommendation = function (recommendation) {
        if (confirm("Really delete this recommendation?")) {
            recommendation.IsDeleted = true;
            $scope.saveRecommendation(recommendation)
        }
    }

    $scope.dependentPasses = function (question) {
        var dependsOnQuestion = _.where($scope.questions, { Id: question.DependsOnIndicatorQuestionId });
        return dependsOnQuestion.length && dependsOnQuestion[0].Answer
    }

    $scope.next = function () {
        var url = '/Api/Indicator/Next';
        $http.get(url, { params: { indicatorId: $scope.indicator.Id, sectorId: routeInfo.sectorId, assessmentId: routeInfo.entityId } }).success(function (result) {
            if (result) {
                $state.go("Assessment.Stages.Detail.Indicator", { indicatorId: result.Id, stageId: result.StageId, sectorId: result.SectorId });
            }
        });
    }

    $scope.previous = function () {
        var url = '/Api/Indicator/Previous';
        $http.get(url, { params: { indicatorId: $scope.indicator.Id, sectorId: routeInfo.sectorId, assessmentId: routeInfo.entityId } }).success(function (result) {
            if (result) {
                $state.go("Assessment.Stages.Detail.Indicator", { indicatorId: result.Id, stageId: result.StageId, sectorId: result.SectorId });
            }
        });
    }

}]);
app.ng.controller("App.Controller.Assessment.Projects", ["$scope", "$rootScope", "$http", "$state", "routeInfo", "entityController", "$timeout", function ($scope, $rootScope, $http, $state, routeInfo, entityController, $timeout) {

    angular.extend($scope, entityController);

    $scope.loadProjects = function () {
        $rootScope.$broadcast('loaderStart', {});
        var url = app.root + '/Api/Project/ForAssessment?assessmentId=' + routeInfo.entityId;
        $http.get(url, {}).success(function (result) {
            $scope.projects = result;
            $scope.loadStages();
            $rootScope.$broadcast('loaderEnd', {});
        });
    }
    $scope.loadProjects();

    $scope.loadStages = function () {
        var url = app.root + '/Api/Stage/All';
        $http.get(url, {}).success(function (result) {
            $scope.stages = result;
            $scope.updateMatrix();
        });
    }
  
    $scope.addProject = function () {
        $scope.projects.push({AssessmentId: routeInfo.entityId, editing:true, IsDeleted: false});
    }

    $scope.saveProject = function (project) {
        $rootScope.$broadcast('loaderStart', {});
        $scope.synchProject(project);
        var url = app.root + '/Api/Project/Update';
        $http.post(url, project).success(function (result) {
            $rootScope.$broadcast('loaderEnd', {});
            $scope.loadProjects();
        });
    }

    $scope.deleteProject = function (project) {
        if (confirm('Are you sure you want to delete this project?')) {
            var url = app.root + '/Api/Project/Delete';
            $rootScope.$broadcast('loaderStart', {});
            $http.post(url, project).success(function (result) {
                $rootScope.$broadcast('loaderEnd', {});
                project.editing = false;
                project.IsDeleted = true;
                $scope.loadProjects();
            });
        }
    }

    $scope.updateMatrix = function () {
        $scope.checkMatrix = {};

        _.each($scope.stages, function (stage) {
            _.each(stage.Indicators, function (indicator) {
                $scope.checkMatrix[indicator.Id] = {};
                _.each($scope.projects, function (project) {
                    $scope.checkMatrix[indicator.Id][project.Id] = {checked: $scope.isChecked(indicator, project) };
                });
            });
        });

    }

    $scope.synchProject = function (project) {
        project.ProjectIndicators = [];
        for (var indicatorId in $scope.checkMatrix) {
            for (var projectId in $scope.checkMatrix[indicatorId]) {
                var tuple = $scope.checkMatrix[indicatorId][projectId];
                if (tuple.checked) {
                    project.ProjectIndicators.push({ IndicatorId: indicatorId, ProjectId: projectId })
                }
            }
        }
    }

    $scope.isChecked = function (indicator, project) {
        var result = _.where(project.ProjectIndicators, { IndicatorId: indicator.Id }).length;
        return result > 0;
    }

}]);
app.ng.controller("App.Controller.Assessment.Root", ["$scope", "$rootScope", "$http",
	"$state", "routeInfo", "entityController", "$location", "$window","$q"
	, function ($scope, $rootScope, $http, $state, routeInfo, entityController, $location, $window, $q) {

    if (!$rootScope.loggedIn) {
        $state.go("403");
    }

    $scope.isNew = !parseInt(routeInfo.entityId);
    angular.extend($scope, entityController);
    $scope.preAssessment = false;

    $scope.loadAssessment = function () {
        $scope.entity = entityController.load(routeInfo.entityId, 'Assessment')
            .then(
			function (entity) {
			    $scope.entity = entity; $scope.assessment = entity;
			    $rootScope.$broadcast('rootAssessmentLoaded', {});
			    $scope.loadStages();
            },
            function (err) { $scope.accessDenied = true; }
            );
    }
    $scope.loadAssessment();

	$scope.loadStages = function () {
	    var url = app.root + ($scope.assessment.Archived ? '/Api/Stage/ForArchivedAssessment' : '/Api/Stage/All');
	    $http.get(url, { params: {assessmentId: $scope.assessment.Id}}).success(function (result) {
		    $scope.stages = result;
			if (result != null && result.length > 1) {
				$scope.stage = result[0];
			}			
		});
	}

	$scope.colorset = ['green', 'red', 'black', 'gray']


	$scope.toExcel = function () {
		$rootScope.$broadcast('loaderStart', {});
		var url = app.root + '/Api/Assessment/Overview';
		$http.get(url, { params: { assessmentId: routeInfo.entityId, includeStagesOverview: true, includeIndicatorsOverview: true } }).success(function (result) {
			$scope.stagesNames = result.Stages.map(function (e) { return e.Name; });
			if ($rootScope.asterPlotChartId != null) {
				$rootScope.asterPlotChartId++;
			} else {
				$rootScope.asterPlotChartId = 0;
			}
			$scope.asterPlotChartId = $rootScope.asterPlotChartId;
			var blobs = []; var promises = [];
			var deferred = $q.defer();
			promises.push(deferred.promise);
			$("#assessmentChartHidden").innerHTML = "";

				drawAsterPlot($("#assessmentChartHidden"), result.AsterPlotData, 'CAT-I', null, $scope, $location, $window, "assessmentChart");
				svgAsDataBlob($("#assessmentChartHidden").find("#assessmentChart")[0],
				{ backgroundColor: "#fff" }, function (blob) {

					blobs.push({ Image: blob, Type: 1, Id: routeInfo.entityId});
					deferred.resolve();
				});	
				
			result.Stages.forEach(function(stage) {
				
				if (stage.Overview.AsterPlotData != null) {
					drawAsterPlot($("#assessmentChartHidden"), stage.Overview.AsterPlotData, stage.Name, null, $scope, $location, $window, "stageChart" + stage.Id);
					var deferred = $q.defer();
					promises.push(deferred.promise);

					svgAsDataBlob($("#assessmentChartHidden").find("#stageChart" + stage.Id)[0],
						{ backgroundColor: "#fff" }, function (blob) {
							blobs.push({ Image: blob, Type: 2, Id: stage.Id, DisplayOrder: stage.Id });
							deferred.resolve();
						});
				}
				
				stage.Indicators.forEach(function (indicator) {
					
					if (indicator.Overview.AsterPlotData != null) {
						drawAsterPlot($("#assessmentChartHidden"),
							indicator.Overview.AsterPlotData,
							indicator.Name,
							null,
							$scope,
							$location,
							$window,
							"indicatorChart" + indicator.Id);
						var def = $q.defer();
						promises.push(def.promise);

						svgAsDataBlob($("#assessmentChartHidden").find("#indicatorChart" + indicator.Id)[0],
							{ backgroundColor: "#fff" },
							function(blob) {
								blobs.push({
									Image: blob,
									Type: 3,
									Id: indicator.Id,
									DisplayOrder: indicator.DisplayOrder
								});
								def.resolve();
							});
					}					
				});
			});
			
			$q.all(promises).then(function () {
				$http.post('/Export/AssessmentToExcel', { id: routeInfo.entityId, images: blobs })
					.success(function (data) {
							$rootScope.$broadcast('loaderEnd', {});
							//window.location.href = '/Export/AssessmentToExcel?id=' + routeInfo.entityId;
							window.location = '/Document/DownloadFromLocalMemory?fileGuid=' + data.FileGuid
								+ '&filename=' + data.FileName;
					}).error(function () {
							$rootScope.$broadcast('loaderEnd', {});
					});
			});
		});

    }

    $rootScope.$on('assessmentChanged', function () {
        $scope.loadAssessment();
    });

}]);
app.ng.controller("App.Controller.Assessment.Stage", ["$scope", "$rootScope", "$http", "$state", "routeInfo", "entityController", "$timeout", "$location", function ($scope, $rootScope, $http, $state, routeInfo, entityController, $timeout, $location) {
    angular.extend($scope, entityController);
    entityController.load(routeInfo.stageId, 'Stage').then(function(entity) {
		$scope.stage = entity;
    });

    $scope.loadIndicators = function () {
        
        var url = app.root;
        if ($scope.assessment.Archived) {
            $scope.loadArchivedIndicators();
            $scope.loadArchivedOverview();
            url = url + '/Api/Indicator/ForArchivedStage';
        }
        else {
            $scope.loadOverview();
            url = url + '/Api/Indicator/ForStage';
        }

        $http.get(url, { params: { stageId: routeInfo.stageId, assessmentId: $scope.assessment.Id } }).success(function (result) {
            $scope.indicators = result;
            $rootScope.$broadcast('loaderEnd', {});
            $scope.setSector($scope.stage);
        });
        
    }

    $scope.setSector = function (result) {
        if (result.RepeatedPerSector) {
            var sectorId = null;
            if (routeInfo.sectorId != null)
                sectorId = routeInfo.sectorId;
            else {
                sectorId = $scope.assessment.Sectors[0].Id
                $location.search('sectorId', sectorId);
            }

            if (!$scope.sector) {
                $scope.sector = _.where($scope.assessment.Sectors, { Id: parseInt(sectorId,10) })[0];
            }
        }
    }

    $scope.loadArchivedIndicators = function () {
        var url = app.root + '/Api/Assessment/IndicatorsForArchivedAssessment';
        $http.get(url, { params: { assessmentId: $scope.assessment.Id, stageId: routeInfo.stageId } }).success(function (result) {
            $scope.indicators = result;
            $scope.setSector(result);
        });
    }

    $scope.init = function () {
        if (!$scope.assessment) {
            $timeout($scope.init, 200);
            return;
        }
        $scope.loadIndicators();
    }

    $timeout( $scope.init, 0);


    $scope.loadOverview = function () {
        var url = app.root + '/Api/Assessment/Overview';
        $http.get(url, { params: { assessmentId: routeInfo.entityId } }).success(function (result) {
            $scope.assessmentOverview = result;
            $rootScope.$broadcast('loaderEnd', {});
        });
    }

    $scope.loadArchivedOverview = function () {
        var url = app.root + '/Api/Assessment/ArchivedOverview';
        $http.get(url, { params: { assessmentId: routeInfo.entityId } }).success(function (result) {
            $scope.assessmentOverview = result;
            $rootScope.$broadcast('loaderEnd', {});
        });
    }


    /*
    $rootScope.$on('indicatorUpdated', function () {
        $scope.overview = null;
        $scope.loadOverview();
    });*/

    $scope.isIndicatorActive = function (indicator) {
        
        if ($scope.indicatorInUrl(indicator)) {
            return true;
        }
        var result = false;
        _.each(indicator.SubIndicators, function (subIndicator) {
            if ($scope.indicatorInUrl(subIndicator)) {
                result = true;
                return;
            }
        })
        return result;
       
    }

    $scope.indicatorInUrl = function (indicator) {
        var url = $location.path();
        var string = '/Indicator/' + indicator.Id;
        if (url.indexOf(string) + string.length == url.length) {
            return true;
        }
	}

	$scope.getIndicatorId = function () {
		var url = $location.path();
		var string = '/Indicator/';
		return url.substring(url.indexOf(string) + string.length);
	}

}]);
app.ng.controller("App.Controller.Assessment.StageHome",
	[
		"$scope", "$rootScope", "$http", "$state", "routeInfo", "entityController", "$timeout", "$location",
		function($scope, $rootScope, $http, $state, routeInfo, entityController, $timeout, $location) {
			angular.extend($scope, entityController);
			entityController.load(routeInfo.stageId, "Stage")
				.then(function(entity) {
				    $scope.stage = entity;

				    $scope.init();
				});

			$scope.init = function () {
			    if (!$scope.assessment) {
			        $timeout($scope.init, 200);
			        return;
			    }
			    if ($scope.assessment.Archived) {
			        //      $scope.loadArchivedOverview();
			        $scope.loadArchivedIndicators();
			    }
			    else {
			  //      $scope.loadOverview();
			        $scope.loadIndicators();
			    }
			}

		/*	$scope.loadOverview = function() {
			    var url = app.root + "/Api/Assessment/Overview";
				$http.get(url,
						{ params: { stageId: routeInfo.stageId, assessmentId: routeInfo.entityId, sectorId: routeInfo.sectorId } })
					.success(function(result) {
					    $scope.stageOverview = result;
						$scope.loadIndicators();
					});
			};

			$scope.loadArchivedOverview = function () {
			    var url = app.root + "/Api/Assessment/ArchivedOverview";
			    $http.get(url,
						{ params: { stageId: routeInfo.stageId, assessmentId: routeInfo.entityId, sectorId: routeInfo.sectorId } })
					.success(function (result) {
					    $scope.stageOverview = result;
					    $scope.loadArchivedIndicators();
					});
			};*/


			$scope.loadIndicators = function() {
				var url = app.root + "/Api/Indicator/ForStage";
				$http.get(url, { params: { stageId: routeInfo.stageId, assessmentId: routeInfo.entityId } }).success(function (result) {
				    $scope.indicators = result;
				    $scope.sectorId = $scope.stage.RepeatedPerSector ? routeInfo.sectorId : null;
					$scope.setSector($scope.stage);
					$rootScope.$broadcast("loaderEnd", {});
				});
			};

			$scope.loadArchivedIndicators = function () {
			    var url = app.root + "/Api/Indicator/ForArchivedStage";
			    $http.get(url, { params: { stageId: routeInfo.stageId, assessmentId: routeInfo.entityId } }).success(function (result) {
			        $scope.indicators = result;
			        $scope.sectorId = $scope.stage.RepeatedPerSector ? routeInfo.sectorId : null;
			        $rootScope.$broadcast("loaderEnd", {});
			    });
			};

			$scope.setSector = function (stage) {
			    if (stage.RepeatedPerSector) {
			        var sector = null;
			        if (routeInfo.sectorId != null)
			            $scope.sectorId = routeInfo.sectorId;
			        else {
			            $scope.sectorId = $scope.assessment.Sectors[0].Id;
			            $location.search('sectorId', $scope.sectorId);
			        }
			    }
			}

		}
	]);
app.ng.controller("App.Controller.Assessment.Stages", ["$scope", "$rootScope", "$http", "$state", "routeInfo", "entityController", "$timeout", function ($scope, $rootScope, $http, $state, routeInfo, entityController, $timeout) {

  //  angular.extend($scope, entityController);
  //  $scope.entity = entityController.load().then(function (entity) { $scope.entity = entity; });
    /*
    $scope.loadStages = function () {
        var url = app.root + '/Api/Stage/All';
        $http.get(url, {}).success(function (result) {
            $scope.stages = result;
            $rootScope.$broadcast('loaderEnd', {});
            
        });
    }
    $scope.loadStages();
 

 */
  

}]);
