app.controller('ctxListController', function($scope, $http) {			
	$scope.contexts = [];
	$scope.tmpCtx = {};
	$scope.mode = '';		
				
	call_http_get($http, './ajax/contexts/?' + $.now(), function(res) {			
		$scope.contexts = res.data;			
	});			
	
	$scope.prepareNewCtx = function() {
		$scope.mode = 'new';
		$scope.tmpCtx = {
			'id'         : '',
			'label'      : '',
			'type'       : '',
			'parameters' : []
		};
	}

	$scope.prepareEditCtx = function(ctx) {
		$scope.mode = 'edit';
		$scope.tmpCtx = angular.copy(ctx);
	}
					
	$scope.saveContext = function(ctx) {
		if ($scope.mode == 'new') {
			var found = false;
			
			angular.forEach($scope.contexts, function(v) {
				if (ctx.id == ctx.id) { found = true; };
			});
			
			if (found) {
				alert("Insertion failed: context already exists !");
				return;
			}
		}
									
		json_http_post($http,'./ajax/contexts/?' + $.now(), ctx, function(res) {			
			$scope.contexts = res.data;
			alert("Context saved");
		});			
	};			
	 					
	$scope.deleteContext = function(id) {			
		if (confirm("Are you sure ?")) {			
			call_http_delete($http, './ajax/contexts/' + encodeURIComponent(id) + '?' + $.now(), function(res) {			
				$scope.contexts = res.data;
				alert("Context deleted");
			});			
		}			
	};			
	
});

// ----------------------------------------------------

app.controller('ctxViewerController', function($scope, $http, $routeParams) {			
	$scope.ctxId = $routeParams.id;
	$scope.ctxInfo = {};
	$scope.categories = [];				
	$scope.parameters = [];
			
	var url = './ajax/contexts/' + encodeURIComponent($scope.ctxId);

	call_http_get($http, url + '?' + $.now(), function(res) {			
		$scope.ctxInfo = res.data;

		call_http_get($http, url + '/categories?' + $.now(), function(res) {			
			$scope.categories = res.data;			
		});			
	});			
	
	$scope.loadContextParameters = function() {
		$scope.parameters = [];
		call_http_get($http, './ajax/contexts/' + encodeURIComponent($scope.ctxId) + '?' + $.now(), function(res) {			
			$scope.parameters = res.data.parameters;			
		});
	}
	
	$scope.populateNode = function(level, node) {
		$scope.url = './ajax/contexts/' 
			+  encodeURIComponent(level) 
			+ '/' 
			+ encodeURIComponent(node.id) 
			+ '/concepts';
	
		node.populated = true;
		
		call_http_get($http, $scope.url + '?' + $.now(), function(res) {			
			node.concepts = res.data;			
		});
	}

	$scope.initShowParameters = function(params) {
		$scope.parameters = params;
	}
 				
});
