<commit_before>//'use strict';

window.Nawrs = angular.module('nawrs', ['ui-leaflet', 'elasticsearch', 'ngTable']);

// the application
Nawrs.controller('geoSearch', ['$scope', '$http', '$filter', 'client', 'esFactory', '$location', 'NgTableParams', 'leafletMapEvents', 'leafletData', function ($scope, $http, $filter, client, esFactory, $location, NgTableParams, leafletMapEvents, leafletData) {
  // Map bindings

  $scope.state_ref_layer = L.featureGroup();
  $scope.state_facets = L.featureGroup();
  $scope.state_select = [];

  $scope.watershed_ref_layer = L.featureGroup();
  $scope.watershed_facets = L.featureGroup();
  $scope.watershed_select = [];

  $scope.tribal_boundary_layer = L.featureGroup();
  $scope.tribal_boundary_facets = L.featureGroup();
  $scope.tribal_boundary_select = [];

  var tilesDict = {
    osm: {
      name: "OpenStreetMap",
      url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      type: 'xyz',
      options: {
        attribution: '© OpenStreetMap contributors'
      }
    },
    stamen_ter: {
      name: "Stamen Terrain",
      url: 'http://stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}.{ext}',
      options: {
        attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
        ext: 'png'
      }
    },
    esri_world: {
      name: "ESRI World Imagery",
      url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
      options: {
        attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
      }
    }
  }

  angular.extend($scope, {
    tiles: tilesDict.osm,
    centroid: {
      lat: 39.5,
      lng: -98.35,
      zoom: 4
    },
    events: {
      map: {
        enable: ['click'],
        logic: 'emit'
      }
    },
    layers: {
      //overlays: {}
    }
  })

  $http.get('nawrs/data/us_state_PR_1hundthDD.geojson').success(function(data, status){
    leafletData.getMap().then(function(map){
      var newLayer = L.geoJSON(data, {
        onEachFeature: function(feature, layer){
          $scope.state_select.push(layer.feature);
        }
      });
      var i = 0;
      for (; i < $scope.state_select.length; i++){
        $scope.state_select[i].selected = false;
      }
      $scope.state_ref_layer.addLayer(newLayer);
    })
  })

  $http.get('nawrs/data/wbdhu2_PR_1hundthDD.geojson').success(function(data, status){
    leafletData.getMap().then(function(map){
      var newLayer = L.geoJSON(data, {
        onEachFeature: function(feature, layer){
          $scope.watershed_select.push(layer.feature);
        }
      });
      var i = 0;
      for (; i < $scope.watershed_select.length; i++){
        $scope.watershed_select[i].selected = false;
      }
      $scope.watershed_ref_layer.addLayer(newLayer);
    })
  })

  $http.get('nawrs/data/tl_2011_PR_1hundthDD.geojson').success(function(data, status){
    leafletData.getMap().then(function(map){
      var newLayer = L.geoJSON(data, {
        onEachFeature: function(feature, layer){
          $scope.tribal_boundary_select.push(layer.feature);
        }
      });
      var i = 0;
      for (; i < $scope.tribal_boundary_select.length; i++){
        $scope.tribal_boundary_select[i].selected = false;
      }
      $scope.tribal_boundary_layer.addLayer(newLayer);
    })
  })

  $scope.changeTiles = function(tiles) {
    $scope.tiles = tilesDict[tiles];
  }

  $scope.clearFacets = function(){
    $scope.facets = [];
    $scope.geo_facets = [];
    var vi = 0;
    for (; vi < $scope.state_select.length; vi++){
      $scope.state_select[vi].selected = false;
    }
    var vii = 0;
    for (; vii < $scope.watershed_select.length; vii++){
      $scope.watershed_select[vii].selected = false;
    }
    var viii = 0;
    for (; viii < $scope.tribal_boundary_select.length; viii++){
      $scope.tribal_boundary_select[viii].selected = false;
    }
    leafletData.getMap().then(function(map){
      $scope.watershed_facets.clearLayers();
      $scope.state_facets.clearLayers();
      $scope.tribal_boundary_facets.clearLayers();
    })
    $scope.search();
  }

  // Handle search and facet bindings
  var self = this;
  self.tableParams = new NgTableParams({}, { dataset: $scope.docs});

  $scope.searchTerm = $location.search().q;
  $scope.docs = [];
  $scope.doc_type = [];
  $scope.doc_geometry = [];
  $scope.cur_doc_geometry = [];
  $scope.subject = [];
  $scope.facets = [];
  $scope.geo_facets = [];
  $scope.feature_set = L.featureGroup();

  $scope.search = function(search_type){
    $scope.docs = [];
    $scope.facets = [];
    $scope.geo_facets = [];
    $scope.doc_geometry = [];
    $scope.cur_doc_geometry = [];
    $scope.doc_type = [];
    $scope.subject = [];

    leafletData.getMap().then(function(map){
      $scope.feature_set.clearLayers();
      $scope.watershed_facets.clearLayers();
      $scope.state_facets.clearLayers();
      $scope.tribal_boundary_facets.clearLayers();
    })

    client.search($scope.searchTerm, $scope.facets, $scope.geo_facets).then(function(results){
      var i = 0;
      for (; i < results[1].length; i++){
        $scope.docs.push(results[1][i]);
        $scope.doc_geometry.push(results[1][i].polygon.features[0]);
      }
      var ii = 0;
      $scope.doc_type = results[0].doc_type.buckets;
      for (; ii < $scope.doc_type.length; ii++){
        $scope.doc_type[ii].selected = false;
      }
      $scope.subject = results[0].subject.buckets;
      var iii = 0;
      for (; iii < $scope.subject.length; iii++){
        $scope.subject[iii].selected = false;
      }
      var iv = 0;
      for (; iv < $scope.doc_geometry.length; iv++){
        $scope.doc_geometry[iv].selected = false;
      }
      var vi = 0;
      for (; vi < $scope.state_select.length; vi++){
        $scope.state_select[vi].selected = false;
      }
      var vii = 0;
      for (; vii < $scope.watershed_select.length; vii++){
        $scope.watershed_select[vii].selected = false;
      }
      var viii = 0;
      for (; viii < $scope.tribal_boundary_select.length; viii++){
        $scope.tribal_boundary_select[viii].selected = false;
      }
      leafletData.getMap().then(function(map){
        var v = 0;
        for (; v < $scope.doc_geometry.length; v++) {
          $scope.doc_geometry[v].selected = true;
          var newLayer =  L.geoJSON($scope.doc_geometry[v], {
            style: function(feature){
              return {color: "red"};
            }
          }).bindPopup (function(layer){
            return layer.feature.properties.NAMELSAD;
          });
          $scope.feature_set.addLayer(newLayer);
        }
        $scope.feature_set.addTo(map);
        map.fitBounds($scope.feature_set.getBounds());
      })
    })
  }

  $scope.set_facets = function(){
    // get all checked and redo search - don't store old
    var xx = 0;
    for (;xx < $scope.doc_geometry.length; xx++){
      $scope.cur_doc_geometry.push($scope.doc_geometry[xx]);
    }
    $scope.facets = [];
    $scope.geo_facets = [];
    $scope.doc_geometry = [];
    leafletData.getMap().then(function(map){
      $scope.feature_set.clearLayers();
      $scope.watershed_facets.clearLayers();
      $scope.state_facets.clearLayers();
      $scope.tribal_boundary_facets.clearLayers();
    })
    angular.forEach($scope.doc_type, function(facet){
      if (facet.selected){
        var f = {
          "term": {}
        };
        f.term.type = facet.key;
        $scope.facets.push(f);
      }
    })
    angular.forEach($scope.subject, function(facet){
      if (facet.selected){
        var f = {
          "term": {}
        };
        f.term.subject = facet.key;
        $scope.facets.push(f);
      }
    })
    angular.forEach($scope.cur_doc_geometry, function(facet){
      if (facet.selected){
        if (facet.geometry.coordinates[0].length == 1){
          $scope.geo_facets.push(facet.geometry.coordinates[0][0])
        } else {
          $scope.geo_facets.push(facet.geometry.coordinates[0]);
        }
      }
    })
    angular.forEach($scope.state_select, function(facet){
      if (facet.selected){
        if (facet.geometry.coordinates[0].length == 1){
          $scope.geo_facets.push(facet.geometry.coordinates[0][0])
        } else {
          $scope.geo_facets.push(facet.geometry.coordinates[0]);
        }
        leafletData.getMap().then(function(map){
          var newLayer = L.geoJSON(facet);
          $scope.state_facets.addLayer(newLayer);
          $scope.state_facets.addTo(map);
        })
      }
    })
    angular.forEach($scope.watershed_select, function(facet){
      if (facet.selected){
        if (facet.geometry.coordinates[0].length == 1){
          $scope.geo_facets.push(facet.geometry.coordinates[0][0])
        } else {
          $scope.geo_facets.push(facet.geometry.coordinates[0]);
        }
        leafletData.getMap().then(function(map){
          var newLayer = L.geoJSON(facet);
          $scope.watershed_facets.addLayer(newLayer);
          $scope.watershed_facets.addTo(map);
        })
      }
    })
    angular.forEach($scope.tribal_boundary_select, function(facet){
      if (facet.selected){
        /*if (facet.geometry.coordinates[0].length == 1){
          $scope.geo_facets.push(facet.geometry.coordinates[0][0])
        } else {
          $scope.geo_facets.push(facet.geometry.coordinates[0]);
        }*/
        $scope.geo_facets.push(facet.geometry.coordinates[0]);
        leafletData.getMap().then(function(map){
          var newLayer = L.geoJSON(facet);
          $scope.tribal_boundary_facets.addLayer(newLayer);
          $scope.tribal_boundary_facets.addTo(map);
        })
      }
    })
    $scope.facet_search();
  };

  $scope.facet_search = function(){
    $scope.docs = [];
    client.search($scope.searchTerm, $scope.facets, $scope.geo_facets).then(function(results){
      var i = 0;
      for (; i < results[1].length; i++){
        $scope.docs.push(results[1][i]);
        $scope.doc_geometry.push(results[1][i].polygon.features[0]);
      }
      leafletData.getMap().then(function(map){
        var vi = 0;
        for (; vi < $scope.doc_geometry.length; vi++) {
          var newLayer =  L.geoJSON($scope.doc_geometry[vi], {
            style: function(feature){
              return {color: "red"};
            }
          }).bindPopup (function(layer){
            return layer.feature.properties.NAMELSAD;
          });
          $scope.feature_set.addLayer(newLayer);
        }
        $scope.feature_set.addTo(map);
        map.fitBounds($scope.feature_set.getBounds());
      })
    })
  }

}]);

