realoApp.controller('mainCtrl', ['$scope', 'httpPostFactory', function($scope, httpPostFactory) {
httpPostFactory('main.php', new FormData(), function(callback) {
$scope.voteValues = callback;
$scope.answered = 0;
$scope.answer = [];
$scope.unansweredQuestions = [];
$scope.results = [];
angular.forEach($scope.voteValues, function(v, k) {
$scope.unansweredQuestions.push(k);
var parties = {};
for(var party in v.yes) {
if(v.yes.hasOwnProperty(party)) {
parties[party] = "";
}
}
$scope.results.push(parties);
});
});
$scope.updateAnswer = function(index) {
var name = $scope.unansweredQuestions[index];
var vote = $scope.answer[index];
var currValues = $scope.voteValues[name][vote];
for(var value in currValues) {
if(currValues.hasOwnProperty(value)) {
$scope.results[index][value] = currValues[value];
}
}
updateResults();
}
var updateResults = function() {
$scope.answered = 0;
var sum = {};
angular.forEach($scope.results, function(v, k) {
var empty = false;
for(var value in v) {
if(v.hasOwnProperty(value)) {
if(v[value] === "") {
empty = true;
break;
}
if(typeof sum[value] === 'undefined') sum[value] = 0;
sum[value] += v[value];
}
}
if(!empty) $scope.answered++;
});
if($scope.answered != 0) {
$scope.result = {};
angular.forEach(sum, function(v, k) {
$scope.result[k] = Math.round((v/$scope.answered)*100) + '%';
})
}
}
}]);