  var myapp = angular.module("myApp", []);
  myapp.controller("visitCtrl", ["$scope", "$http", "$log", "$location", function($scope, $http, $log, $location) {

  $scope.STUDENTS = $http.get('data-student.json')
       .then(function(res){
          return res.data; //$scope.STUDENTS = res.data;                
        });
  $scope.SCHOOLS = $http.get('data-school.json')
       .then(function(res){
          return res.data; //$scope.SCHOOLS = res.data;                
        });

  $scope.STAFF = $http.get('data-teacher.json')
       .then(function(res){
          return res.data; //$scope.SCHOOLS = res.data;                
        });

  $scope.staffroles = [
    { id: 1, name: 'Classroom Teacher' },
    { id: 1, name: 'Specialist' },
    { id: 1, name: 'Counselor' },
    { id: 1, name: 'Administrator' },
    { id: 1, name: 'Special Education Staff' },
    { id: 1, name: 'Interpreter' }
  ];

  var params = $location.search();

  $scope.CAREGIVERS = [
    { id: 1, name: 'CG A', students: [ 1 ] },
    { id: 2, name: 'CG B', students: [ 1 ] },
    { id: 3, name: 'CG C', students: [ 2 ] },
    { id: 4, name: 'CG D', students: [ 2 ] },
    { id: 5, name: 'CG E', students: [ 3 ] }
  ];

  function make_data() {
    var data = []
    $scope.SCHOOLS.then(function(schools) {
      angular.forEach(schools, function(school) {
        school.students = [];
        school.staff = [];
        $scope.STAFF.then(function(teachers) {
          angular.forEach(teachers, function(staff) {
            if (staff.school == school.id) {
              school.staff.push(staff);
            }
          });
        });
        $scope.STUDENTS.then(function(students) {
          angular.forEach(students, function(student) {
            if (student.school == school.id) {
              school.students.push(student);
              student.caregivers = [{ id: 0, name: "New" }];
              angular.forEach($scope.CAREGIVERS, function(cg) {
                angular.forEach(cg.students, function(cgst) {
                  if (cgst == student.id) {
                    student.caregivers.push(cg);
                  }
                });
              });
            }
          });
        });
        data.push(school);
    });
    });
    return data;
  }
  $scope.resetForm = function() {
    $scope.visit = { 
      school: null, 
      student: null, 
      caregiver: 0 
    };
    $scope.data = make_data();
    if (angular.isDefined(params.id)) {
      $scope.STAFF.then(function(teachers) {
         $scope.staff1 = teachers[parseInt(params.id)];
         $scope.SCHOOLS.then(function(schools) {
           angular.forEach(schools, function(s) {
             if (s.name == $scope.staff1.school) {
               $scope.visit.school = s;
             }
           });
         });
      });
    }
  };
  $scope.resetForm();

  }]);