Nawrs.factory('client', ['esFactory', '$location', '$q', function (esFactory, $location, $q) {
  var client = esFactory({
    host: 'compute.karlbenedict.com/es',
    apiVersion: '5.0'
  });

  client.ping({
    requestTimeout: 30000,
  }, function (error) {
    if (error) {
      console.error('Failed to connect to Elasticsearch.');
    } else {
      console.log('Connected to Elasticsearch.');
    }
  });

  var search = function(term, filter_terms, filter_geo){
    var deferred = $q.defer();
    var query = {};
    if (filter_geo.length != 0 && filter_terms.length == 0){
      var outer = [];
      var c = 0;
      for (;c < filter_geo.length; c++){
        var inner = [];
        inner.push(filter_geo[c]);
        outer.push(inner);
      }
      query = {
        "bool" : {
          "must" : {
            "match_all" : {}
          },
          "filter" : {
            "geo_shape": {
              "centroid.features.geometry": {
                "shape": {
                  "type": "multipolygon",
                  "coordinates" : outer
                },
                "relation": "intersects"
              }
            }
          }
        }
      }
    } else if (filter_geo.length == 0 && filter_terms.length != 0){
      query = {
        bool: {
          must: [{
            match: {
              _all: term
            }
          }
        ],
        filter: filter_terms
      }
    }
  } else if (filter_geo.length != 0 && filter_terms.length != 0){
    var outer = [];
    var c = 0;
    for (;c < filter_geo.length; c++){
      var inner = [];
      inner.push(filter_geo[c]);
      outer.push(inner);
    }
    query = {
      bool: {
        must: [{
          match: {
            _all: term
          },
          "filter" : {
            "geo_shape": {
              "centroid.features.geometry": {
                "shape": {
                  "type": "multipolygon",
                  "coordinates" : outer
                },
                "relation": "intersects"
              }
            }
          }
        }
      ],
      filter: filter_terms
    }
  }
} else if (filter_geo.length == 0 && filter_terms.length == 0){
  query = {
    bool: {
      must: [{
        match: {
          _all: term
        }
      }
    ]
  }
}
};
client.search({
  index: 'nawrs',
  type: 'item',
  size: 1000,
  body: {
    query: query,
    aggregations: {
      doc_type: {
        terms: {
          field: "type"
        }
      },
      subject: {
        terms: {
          field: "subject"
        }
      }
    }
  }
}).then(function(result){
  var docs_aggs = [];
  docs_aggs.push(result.aggregations);
  var ii = 0, hits_in, hits_out = [];
  hits_in = (result.hits || {}).hits || [];
  for(; ii < hits_in.length; ii++){
    hits_out.push(hits_in[ii]._source);
  }
  docs_aggs.push(hits_out);
  deferred.resolve(docs_aggs);
}, deferred.reject);

return deferred.promise;

};

return {
  search: search
};
}]);
<commit_msg>geo facet update<commit_after>//'use strict';

window.Nawrs = angular.module('nawrs', ['ui-leaflet', 'elasticsearch', 'ngTable']);

// the application
Nawrs.controller('geoSearch', ['$scope', '$http', '$filter', 'client', 'esFactory', '$location', 'NgTableParams', 'leafletMapEvents', 'leafletData', function ($scope, $http, $filter, client, esFactory, $location, NgTableParams, leafletMapEvents, leafletData) {
  // Map bindings

  $scope.state_ref_layer = L.featureGroup();
  $scope.state_facets = L.featureGroup();
  $scope.state_select = [];

  $scope.watershed_ref_layer = L.featureGroup();
  $scope.watershed_facets = L.featureGroup();
  $scope.watershed_select = [];

  $scope.tribal_boundary_layer = L.featureGroup();
  $scope.tribal_boundary_facets = L.featureGroup();
  $scope.tribal_boundary_select = [];

  var tilesDict = {
    osm: {
      name: "OpenStreetMap",
      url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      type: 'xyz',
      options: {
        attribution: '© OpenStreetMap contributors'
      }
    },
    stamen_ter: {
      name: "Stamen Terrain",
      url: 'http://stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}.{ext}',
      options: {
        attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
        ext: 'png'
      }
    },
    esri_world: {
      name: "ESRI World Imagery",
      url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
      options: {
        attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
      }
    }
  }

  angular.extend($scope, {
    tiles: tilesDict.osm,
    centroid: {
      lat: 39.5,
      lng: -98.35,
      zoom: 4
    },
    events: {
      map: {
        enable: ['click'],
        logic: 'emit'
      }
    },
    layers: {
      //overlays: {}
    }
  })

  $http.get('nawrs/data/us_state_PR_1hundthDD.geojson').success(function(data, status){
    leafletData.getMap().then(function(map){
      var newLayer = L.geoJSON(data, {
        onEachFeature: function(feature, layer){
          $scope.state_select.push(layer.feature);
        }
      });
      var i = 0;
      for (; i < $scope.state_select.length; i++){
        $scope.state_select[i].selected = false;
      }
      $scope.state_ref_layer.addLayer(newLayer);
    })
  })

  $http.get('nawrs/data/wbdhu2_PR_1hundthDD.geojson').success(function(data, status){
    leafletData.getMap().then(function(map){
      var newLayer = L.geoJSON(data, {
        onEachFeature: function(feature, layer){
          $scope.watershed_select.push(layer.feature);
        }
      });
      var i = 0;
      for (; i < $scope.watershed_select.length; i++){
        $scope.watershed_select[i].selected = false;
      }
      $scope.watershed_ref_layer.addLayer(newLayer);
    })
  })

  $http.get('nawrs/data/tl_2011_PR_1hundthDD.geojson').success(function(data, status){
    leafletData.getMap().then(function(map){
      var newLayer = L.geoJSON(data, {
        onEachFeature: function(feature, layer){
          $scope.tribal_boundary_select.push(layer.feature);
        }
      });
      var i = 0;
      for (; i < $scope.tribal_boundary_select.length; i++){
        $scope.tribal_boundary_select[i].selected = false;
      }
      $scope.tribal_boundary_layer.addLayer(newLayer);
    })
  })

  $scope.changeTiles = function(tiles) {
    $scope.tiles = tilesDict[tiles];
  }

  $scope.clearFacets = function(){
    $scope.facets = [];
    $scope.geo_facets = [];
    var vi = 0;
    for (; vi < $scope.state_select.length; vi++){
      $scope.state_select[vi].selected = false;
    }
    var vii = 0;
    for (; vii < $scope.watershed_select.length; vii++){
      $scope.watershed_select[vii].selected = false;
    }
    var viii = 0;
    for (; viii < $scope.tribal_boundary_select.length; viii++){
      $scope.tribal_boundary_select[viii].selected = false;
    }
    leafletData.getMap().then(function(map){
      $scope.watershed_facets.clearLayers();
      $scope.state_facets.clearLayers();
      $scope.tribal_boundary_facets.clearLayers();
    })
    $scope.search();
  }

  // Handle search and facet bindings
  var self = this;
  self.tableParams = new NgTableParams({}, { dataset: $scope.docs});

  $scope.searchTerm = $location.search().q;
  $scope.docs = [];
  $scope.doc_type = [];
  $scope.doc_geometry = [];
  $scope.cur_doc_geometry = [];
  $scope.subject = [];
  $scope.facets = [];
  $scope.geo_facets = [];
  $scope.feature_set = L.featureGroup();

  $scope.search = function(search_type){
    $scope.docs = [];
    $scope.facets = [];
    $scope.geo_facets = [];
    $scope.doc_geometry = [];
    $scope.cur_doc_geometry = [];
    $scope.doc_type = [];
    $scope.subject = [];

    leafletData.getMap().then(function(map){
      $scope.feature_set.clearLayers();
      $scope.watershed_facets.clearLayers();
      $scope.state_facets.clearLayers();
      $scope.tribal_boundary_facets.clearLayers();
    })

    client.search($scope.searchTerm, $scope.facets, $scope.geo_facets).then(function(results){
      var i = 0;
      for (; i < results[1].length; i++){
        $scope.docs.push(results[1][i]);
        $scope.doc_geometry.push(results[1][i].polygon.features[0]);
      }
      var ii = 0;
      $scope.doc_type = results[0].doc_type.buckets;
      for (; ii < $scope.doc_type.length; ii++){
        $scope.doc_type[ii].selected = false;
      }
      $scope.subject = results[0].subject.buckets;
      var iii = 0;
      for (; iii < $scope.subject.length; iii++){
        $scope.subject[iii].selected = false;
      }
      var iv = 0;
      for (; iv < $scope.doc_geometry.length; iv++){
        $scope.doc_geometry[iv].selected = false;
      }
      var vi = 0;
      for (; vi < $scope.state_select.length; vi++){
        $scope.state_select[vi].selected = false;
      }
      var vii = 0;
      for (; vii < $scope.watershed_select.length; vii++){
        $scope.watershed_select[vii].selected = false;
      }
      var viii = 0;
      for (; viii < $scope.tribal_boundary_select.length; viii++){
        $scope.tribal_boundary_select[viii].selected = false;
      }
      leafletData.getMap().then(function(map){
        var v = 0;
        for (; v < $scope.doc_geometry.length; v++) {
          $scope.doc_geometry[v].selected = true;
          var newLayer =  L.geoJSON($scope.doc_geometry[v], {
            style: function(feature){
              return {color: "red"};
            }
          }).bindPopup (function(layer){
            return layer.feature.properties.NAMELSAD;
          });
          $scope.feature_set.addLayer(newLayer);
        }
        $scope.feature_set.addTo(map);
        map.fitBounds($scope.feature_set.getBounds());
      })
    })
  }

  $scope.set_facets = function(){
    // get all checked and redo search - don't store old
    var xx = 0;
    for (;xx < $scope.doc_geometry.length; xx++){
      $scope.cur_doc_geometry.push($scope.doc_geometry[xx]);
    }
    $scope.facets = [];
    $scope.geo_facets = [];
    $scope.doc_geometry = [];
    leafletData.getMap().then(function(map){
      $scope.feature_set.clearLayers();
      $scope.watershed_facets.clearLayers();
      $scope.state_facets.clearLayers();
      $scope.tribal_boundary_facets.clearLayers();
    })
    angular.forEach($scope.doc_type, function(facet){
      if (facet.selected){
        var f = {
          "term": {}
        };
        f.term.type = facet.key;
        $scope.facets.push(f);
      }
    })
    angular.forEach($scope.subject, function(facet){
      if (facet.selected){
        var f = {
          "term": {}
        };
        f.term.subject = facet.key;
        $scope.facets.push(f);
      }
    })
    angular.forEach($scope.cur_doc_geometry, function(facet){
      if (facet.selected){
        if (facet.geometry.coordinates[0].length == 1){
          $scope.geo_facets.push(facet.geometry.coordinates[0][0])
        } else {
          $scope.geo_facets.push(facet.geometry.coordinates[0]);
        }
      }
    })
    angular.forEach($scope.state_select, function(facet){
      if (facet.selected){
        if (facet.geometry.coordinates[0].length == 1){
          $scope.geo_facets.push(facet.geometry.coordinates[0][0])
        } else {
          $scope.geo_facets.push(facet.geometry.coordinates[0]);
        }
        leafletData.getMap().then(function(map){
          var newLayer = L.geoJSON(facet);
          $scope.state_facets.addLayer(newLayer);
          $scope.state_facets.addTo(map);
        })
      }
    })
    angular.forEach($scope.watershed_select, function(facet){
      if (facet.selected){
        if (facet.geometry.coordinates[0].length == 1){
          $scope.geo_facets.push(facet.geometry.coordinates[0][0])
        } else {
          $scope.geo_facets.push(facet.geometry.coordinates[0]);
        }
        leafletData.getMap().then(function(map){
          var newLayer = L.geoJSON(facet);
          $scope.watershed_facets.addLayer(newLayer);
          $scope.watershed_facets.addTo(map);
        })
      }
    })
    angular.forEach($scope.tribal_boundary_select, function(facet){
      if (facet.selected){
        /*if (facet.geometry.coordinates[0].length == 1){
          $scope.geo_facets.push(facet.geometry.coordinates[0][0])
        } else {
          $scope.geo_facets.push(facet.geometry.coordinates[0]);
        }*/
        $scope.geo_facets.push(facet.geometry.coordinates);
        leafletData.getMap().then(function(map){
          var newLayer = L.geoJSON(facet);
          $scope.tribal_boundary_facets.addLayer(newLayer);
          $scope.tribal_boundary_facets.addTo(map);
        })
      }
    })
    $scope.facet_search();
  };

  $scope.facet_search = function(){
    $scope.docs = [];
    client.search($scope.searchTerm, $scope.facets, $scope.geo_facets).then(function(results){
      var i = 0;
      for (; i < results[1].length; i++){
        $scope.docs.push(results[1][i]);
        $scope.doc_geometry.push(results[1][i].polygon.features[0]);
      }
      leafletData.getMap().then(function(map){
        var vi = 0;
        for (; vi < $scope.doc_geometry.length; vi++) {
          var newLayer =  L.geoJSON($scope.doc_geometry[vi], {
            style: function(feature){
              return {color: "red"};
            }
          }).bindPopup (function(layer){
            return layer.feature.properties.NAMELSAD;
          });
          $scope.feature_set.addLayer(newLayer);
        }
        $scope.feature_set.addTo(map);
        map.fitBounds($scope.feature_set.getBounds());
      })
    })
  }

}]);

Nawrs.factory('client', ['esFactory', '$location', '$q', function (esFactory, $location, $q) {
  var client = esFactory({
    host: 'compute.karlbenedict.com/es',
    apiVersion: '5.0'
  });

  client.ping({
    requestTimeout: 30000,
  }, function (error) {
    if (error) {
      console.error('Failed to connect to Elasticsearch.');
    } else {
      console.log('Connected to Elasticsearch.');
    }
  });

  var search = function(term, filter_terms, filter_geo){
    var deferred = $q.defer();
    var query = {};
    if (filter_geo.length != 0 && filter_terms.length == 0){
      var outer = [];
      var c = 0;
      for (;c < filter_geo.length; c++){
        var inner = [];
        inner.push(filter_geo[c]);
        outer.push(inner);
      }
      query = {
        "bool" : {
          "must" : {
            "match_all" : {}
          },
          "filter" : {
            "geo_shape": {
              "centroid.features.geometry": {
                "shape": {
                  "type": "multipolygon",
                  "coordinates" : filter_geo
                },
                "relation": "intersects"
              }
            }
          }
        }
      }
    } else if (filter_geo.length == 0 && filter_terms.length != 0){
      query = {
        bool: {
          must: [{
            match: {
              _all: term
            }
          }
        ],
        filter: filter_terms
      }
    }
  } else if (filter_geo.length != 0 && filter_terms.length != 0){
    var outer = [];
    var c = 0;
    for (;c < filter_geo.length; c++){
      var inner = [];
      inner.push(filter_geo[c]);
      outer.push(inner);
    }
    query = {
      bool: {
        must: [{
          match: {
            _all: term
          },
          "filter" : {
            "geo_shape": {
              "centroid.features.geometry": {
                "shape": {
                  "type": "multipolygon",
                  "coordinates" : filter_geo
                },
                "relation": "intersects"
              }
            }
          }
        }
      ],
      filter: filter_terms
    }
  }
} else if (filter_geo.length == 0 && filter_terms.length == 0){
  query = {
    bool: {
      must: [{
        match: {
          _all: term
        }
      }
    ]
  }
}
};
client.search({
  index: 'nawrs',
  type: 'item',
  size: 1000,
  body: {
    query: query,
    aggregations: {
      doc_type: {
        terms: {
          field: "type"
        }
      },
      subject: {
        terms: {
          field: "subject"
        }
      }
    }
  }
}).then(function(result){
  var docs_aggs = [];
  docs_aggs.push(result.aggregations);
  var ii = 0, hits_in, hits_out = [];
  hits_in = (result.hits || {}).hits || [];
  for(; ii < hits_in.length; ii++){
    hits_out.push(hits_in[ii]._source);
  }
  docs_aggs.push(hits_out);
  deferred.resolve(docs_aggs);
}, deferred.reject);

return deferred.promise;

};

return {
  search: search
};
}]);
<|endoftext|>


<commit_before>var Environment = require("qbs.Environment");

function setupEnvironment()
{
	if (product.qbs.hostOS.contains("windows"))
		Environment.putEnv("PATH", product.cutehmi.dirs.externalLibDir + product.qbs.pathListSeparator + Environment.getEnv("PATH"))
	else
		Environment.putEnv("LD_LIBRARY_PATH", product.cutehmi.dirs.externalLibDir + product.qbs.pathListSeparator + Environment.getEnv("LD_LIBRARY_PATH"))

	Environment.putEnv("QML2_IMPORT_PATH", product.cutehmi.dirs.installDir + "/" + product.cutehmi.dirs.extensionsInstallSubdir)

	Environment.putEnv("CUTEHMI_INSTALL_DIR", product.cutehmi.dirs.installDir)
	Environment.putEnv("CUTEHMI_TOOLS_INSTALL_SUBDIR", product.cutehmi.dirs.toolsInstallSubdir)
}

//(c)C: Copyright © 2019-2020, Michał Policht <michal@policht.pl>. All rights reserved.
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI.  If not, see <https://www.gnu.org/licenses/>.
<commit_msg>Set 'CUTEHMI_SOURCE_DIR' environmental variable.<commit_after>var Environment = require("qbs.Environment");

function setupEnvironment()
{
	if (product.qbs.hostOS.contains("windows"))
		Environment.putEnv("PATH", product.cutehmi.dirs.externalLibDir + product.qbs.pathListSeparator + Environment.getEnv("PATH"))
	else
		Environment.putEnv("LD_LIBRARY_PATH", product.cutehmi.dirs.externalLibDir + product.qbs.pathListSeparator + Environment.getEnv("LD_LIBRARY_PATH"))

	Environment.putEnv("QML2_IMPORT_PATH", product.cutehmi.dirs.installDir + "/" + product.cutehmi.dirs.extensionsInstallSubdir)

	Environment.putEnv("CUTEHMI_INSTALL_DIR", product.cutehmi.dirs.installDir)
	Environment.putEnv("CUTEHMI_TOOLS_INSTALL_SUBDIR", product.cutehmi.dirs.toolsInstallSubdir)
	Environment.putEnv("CUTEHMI_SOURCE_DIR", product.sourceDirectory)
}

//(c)C: Copyright © 2019-2020, Michał Policht <michal@policht.pl>. All rights reserved.
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI.  If not, see <https://www.gnu.org/licenses/>.
<|endoftext|>


<commit_before>/**
 * Created by ksinger on 20.08.2015.
 */
;
import won from '../won-es6';
import angular from 'angular';
import loginComponent from 'app/components/login';
import logoutComponent from 'app/components/logout';
import { attach } from '../utils';
import { actionCreators }  from '../actions/actions';

function genTopnavConf() {
    let template = `

            Lost connection – make sure your internet-connection
            is working, then click “reconnect”.
            <button
                ng-show="self.connectionHasBeenLost && !self.reconnecting" ng-click="self.reconnect()"
                class="si__button won-button outline white">
                    Reconnect
            </button>

                            Web of Needs – Beta

                        New Need

                            <button
                                ui-sref="landingpage({focusSignup: true})"
                                class="topnav__button won-button--filled lighterblue"
                                ng-show="!self.open">
                                    Sign up
                            </button>

                                    Sign in

                                {{self.email}}

                    <won-login open="self.open"></won-login>

                    <won-logout open="self.open"></won-logout>

{{toast.get('msg')}}

    `;

    const serviceDependencies = ['$q', '$ngRedux', '$scope', /*injections as strings here*/];

    class Controller {
        constructor(/* arguments <- serviceDependencies */){
            attach(this, serviceDependencies, arguments);
            window.tnc4dbg = this;

            const selectFromState = (state) => ({
                WON: won.WON,
                loginVisible: state.get('loginVisible'),
                open: state.get('loginVisible'), // TODO interim while transition to redux-state based solution (i.e. "loginVisible")
                loggedIn: state.getIn(['user', 'loggedIn']),
                email: state.getIn(['user','email']),
                toastsArray: state.getIn(['toasts']).toArray(),
                connectionHasBeenLost: state.getIn(['messages', 'lostConnection']), // name chosen to avoid name-clash with the action-creator
                reconnecting: state.getIn(['messages', 'reconnecting']),
            });

            const disconnect = this.$ngRedux.connect(selectFromState, actionCreators)(this);
            this.$scope.$on('$destroy',disconnect);
        }
    }
    Controller.$inject = serviceDependencies;

    return {
        restrict: 'E',
        scope: {},//isolate scope to allow usage within other controllers/components
        controller: Controller,
        controllerAs: 'self',
        bindToController: true, //scope-bindings -> ctrl
        template: template
    }
}

export default angular.module('won.owner.components.topnav', [
        loginComponent,
        logoutComponent
    ])
    .directive('wonTopnav', genTopnavConf)
    .name;

<commit_msg>fixed defect #945<commit_after>/**
 * Created by ksinger on 20.08.2015.
 */
;
import won from '../won-es6';
import angular from 'angular';
import loginComponent from 'app/components/login';
import logoutComponent from 'app/components/logout';
import { attach } from '../utils';
import { actionCreators }  from '../actions/actions';

function genTopnavConf() {
    let template = `

            Lost connection – make sure your internet-connection
            is working, then click “reconnect”.
            <button
                ng-show="self.connectionHasBeenLost && !self.reconnecting" ng-click="self.reconnect()"
                class="si__button won-button outline white">
                    Reconnect
            </button>

                            Web of Needs – Beta

                        New Need

                            <button
                                ui-sref="landingpage({focusSignup: true})"
                                class="topnav__button won-button--filled lighterblue"
                                ng-show="!self.open">
                                    Sign up
                            </button>

                                    Sign in

                                {{self.email}}

                    <won-login open="self.open"></won-login>

                    <won-logout open="self.open"></won-logout>

{{toast.get('msg')}}

    `;

    const serviceDependencies = ['$q', '$ngRedux', '$scope', /*injections as strings here*/];

    class Controller {
        constructor(/* arguments <- serviceDependencies */){
            attach(this, serviceDependencies, arguments);
            window.tnc4dbg = this;

            const selectFromState = (state) => ({
                WON: won.WON,
                loginVisible: state.get('loginVisible'),
                open: state.get('loginVisible'), // TODO interim while transition to redux-state based solution (i.e. "loginVisible")
                loggedIn: state.getIn(['user', 'loggedIn']),
                focusSignup: state.getIn(['router', 'currentParams', 'focusSignup']) === "true",
                email: state.getIn(['user','email']),
                toastsArray: state.getIn(['toasts']).toArray(),
                connectionHasBeenLost: state.getIn(['messages', 'lostConnection']), // name chosen to avoid name-clash with the action-creator
                reconnecting: state.getIn(['messages', 'reconnecting']),
            });

            const disconnect = this.$ngRedux.connect(selectFromState, actionCreators)(this);
            this.$scope.$on('$destroy',disconnect);
        }
    }
    Controller.$inject = serviceDependencies;

    return {
        restrict: 'E',
        scope: {},//isolate scope to allow usage within other controllers/components
        controller: Controller,
        controllerAs: 'self',
        bindToController: true, //scope-bindings -> ctrl
        template: template
    }
}

export default angular.module('won.owner.components.topnav', [
        loginComponent,
        logoutComponent
    ])
    .directive('wonTopnav', genTopnavConf)
    .name;

<|endoftext|>


<commit_before>import AFRAME from 'aframe';
import 'aframe-animation-component';
import 'aframe-text-component';
import 'babel-polyfill';
import {Entity, Scene} from 'aframe-react';
import React from 'react';
import { Link, withRouter } from 'react-router';

import Camera from './Camera';
import Text from './Text';
import Sky from './Sky';
import Plane from './Plane';

export default props => {
    props.getLikes();
    console.log('Within Home, props is currently:', props)
    let pics = props.pics.map((pic, index) => {
    // console.log(pic.title, index, pic.imageLink)
    const rot = '0 ' + (index * -35) + ' 0';
    // var row;
    // if (index >18 && index <= 27) {
    //   row = -1.1;
    // } else if (index > 9 && index <= 18) {
    //   row = 0;
    // } else if (index > -1 && index <= 9) {
    //   row = 1.1;
    // }
    var imageName = pic.title.split('.')[0];
    return (
      <Entity
      rotation={rot}
      position={"0 "+ ((index*-0.15)+0.5) +" 0"}
      material={{src: ('#resized-'+imageName), color: '#FFF', shader: 'flat', side: 'double', transparent: 'true', repeat: '-1 1'}}
      geometry="height:1;primitive:cylinder;radius:2;segmentsRadial:48;thetaLength:30;openEnded:true;thetaStart:0"
      photoID={pic.id}
      onClick={() => {
        props.router.replace('/' + imageName)
        props.changeBigPic(pic.title, pic.id)
      }} />
    );
  });
  return (
    <Entity>
        <Entity animation__rot={{property: 'rotation', dur: 200000, loop: 'repeat', to: '0 360 0', easing: 'linear'}} >
        {pics}
        </Entity>

        <a-image look-at="[camera]" id="exit-image" src="#exit" geometry="height: 0.3; width: 0.3" position="0.64 -2.5 2.36" onClick={() => props.router.replace('/dashboard')}></a-image>

        <Entity light={{type: 'ambient', color: '#fff'}}/>
        <Entity light={{type: 'directional', intensity: 0.2}} position='-1 2 1'/>

        <a-sky src='#lobby-_1' rotation='0 -90 0'></a-sky>
    </Entity>
  );
};

<commit_msg>Code cleanup in Home.js<commit_after>import AFRAME from 'aframe';
import 'aframe-animation-component';
import 'aframe-text-component';
import 'babel-polyfill';
import {Entity, Scene} from 'aframe-react';
import React from 'react';
import { Link, withRouter } from 'react-router';

import Camera from './Camera';
import Text from './Text';
import Sky from './Sky';
import Plane from './Plane';

export default props => {
    props.getLikes();
    console.log('Within Home, props is currently:', props)
    let pics = props.pics.map((pic, index) => {
    // console.log(pic.title, index, pic.imageLink)
    const rot = '0 ' + (index * -35) + ' 0';
    var imageName = pic.title.split('.')[0];
    return (
      <Entity
      rotation={rot}
      position={"0 "+ ((index*-0.15)+0.5) +" 0"}
      material={{src: ('#resized-'+imageName), color: '#FFF', shader: 'flat', side: 'double', transparent: 'true', repeat: '-1 1'}}
      geometry="height:1;primitive:cylinder;radius:2;segmentsRadial:48;thetaLength:30;openEnded:true;thetaStart:0"
      photoID={pic.id}
      onClick={() => {
        props.router.replace('/' + imageName)
        props.changeBigPic(pic.title, pic.id)
      }} />
    );
  });

  return (
    <Entity>
        <Entity animation__rot={{property: 'rotation', dur: 200000, loop: 'repeat', to: '0 360 0', easing: 'linear'}} >
        {pics}
        </Entity>

        <a-image look-at="[camera]" id="exit-image" src="#exit" geometry="height: 0.3; width: 0.3" position="0.64 -2.5 2.36" onClick={() => props.router.replace('/dashboard')}></a-image>

        <Entity light={{type: 'ambient', color: '#fff'}}/>
        <Entity light={{type: 'directional', intensity: 0.2}} position='-1 2 1'/>

        <a-sky src='#lobby-_1' rotation='0 -90 0'></a-sky>
    </Entity>
  );
};

<|endoftext|>


<commit_before>module.exports = {

    applicationPersonalInfo:[
        'Applicant',
        'Spouse',
        'Child Under 19',
        'Child19-24',
    ],

  sectionTitle: ['Main Applicant (Account Holder)',
      'Spouse',
      'Child',
      'Child'],

  /*
   * Status for each relationship type
   */
  statusLabel: ['Your Status in Canada',
    'Spouses Status in Canada',
    'Child Status in Canada',
    'Child Status in Canada'],
  documentInstructionLabel: ['Your ID requirements',
    'Spouse\'s ID requirements',
    'Child\'s ID requirements',
    'Child\'s ID requirements'],
  documentInstructionsIntro: 'You need to include one of the following with your application:',
  documentInstructionsMarriage: 'Has your name changed since your ID was issue due to marriage or a legal name change? If so, include one or more of the following:',
  documentUploadLabel: [' Upload your documents',
    ' Upload your spouse\'s documents',
    ' Upload your child\'s documents',
    ' Upload your child\'s documents'],
  documentInstructionsNote: 'Scan the document, or take a photo of it. Make sure that it’s:

The entire document, from corner to corner

At least 1000 pixels wide x 1500 pixels tall

Rotated correctly (not upside down or sideways)

In focus and easy to read

A JPG or PNG file (not a PDF)

',
  viewSamplesButton: 'See a sample',

  nameHelpBlock: ['Enter your legal name and gender',
    'Enter your spouse\'s legal name and gender',
    'Enter your child\'s legal name and gender',
    'Enter your child\'s legal name and gender'],

  livedInBCSinceBirth: ['Have you lived in B.C. since birth?',
      'Has your spouse lived in B.C. since birth?',
      'Has your child lived in B.C. since birth?',
      'Has your child lived in B.C. since birth?'],

  phnLabel: ['Your previous B.C. Personal Health Number',
    'Spouse\'s previous B.C. Personal Health Number',
    'Child\'s previous B.C. Personal Health Number',
    'Child\'s previous B.C. Personal Health Number'],

  previousBCHealthNumber: ['Do you have a previous B.C. Personal Health Number?',
      'Does your spouse have a previous B.C. Personal Health Number?',
      'Does your child have a previous B.C. Personal Health Number?',
      'Does your child have a previous B.C. Personal Health Number?'],

  movedFromProvinceLabel: ['Which province are you moving from?',
    'Which province are they moving from?',
    'Which province are they moving from?',
    'Which province are they moving from?'],

  movedFromCountryLabel: 'Which country are you moving from?',
  arrivalDateToBCLabel: 'Arrival date in B.C.',
  arrivalDateToBCLabelForReturning: 'Most recent move to B.C.',
  arrivalDateToCanadaLabel: 'Arrival date in Canada',

  beenOutsideBCOver30DaysLabel: "Since you arrived, have you been outside B.C. for more than 30 days in total?",
  beenOutsideBCForMoreThan30DaysInTotalInThePast12Months: "Have you been outside B.C. for more than 30 days in total in the past 12 months",
  fullTimeStudentLabel: 'Are you a full-time student?',
  haveYouMovedToBCPermanently: 'Have you moved to BC permanently?',
  assertChildBeFullTimeStudent: 'School Information for Full-time Student Child',
  inBCAfterStudiesLabel: 'Will you reside in B.C. upon completion of your studies?',
  childStayInBCAfterStudiesLabel: 'Will this child reside in B.C. after completing study in this school?',

  canadianForcesQuestion: ['Have you been released from the Canadian Armed Forces or an Institution?',
    'Have they been released from the Canadian Armed Forces or an Institution?',
    'Have they been released from the Canadian Armed Forces or an Institution?',
    'Have they been released from the Canadian Armed Forces or an Institution?'],

  nameOfSchool: 'Name of school that this child is attending',
  fullAttendanceLabel: '(must be in full-time attendance)',
  schoolNameErrorIsRequired: 'Name of school is required',
  schoolAddressLabel: 'School address',

  removeSpouseButton: 'Remove',
  removeChildButton: 'Remove',
  mustAnswerQuestionAboutBeenOutsideBC: 'You must answer this question about your absence from B.C.',
  mustAnswerQuestionAboutPermMoveToBC: 'You must answer this question about your move to B.C.',
  mustDeclareStudentStatus: "Are you a full time student right now?",
  mustDeclareInstitutionWorkHistory: "Please answer this question.",
  mustAnswerQuestion: "This question has to be answered in order to continue with the application."
}
<commit_msg>update full-time student label based on user testing<commit_after>module.exports = {

    applicationPersonalInfo:[
        'Applicant',
        'Spouse',
        'Child Under 19',
        'Child19-24',
    ],

  sectionTitle: ['Main Applicant (Account Holder)',
      'Spouse',
      'Child',
      'Child'],

  /*
   * Status for each relationship type
   */
  statusLabel: ['Your Status in Canada',
    'Spouses Status in Canada',
    'Child Status in Canada',
    'Child Status in Canada'],
  documentInstructionLabel: ['Your ID requirements',
    'Spouse\'s ID requirements',
    'Child\'s ID requirements',
    'Child\'s ID requirements'],
  documentInstructionsIntro: 'You need to include one of the following with your application:',
  documentInstructionsMarriage: 'Has your name changed since your ID was issue due to marriage or a legal name change? If so, include one or more of the following:',
  documentUploadLabel: [' Upload your documents',
    ' Upload your spouse\'s documents',
    ' Upload your child\'s documents',
    ' Upload your child\'s documents'],
  documentInstructionsNote: 'Scan the document, or take a photo of it. Make sure that it’s:

The entire document, from corner to corner

At least 1000 pixels wide x 1500 pixels tall

Rotated correctly (not upside down or sideways)

In focus and easy to read

A JPG or PNG file (not a PDF)

',
  viewSamplesButton: 'See a sample',

  nameHelpBlock: ['Enter your legal name and gender',
    'Enter your spouse\'s legal name and gender',
    'Enter your child\'s legal name and gender',
    'Enter your child\'s legal name and gender'],

  livedInBCSinceBirth: ['Have you lived in B.C. since birth?',
      'Has your spouse lived in B.C. since birth?',
      'Has your child lived in B.C. since birth?',
      'Has your child lived in B.C. since birth?'],

  phnLabel: ['Your previous B.C. Personal Health Number',
    'Spouse\'s previous B.C. Personal Health Number',
    'Child\'s previous B.C. Personal Health Number',
    'Child\'s previous B.C. Personal Health Number'],

  previousBCHealthNumber: ['Do you have a previous B.C. Personal Health Number?',
      'Does your spouse have a previous B.C. Personal Health Number?',
      'Does your child have a previous B.C. Personal Health Number?',
      'Does your child have a previous B.C. Personal Health Number?'],

  movedFromProvinceLabel: ['Which province are you moving from?',
    'Which province are they moving from?',
    'Which province are they moving from?',
    'Which province are they moving from?'],

  movedFromCountryLabel: 'Which country are you moving from?',
  arrivalDateToBCLabel: 'Arrival date in B.C.',
  arrivalDateToBCLabelForReturning: 'Most recent move to B.C.',
  arrivalDateToCanadaLabel: 'Arrival date in Canada',

  beenOutsideBCOver30DaysLabel: "Since you arrived, have you been outside B.C. for more than 30 days in total?",
  beenOutsideBCForMoreThan30DaysInTotalInThePast12Months: "Have you been outside B.C. for more than 30 days in total in the past 12 months",
  fullTimeStudentLabel: 'Are you a full-time student in B.C.?',
  haveYouMovedToBCPermanently: 'Have you moved to BC permanently?',
  assertChildBeFullTimeStudent: 'School Information for Full-time Student Child',
  inBCAfterStudiesLabel: 'Will you reside in B.C. upon completion of your studies?',
  childStayInBCAfterStudiesLabel: 'Will this child reside in B.C. after completing study in this school?',

  canadianForcesQuestion: ['Have you been released from the Canadian Armed Forces or an Institution?',
    'Have they been released from the Canadian Armed Forces or an Institution?',
    'Have they been released from the Canadian Armed Forces or an Institution?',
    'Have they been released from the Canadian Armed Forces or an Institution?'],

  nameOfSchool: 'Name of school that this child is attending',
  fullAttendanceLabel: '(must be in full-time attendance)',
  schoolNameErrorIsRequired: 'Name of school is required',
  schoolAddressLabel: 'School address',

  removeSpouseButton: 'Remove',
  removeChildButton: 'Remove',
  mustAnswerQuestionAboutBeenOutsideBC: 'You must answer this question about your absence from B.C.',
  mustAnswerQuestionAboutPermMoveToBC: 'You must answer this question about your move to B.C.',
  mustDeclareStudentStatus: "Are you a full time student right now?",
  mustDeclareInstitutionWorkHistory: "Please answer this question.",
  mustAnswerQuestion: "This question has to be answered in order to continue with the application."
}
<|endoftext|>


<commit_before>// Adding a mode parameter with "build" as value in the run-tests.html will
// make usage of the build version of the library.
var regexS = "[\\?&]mode=([^&#]*)";
var regex = new RegExp( regexS );
var href = window.parent.location.href;
var url = href.substring(0, href.lastIndexOf('/') + 1);
var results = regex.exec( href );
url += (results && results[1] == 'build') ?
    "../build/OpenLayers.js" : "../lib/OpenLayers.js";
scriptTag = "<script src='" + url + "'></script>";
document.write(scriptTag);
<commit_msg>Now we rely on relative paths + minor changes<commit_after>// Adding a mode parameter with "build" as value in the run-tests.html will
// make usage of the build version of the library.
// get the OLLoader.js script location

var r = new RegExp("(^|(.*?\\/))(" + "OLLoader.js" + ")(\\?|$)"),
    s = document.getElementsByTagName('script'),
    src, m, l = "";
for(var i=0, len=s.length; i<len; i++) {
    src = s[i].getAttribute('src');
    if(src) {
        var m = src.match(r);
        if(m) {
            l = m[1];
            break;
        }
    }
}

var regex = new RegExp( "[\\?&]mode=([^&#]*)" );
var href = window.parent.location.href;
var results = regex.exec( href );
l += (results && results[1] == 'build') ?
    "../build/OpenLayers.js" : "../lib/OpenLayers.js";
scriptTag = "<script src='" + l + "'></script>";
document.write(scriptTag);
<|endoftext|>


<commit_before>angular.module('phonecatFilters', []).filter('checkmark', function() {
  return function(input) {
      return input;
  };
});
function AccordionDemoCtrl($scope) {
  $scope.oneAtATime = true;

  $scope.groups = [
    {
      title: 'Dynamic Group Header - 1',
      content: 'Dynamic Group Body - 1'
    },
    {
      title: 'Dynamic Group Header - 2',
      content: 'Dynamic Group Body - 2'
    }
  ];

  $scope.items = ['Item 1', 'Item 2', 'Item 3'];

  $scope.addItem = function() {
    var newItemNo = $scope.items.length + 1;
    $scope.items.push('Item ' + newItemNo);
  };

  $scope.status = {
    isFirstOpen: true,
    isFirstDisabled: false
  };
}
var mozAUApp = angular.module('mozAUApp', ['ngRoute','ui.bootstrap','dndLists']);
mozAUApp.config(function($routeProvider){
    $routeProvider
    // route for the home page
    .when('/', {
        templateUrl : '/static/js/pages/list.html',
        controller  : 'ServerListCtrl'
    })

    .when('/scripts/create/', {
        templateUrl : '/static/js/pages/script_create.html',
        controller  : 'ScriptCreateCtrl'
    })

    .when('/scripts/edit/:id', {
        templateUrl : '/static/js/pages/script_edit.html',
        controller  : 'ScriptEditCtrl'
    })

    // route for the about page
    .when('/detail/:hostname', {
        templateUrl : '/static/js/pages/update_list.html',
        controller  : 'UpdateListCtrl'
    })

    .when('/scripts/:hostname', {
        templateUrl : '/static/js/pages/edit_scripts.html',
        controller  : 'ScriptsCtrl'
    })

    .when('/updatedetail/:id', {
        templateUrl : '/static/js/pages/update_detail.html',
        controller  : 'BackupDetailCtrl'
    })

    .when('/updatecron/:hostname', {
        templateUrl : '/static/js/pages/update_cron.html',
        controller  : 'UpdateCronCtrl'
    })

    // route for the contact page
    .when('/contact', {
        templateUrl : 'pages/contact.html',
        controller  : 'contactController'
    });
});

mozAUApp.directive('delaySearch', function ($timeout) {
        return {
            restrict: 'EA',
            template: ' <input ng-model="search" ng-change="modelChanged()">',
            link: function ($scope, element, attrs) {
                $scope.modelChanged = function () {
                    $timeout(function () {
                        if ($scope.lastSearch != $scope.search) {
                            if ($scope.delayedMethod) {
                                $scope.lastSearch = $scope.search;
                                $scope.delayedMethod({ search: $scope.search });
                            }
                        }
                    }, 300);
                }
            },
            scope: {
                delayedMethod:'&'
            }
        }
    });

mozAUApp.controller('ScriptEditCtrl', function ($scope, $location, $http, $interval, $routeParams) {
    $scope.debug = false;
    $scope.id = $routeParams['id'];
    $scope.file_name = ''
    $scope.description = ''

    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }
    var changeLocation = function(url, forceReload) {
      $scope = $scope || angular.element(document).scope();
      if(forceReload || $scope.$$phase) {
        window.location = url;
      }
      else {
        $location.path(url);
        $scope.$apply();
      }
    };

    $scope.update = function() {
        $scope.alert_id++;
        data = {};
        data['file_name'] = $scope.file_name;
        data['description'] = $scope.description;
        $http({
            withCredentials: false,
            method: 'post',
            headers: { 'Content-Type': 'application/json' },
            url: '/api/scriptedit/' + $scope.id + '/',
            data: JSON.stringify(data)
        }).success(function(data){
            changeLocation('/#/scripts/')
        }).error(function(data){
            log(data);
        });
        log("$scope.filename: " + $scope.file_name);
        log("$scope.description: " + $scope.description);
    }

    $scope.init = function(){
        $http.get('/api/scriptdetail/' + $scope.id + '/').success(function(data){
            $scope.file_name = data.script.file_name;
            $scope.description = data.script.description;
            log($scope.scripts);
        });

    }

});
mozAUApp.controller('ScriptCreateCtrl', function ($scope, $location, $http, $interval) {
    $scope.debug = false;
    $scope.file_name = ''
    $scope.description = ''

    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }
    var changeLocation = function(url, forceReload) {
      $scope = $scope || angular.element(document).scope();
      if(forceReload || $scope.$$phase) {
        window.location = url;
      }
      else {
        $location.path(url);
        $scope.$apply();
      }
    };

    $scope.create = function() {
        $scope.alert_id++;
        data = {};
        data['file_name'] = $scope.file_name;
        data['description'] = $scope.description;
        $http({
            withCredentials: false,
            method: 'post',
            headers: { 'Content-Type': 'application/json' },
            url: '/api/scriptcreate/',
            data: JSON.stringify(data)
        }).success(function(data){
            changeLocation('/#/scripts/')
        }).error(function(data){
            log(data);
        });
        log("$scope.filename: " + $scope.file_name);
        log("$scope.description: " + $scope.description);
    }

    $scope.init = function(){
        log('init called');
    }

});

mozAUApp.controller('ScriptListCtrl', function ($scope, $http, $interval) {
    $scope.debug = false;
    $scope.scripts = [];

    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }

    function scripts(){
        $http.get('/api/scripts/').success(function(data){
            $scope.scripts = data.scripts;
            log($scope.scripts);
        });
    }

    $scope.init = function(){
        log('Calling Init')
        scripts();
    }

});
mozAUApp.controller('ServerListCtrl', function ($scope, $http, $interval) {
    $scope.debug = false;
    $scope.systems = [];
    $scope.recent = [];
    $scope.system = '';

    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }

    function recent_updates(limit){
        $http.get('/api/recentupdateonly/?limit=' + limit).success(function(data){
            $scope.recent = data.updates;
            log($scope.recent);
        });
    }

    $scope.requery = function(search){
        $scope.systems = [];
        if(search){
            $http.get('/api/system/?hostname=' + search).success(function(data){
                $scope.systems = data.systems;
            });
        }
        log("requery called");
    };

    $scope.init = function(limit){
        log("init called");
        if(!$scope.timer){
            $scope.timer = $interval(function(){
                recent_updates(20);
            }, 5000);
        }
        recent_updates(20);
    }

    $scope.$on('$destroy', function() {
      $interval.cancel($scope.timer);
    });

});

mozAUApp.controller('UpdateListCtrl', function ($scope, $http, $routeParams, $interval) {
    $scope.hostname = $routeParams['hostname'];
    $scope.has_loaded = false;
    $scope.updates = [];
    $scope.debug = false;
    $scope.system = {};
    $scope.pings = [];
    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }
    $scope.ping = function(){
        log("Ping Called");
        $http.get('/api/ping/' + $scope.hostname + '/').success(function(data){
            log(data);
        });
    }

    $scope.start_update = function(){
        log("start_update Called");
        $http.get('/api/start_update/' + $scope.hostname + '/').success(function(data){
            log(data);
        });
    }

    function build_update_list(limit){
        if (!limit){
            limit = 10;
        }
        $http.get('/api/updates/' + $scope.hostname + '?limit=' + limit).success(function(data){
            $scope.updates = data.updates;
        });
        $http.get('/api/system/' + $scope.hostname + '/').success(function(data){
            $scope.system = data.system;
            $scope.pings = data.system.pings;
            log($scope.pings);
        });
        $scope.has_loaded = true;
    }
    $scope.init = function(limit){
        log("init called");
        if(!$scope.timer){
            $scope.timer = $interval(function(){
                build_update_list(limit);
            }, 5000);
        }
        build_update_list(limit);
    }

    $scope.$on('$destroy', function() {
      $interval.cancel($scope.timer);
    });

});

mozAUApp.controller('UpdateCronCtrl', function ($scope, $http, $sce, $routeParams) {
    $scope.hostname = $routeParams['hostname'];
    $scope.debug = false;
    $scope.system = {};
    $scope.cronfile = "";
    $scope.show_success = false;
    $scope.success_message = "";
    $scope.alert_id = 1;
    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }
    $scope.updateCronfile = function(){
        $scope.alert_id++;
        data = {};
        data['cronfile'] = $scope.cronfile;
        $http({
            withCredentials: false,
            method: 'post',
            headers: { 'Content-Type': 'application/json' },
            url: '/api/updatecronfile/' + $scope.system.id + '/',
            data: JSON.stringify(data)
        }).success(function(data){
            var alert_text = '
<button type="button" class="close" id="' + $scope.alert_id +' " data-dismiss="alert" aria-hidden="true">×</button>Cronfile Successfully Updated
';
            $scope.success_message = $sce.trustAsHtml(alert_text);
        });
    }

    $scope.init = function(limit){
        $http.get('/api/system/' + $scope.hostname + '/').success(function(data){
            $scope.system = data.system;
            $scope.cronfile = $scope.system.cronfile;
        });
    }
});
mozAUApp.controller('ScriptsCtrl', function ($scope, $http, $routeParams) {
    $scope.debug = false;
    $scope.hostname = $routeParams['hostname'];
    $scope.installed_script_file_names = [];
    $scope.current_installed_scripts = {};
    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }

    $scope.models = {
        selected: null,
        lists: {
            "Installed_Scripts": [],
            "Available_Scripts": []
        }
    };

    // Generate initial model
    $http.get('/api/hostscripts/' + $scope.hostname + '/').success(function(data){
        for (f=0;f<data.scripts.length;f++){
            $scope.models.lists.Installed_Scripts.push({
                label: data.scripts[f].file_name,
                id: data.scripts[f].id
            });
            $scope.installed_script_file_names.push(data.scripts[f].file_name)
        }
        $scope.current_installed_scripts = $scope.models.lists.Installed_Scripts;
    });
    $http.get('/api/scripts/').success(function(data){
        for (f=0;f<data.scripts.length;f++){
            if ($scope.installed_script_file_names.indexOf(data.scripts[f].file_name) == -1){
                $scope.models.lists.Available_Scripts.push({
                    label: data.scripts[f].file_name,
                    id: data.scripts[f].id
                });
            }
        }
    });

    // Model to JSON for demo purpose
    $scope.save = function(){
        $scope.modelAsJson = angular.toJson($scope.models.lists.Installed_Scripts, true);
            $http({
                withCredentials: false,
                method: 'post',
                headers: { 'Content-Type': 'application/json' },
                url: '/api/updatehostscripts/' + $scope.hostname + '/',
                data: $scope.modelAsJson
            }).success(function(data){
                log("Successfully Saved");
            }).error(function(data){
                log(data);
        });

    }

    $scope.init = function(limit){
        log('here in model');
    }

});
mozAUApp.controller('BackupListCtrl', function ($scope, $http, $routeParams) {
    $scope.hostname = $routeParams['hostname'];
    $scope.has_loaded = false;
    $scope.updates = [];
    $scope.debug = false;
    $scope.system = {};
    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }
    function build_update_list(limit){
        if (!limit){
            limit = 10;
        }
        $http.get('/api/updates/' + $scope.hostname + '?limit=' + limit).success(function(data){
            $scope.updates = data.updates;
        });
        $http.get('/api/system/' + $scope.hostname + '/').success(function(data){
            $scope.system = data.system;
        });
        $scope.has_loaded = true;
    }

    $scope.init = function(limit){
        build_update_list(limit);
    }
});
mozAUApp.controller('BackupDetailCtrl', function ($scope, $http, $routeParams, $interval) {
    $scope.id = $routeParams['id'];
    $scope.updates = [];
    $scope.has_loaded = false;

    function build_update_list(limit){
        $http.get('/api/updatedetail/' + $scope.id).success(function(data){
            $scope.updates = data.updates;
            $scope.hostname = data['hostname']
        });
        $scope.has_loaded = true;
    }

    $scope.init = function(limit){
        if(!$scope.timer){
            $scope.timer = $interval(function(){
                build_update_list(1);
            }, 5000);

        }
        build_update_list();
    }

    $scope.$on('$destroy', function() {
        $interval.cancel($scope.timer);
    });

});

<commit_msg>Fix for async script comparisson<commit_after>angular.module('phonecatFilters', []).filter('checkmark', function() {
  return function(input) {
      return input;
  };
});
function AccordionDemoCtrl($scope) {
  $scope.oneAtATime = true;

  $scope.groups = [
    {
      title: 'Dynamic Group Header - 1',
      content: 'Dynamic Group Body - 1'
    },
    {
      title: 'Dynamic Group Header - 2',
      content: 'Dynamic Group Body - 2'
    }
  ];

  $scope.items = ['Item 1', 'Item 2', 'Item 3'];

  $scope.addItem = function() {
    var newItemNo = $scope.items.length + 1;
    $scope.items.push('Item ' + newItemNo);
  };

  $scope.status = {
    isFirstOpen: true,
    isFirstDisabled: false
  };
}
var mozAUApp = angular.module('mozAUApp', ['ngRoute','ui.bootstrap','dndLists']);
mozAUApp.config(function($routeProvider){
    $routeProvider
    // route for the home page
    .when('/', {
        templateUrl : '/static/js/pages/list.html',
        controller  : 'ServerListCtrl'
    })

    .when('/scripts/create/', {
        templateUrl : '/static/js/pages/script_create.html',
        controller  : 'ScriptCreateCtrl'
    })

    .when('/scripts/edit/:id', {
        templateUrl : '/static/js/pages/script_edit.html',
        controller  : 'ScriptEditCtrl'
    })

    // route for the about page
    .when('/detail/:hostname', {
        templateUrl : '/static/js/pages/update_list.html',
        controller  : 'UpdateListCtrl'
    })

    .when('/scripts/:hostname', {
        templateUrl : '/static/js/pages/edit_scripts.html',
        controller  : 'ScriptsCtrl'
    })

    .when('/updatedetail/:id', {
        templateUrl : '/static/js/pages/update_detail.html',
        controller  : 'BackupDetailCtrl'
    })

    .when('/updatecron/:hostname', {
        templateUrl : '/static/js/pages/update_cron.html',
        controller  : 'UpdateCronCtrl'
    })

    // route for the contact page
    .when('/contact', {
        templateUrl : 'pages/contact.html',
        controller  : 'contactController'
    });
});

mozAUApp.directive('delaySearch', function ($timeout) {
        return {
            restrict: 'EA',
            template: ' <input ng-model="search" ng-change="modelChanged()">',
            link: function ($scope, element, attrs) {
                $scope.modelChanged = function () {
                    $timeout(function () {
                        if ($scope.lastSearch != $scope.search) {
                            if ($scope.delayedMethod) {
                                $scope.lastSearch = $scope.search;
                                $scope.delayedMethod({ search: $scope.search });
                            }
                        }
                    }, 300);
                }
            },
            scope: {
                delayedMethod:'&'
            }
        }
    });

mozAUApp.controller('ScriptEditCtrl', function ($scope, $location, $http, $interval, $routeParams) {
    $scope.debug = false;
    $scope.id = $routeParams['id'];
    $scope.file_name = ''
    $scope.description = ''

    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }
    var changeLocation = function(url, forceReload) {
      $scope = $scope || angular.element(document).scope();
      if(forceReload || $scope.$$phase) {
        window.location = url;
      }
      else {
        $location.path(url);
        $scope.$apply();
      }
    };

    $scope.update = function() {
        $scope.alert_id++;
        data = {};
        data['file_name'] = $scope.file_name;
        data['description'] = $scope.description;
        $http({
            withCredentials: false,
            method: 'post',
            headers: { 'Content-Type': 'application/json' },
            url: '/api/scriptedit/' + $scope.id + '/',
            data: JSON.stringify(data)
        }).success(function(data){
            changeLocation('/#/scripts/')
        }).error(function(data){
            log(data);
        });
        log("$scope.filename: " + $scope.file_name);
        log("$scope.description: " + $scope.description);
    }

    $scope.init = function(){
        $http.get('/api/scriptdetail/' + $scope.id + '/').success(function(data){
            $scope.file_name = data.script.file_name;
            $scope.description = data.script.description;
            log($scope.scripts);
        });

    }

});
mozAUApp.controller('ScriptCreateCtrl', function ($scope, $location, $http, $interval) {
    $scope.debug = false;
    $scope.file_name = ''
    $scope.description = ''

    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }
    var changeLocation = function(url, forceReload) {
      $scope = $scope || angular.element(document).scope();
      if(forceReload || $scope.$$phase) {
        window.location = url;
      }
      else {
        $location.path(url);
        $scope.$apply();
      }
    };

    $scope.create = function() {
        $scope.alert_id++;
        data = {};
        data['file_name'] = $scope.file_name;
        data['description'] = $scope.description;
        $http({
            withCredentials: false,
            method: 'post',
            headers: { 'Content-Type': 'application/json' },
            url: '/api/scriptcreate/',
            data: JSON.stringify(data)
        }).success(function(data){
            changeLocation('/#/scripts/')
        }).error(function(data){
            log(data);
        });
        log("$scope.filename: " + $scope.file_name);
        log("$scope.description: " + $scope.description);
    }

    $scope.init = function(){
        log('init called');
    }

});

mozAUApp.controller('ScriptListCtrl', function ($scope, $http, $interval) {
    $scope.debug = false;
    $scope.scripts = [];

    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }

    function scripts(){
        $http.get('/api/scripts/').success(function(data){
            $scope.scripts = data.scripts;
            log($scope.scripts);
        });
    }

    $scope.init = function(){
        log('Calling Init')
        scripts();
    }

});
mozAUApp.controller('ServerListCtrl', function ($scope, $http, $interval) {
    $scope.debug = false;
    $scope.systems = [];
    $scope.recent = [];
    $scope.system = '';

    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }

    function recent_updates(limit){
        $http.get('/api/recentupdateonly/?limit=' + limit).success(function(data){
            $scope.recent = data.updates;
            log($scope.recent);
        });
    }

    $scope.requery = function(search){
        $scope.systems = [];
        if(search){
            $http.get('/api/system/?hostname=' + search).success(function(data){
                $scope.systems = data.systems;
            });
        }
        log("requery called");
    };

    $scope.init = function(limit){
        log("init called");
        if(!$scope.timer){
            $scope.timer = $interval(function(){
                recent_updates(20);
            }, 5000);
        }
        recent_updates(20);
    }

    $scope.$on('$destroy', function() {
      $interval.cancel($scope.timer);
    });

});

mozAUApp.controller('UpdateListCtrl', function ($scope, $http, $routeParams, $interval) {
    $scope.hostname = $routeParams['hostname'];
    $scope.has_loaded = false;
    $scope.updates = [];
    $scope.debug = false;
    $scope.system = {};
    $scope.pings = [];
    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }
    $scope.ping = function(){
        log("Ping Called");
        $http.get('/api/ping/' + $scope.hostname + '/').success(function(data){
            log(data);
        });
    }

    $scope.start_update = function(){
        log("start_update Called");
        $http.get('/api/start_update/' + $scope.hostname + '/').success(function(data){
            log(data);
        });
    }

    function build_update_list(limit){
        if (!limit){
            limit = 10;
        }
        $http.get('/api/updates/' + $scope.hostname + '?limit=' + limit).success(function(data){
            $scope.updates = data.updates;
        });
        $http.get('/api/system/' + $scope.hostname + '/').success(function(data){
            $scope.system = data.system;
            $scope.pings = data.system.pings;
            log($scope.pings);
        });
        $scope.has_loaded = true;
    }
    $scope.init = function(limit){
        log("init called");
        if(!$scope.timer){
            $scope.timer = $interval(function(){
                build_update_list(limit);
            }, 5000);
        }
        build_update_list(limit);
    }

    $scope.$on('$destroy', function() {
      $interval.cancel($scope.timer);
    });

});

mozAUApp.controller('UpdateCronCtrl', function ($scope, $http, $sce, $routeParams) {
    $scope.hostname = $routeParams['hostname'];
    $scope.debug = false;
    $scope.system = {};
    $scope.cronfile = "";
    $scope.show_success = false;
    $scope.success_message = "";
    $scope.alert_id = 1;
    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }
    $scope.updateCronfile = function(){
        $scope.alert_id++;
        data = {};
        data['cronfile'] = $scope.cronfile;
        $http({
            withCredentials: false,
            method: 'post',
            headers: { 'Content-Type': 'application/json' },
            url: '/api/updatecronfile/' + $scope.system.id + '/',
            data: JSON.stringify(data)
        }).success(function(data){
            var alert_text = '
<button type="button" class="close" id="' + $scope.alert_id +' " data-dismiss="alert" aria-hidden="true">×</button>Cronfile Successfully Updated
';
            $scope.success_message = $sce.trustAsHtml(alert_text);
        });
    }

    $scope.init = function(limit){
        $http.get('/api/system/' + $scope.hostname + '/').success(function(data){
            $scope.system = data.system;
            $scope.cronfile = $scope.system.cronfile;
        });
    }
});
mozAUApp.controller('ScriptsCtrl', function ($scope, $http, $routeParams) {
    $scope.debug = false;
    $scope.hostname = $routeParams['hostname'];
    $scope.installed_script_file_names = [];
    $scope.current_installed_scripts = {};
    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }

    $scope.models = {
        selected: null,
        lists: {
            "Installed_Scripts": [],
            "Available_Scripts": []
        }
    };

    // Generate initial model
    $http.get('/api/hostscripts/' + $scope.hostname + '/').success(function(data){
        for (f=0;f<data.scripts.length;f++){
            $scope.models.lists.Installed_Scripts.push({
                label: data.scripts[f].file_name,
                id: data.scripts[f].id
            });
            $scope.installed_script_file_names.push(data.scripts[f].file_name)
        }
        $scope.current_installed_scripts = $scope.models.lists.Installed_Scripts;
        $http.get('/api/scripts/').success(function(data){
            for (f=0;f<data.scripts.length;f++){
                if ($scope.installed_script_file_names.indexOf(data.scripts[f].file_name) == -1){
                    $scope.models.lists.Available_Scripts.push({
                        label: data.scripts[f].file_name,
                        id: data.scripts[f].id
                    });
                }
            }
        });
    });

    // Model to JSON for demo purpose
    $scope.save = function(){
        $scope.modelAsJson = angular.toJson($scope.models.lists.Installed_Scripts, true);
            $http({
                withCredentials: false,
                method: 'post',
                headers: { 'Content-Type': 'application/json' },
                url: '/api/updatehostscripts/' + $scope.hostname + '/',
                data: $scope.modelAsJson
            }).success(function(data){
                log("Successfully Saved");
            }).error(function(data){
                log(data);
        });

    }

    $scope.init = function(limit){
        log('here in model');
    }

});
mozAUApp.controller('BackupListCtrl', function ($scope, $http, $routeParams) {
    $scope.hostname = $routeParams['hostname'];
    $scope.has_loaded = false;
    $scope.updates = [];
    $scope.debug = false;
    $scope.system = {};
    function log(message){
        if($scope.debug && console){
            console.log(message);
        }
    }
    function build_update_list(limit){
        if (!limit){
            limit = 10;
        }
        $http.get('/api/updates/' + $scope.hostname + '?limit=' + limit).success(function(data){
            $scope.updates = data.updates;
        });
        $http.get('/api/system/' + $scope.hostname + '/').success(function(data){
            $scope.system = data.system;
        });
        $scope.has_loaded = true;
    }

    $scope.init = function(limit){
        build_update_list(limit);
    }
});
mozAUApp.controller('BackupDetailCtrl', function ($scope, $http, $routeParams, $interval) {
    $scope.id = $routeParams['id'];
    $scope.updates = [];
    $scope.has_loaded = false;

    function build_update_list(limit){
        $http.get('/api/updatedetail/' + $scope.id).success(function(data){
            $scope.updates = data.updates;
            $scope.hostname = data['hostname']
        });
        $scope.has_loaded = true;
    }

    $scope.init = function(limit){
        if(!$scope.timer){
            $scope.timer = $interval(function(){
                build_update_list(1);
            }, 5000);

        }
        build_update_list();
    }

    $scope.$on('$destroy', function() {
        $interval.cancel($scope.timer);
    });

});

<|endoftext|>