<commit_before>'use strict';

angular.module('myModule', ['angular.filter','esri.map'])
    .controller('myController', function($scope, esriLoader, $filter, $http, $window) {

      var map2;
      $scope.mapFlag = 0;

      //get the data from neighborhood spreadsheet
      $http({
            method: 'GET',
            url: 'http://localhost:3000/GS-Neighborhood'
      }).then(function (response){
            $scope.neighborhood = response.data.data;
      });

      //get the data from region spreadsheet
      $http({
            method: 'GET',
            url: 'http://localhost:3000/GS-Region'
      }).then(function (response){
            $scope.regionData = response.data.data;
      });

      //function to move to next slide and set region selected
      $scope.neighborhoods = function(reg){
            $('#mapCarousel').carousel('next');
            $scope.regionpick = reg.region;
            $scope.regionMap();
      }

      //function to set the neigborhood in sessionStorage and go to the specific neighborhood page
      $scope.neighborhoodmap = function(dataset){
            $scope.mapdata = dataset;

            sessionStorage.nhood =  JSON.stringify($scope.mapdata);
            sessionStorage.variable = JSON.stringify("Median Household Income");
            sessionStorage.varUrl = JSON.stringify("http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/Income_MedianHouseholdIncome_2015_NDSC/FeatureServer/0");
      };

      //draw the neighborhoods map on selecting region
      $scope.regionMap = function() {

                  esriLoader.require([
                    "esri/map",
      "esri/geometry/Extent",
      "esri/layers/FeatureLayer",
      "esri/symbols/SimpleLineSymbol",
      "esri/symbols/SimpleFillSymbol",
      "esri/symbols/TextSymbol",
      "esri/renderers/SimpleRenderer",
      "esri/layers/LabelClass",
      "dojo/_base/Color",
      "esri/graphic",
      "esri/lang",
      "esri/tasks/QueryTask",
      "esri/tasks/query",
      "dojo/domReady!"
      ], function(Map, Extent, FeatureLayer, SimpleLineSymbol, SimpleFillSymbol,
      TextSymbol, SimpleRenderer, LabelClass, Color, Graphic, esriLang, QueryTask, Query) {

      if($scope.mapFlag == 1){
        map2.destroy();
      }

      $scope.mapFlag = 1;
      var url = "http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Neighborhoods_LAT_2017_NDSC/FeatureServer/0";
      var url2 = "http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Regions_LAT_2017_NDSC/FeatureServer/0";
      var info = new esri.InfoTemplate();
      info.setTitle("Neighborhood");
      info.setContent("${name}");

      var mapLayer = new FeatureLayer(url, {
                      id: "regionMap",
                      outFields: ["*"],
                      infoTemplate: info
                      });

    var regionMapLayer = new FeatureLayer(url2, {
                      id: "regionMapLayer",
                      outFields: ["*"],
                      });

    map2 = new Map("map2", {
                    basemap: "gray",
                    center: [-118.2437, 34.2522],
                    zoom: 9,
                    showLabels : true,
                    layers: regionMapLayer
                    });

    // var labelField = "name";
    //
    // var nColor = new Color("#191165");
    // var nLine = new SimpleLineSymbol("solid", nColor, 1.5);
    // var nSymbol = new SimpleFillSymbol("solid", nLine, null);
    // var nRenderer = new SimpleRenderer(nSymbol);
    //
    // var neighborhoodLabel = new TextSymbol().setColor(nColor);
    // neighborhoodLabel.font.setSize("9pt");
    // neighborhoodLabel.font.setFamily("arial");
    //
    // var json = {"labelExpressionInfo": {"value": "{name}"}
    //             };
    //
    // var labelClass = new LabelClass(json);
    // labelClass.symbol = neighborhoodLabel;
    // //mapLayer.setLabelingInfo([ labelClass ]);

    var symbol2 = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,new Color([0,0,0]),2);

    //regionMapLayer.setRenderer(new SimpleRenderer(symbol2));

    var symbol = new SimpleFillSymbol( SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                          new Color([0,112,255,255]),
                          2),new Color([173,216,230]));

    mapLayer.setRenderer(new SimpleRenderer(symbol));
    map2.removeLayer("https://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer");
    map2.addLayer(mapLayer);
    //map2.addLayer(regionMapLayer);

    var regionObject = $filter('filter')($scope.regionData, { region : $scope.regionpick});
    var startExtent = new Extent();
    startExtent.xmin = regionObject[0].minpointx;
    startExtent.ymin = regionObject[0].minpointy;
    startExtent.xmax = regionObject[0].maxpointx;
    startExtent.ymax = regionObject[0].maxpointy;
    map2.setExtent(startExtent);

    //set highlight symbol
    // var highlightSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(
    //                     SimpleLineSymbol.STYLE_SOLID,new Color("#191165"), 1),new Color([ 0, 197, 255]));

    var highlightSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(
                                          SimpleLineSymbol.STYLE_SOLID,new Color([0, 197, 255, 0.35]), 1),new Color([ 0, 197, 255, 0.35]));

    map2.on("load", function(){
              map2.graphics.enableMouseEvents();

              var queryTask = new esri.tasks.QueryTask("http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Regions_LAT_2017_NDSC/FeatureServer/0");
              var query = new esri.tasks.Query();
              query.returnGeometry = true;
              query.where = "Name = '" + $scope.regionpick + "'";

              queryTask.execute(query, function(result){

              console.log(result.features[0]);

              //map2.graphics.clear();
              for (var i=0, il=result.features.length; i<il; i++) {

                var graphic = result.features[i];

                graphic.setSymbol(highlightSymbol);
              // var highlightGraphic = new Graphic(graphic.geometry,highlightSymbol);
              //console.log(highlightGraphic);

              map2.graphics.add(graphic);
              }

              // $scope.regionGraphic = result.features[0];
              // console.log($scope.regionGraphic.geometry);
              // var highlightGraphic = new Graphic($scope.regionGraphic.geometry,highlightSymbol);
              // map2.graphics.add(highlightGraphic);

             });

            var highlightSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(
                                                  SimpleLineSymbol.STYLE_SOLID,new Color("#191165"), 1),new Color([ 0, 197, 255, 0.35]));

            console.log($scope.regionGraphic.geometry);
            var highlightGraphic = new Graphic($scope.regionGraphic.geometry,highlightSymbol);
            map2.graphics.add(highlightGraphic);

            map2.graphics.on("mouse-out", function() {
          map2.graphics.clear();
          //map2.graphics.remove(map.graphics.graphics[map.graphics.graphics.length - 1]);
          map2.infoWindow.hide();
        });

mapLayer.on("mouse-over", function(evt){
                  var t = "${name}";
                  var content = esriLang.substitute(evt.graphic.attributes,t);
                  var highlightGraphic = new Graphic(evt.graphic.geometry,highlightSymbol);
                  //alert(evt);
                  map2.graphics.add(highlightGraphic);
                  map2.infoWindow.setContent(content);
                  map2.infoWindow.setTitle("Neighborhood");
                  map2.infoWindow.show(evt.screenPoint,map2.getInfoWindowAnchor(evt.screenPoint));
                });

        });//end of on load function

		var queryTask = new esri.tasks.QueryTask("http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Neighborhoods_LAT_2017_NDSC/FeatureServer/0");
        var query = new esri.tasks.Query();
        query.returnGeometry = true;
        query.outFields = ["name"];

        map2.on("click", function(evt){
            //console.log(evt.graphic);
            $scope.regionGraphic = evt.graphic;
            query.geometry = evt.mapPoint;
            //console.log(evt.mapPoint);
            queryTask.execute(query, function(result){
            $scope.regionpick = result.features[0].attributes.name;
            $scope.neighborhoodmap($scope.regionpick);

            window.location.href = 'neighborhoodmap.html';

          })
        });

    // map2.graphics.on("mouse-out", function() {
    //           map2.graphics.clear();
    //           map2.infoWindow.hide();
    //         });

    // mapLayer.on("mouse-over", function(evt){
    //                   var t = "${name}";
    //                   var content = esriLang.substitute(evt.graphic.attributes,t);
    //                   var highlightGraphic = new Graphic(evt.graphic.geometry,highlightSymbol);
    //
    //                   map2.graphics.add(highlightGraphic);
    //                   map2.infoWindow.setContent(content);
    //                   map2.infoWindow.setTitle("Neighborhood");
    //                   map2.infoWindow.show(evt.screenPoint,map2.getInfoWindowAnchor(evt.screenPoint));
    //                 });

                    // var highlightSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(
                    //                                     SimpleLineSymbol.STYLE_SOLID,new Color("#191165"), 1),new Color([ 0, 197, 255]));
                    //
                    //     //var content = esriLang.substitute(evt.graphic.attributes,t);
                    //     alert($scope.regionGraphic);
                    //     var highlightGraphic = new Graphic($scope.regionGraphic.geometry,highlightSymbol);
                    //
                    //     map2.graphics.add(highlightGraphic);

                });

              }

//draw the first region map
$scope.onMapLoad = function(map) {

esriLoader.require([
              "esri/map",
"esri/geometry/Extent",
"esri/layers/FeatureLayer",
"esri/symbols/SimpleLineSymbol",
"esri/symbols/SimpleFillSymbol",
"esri/symbols/TextSymbol",
"esri/renderers/SimpleRenderer",
"esri/layers/LabelClass",
"dojo/_base/Color",
"esri/graphic",
"esri/lang",
"esri/tasks/QueryTask",
  "esri/tasks/query",
"dojo/domReady!"
], function(Map, Extent, FeatureLayer, SimpleLineSymbol, SimpleFillSymbol,
TextSymbol, SimpleRenderer, LabelClass, Color, Graphic, esriLang, QueryTask, Query) {

//Setting labels for map
var labelField = "Name";
var statesColor = new Color("#191165");
var statesLine = new SimpleLineSymbol("solid", statesColor, 1.5);
var statesSymbol = new SimpleFillSymbol("solid", statesLine, null);
var statesRenderer = new SimpleRenderer(statesSymbol);

var statesUrl = "http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Regions_LAT_2017_NDSC/FeatureServer/0";

var info = new esri.InfoTemplate();
info.setTitle("Region");
info.setContent("${Name}");

var states = new FeatureLayer(statesUrl, {
id: "states",
outFields: ["*"],
infoTemplate: info,
});
var statesLabel = new TextSymbol().setColor(statesColor);
statesLabel.font.setSize("9pt");
statesLabel.font.setFamily("arial");
var json = {
  "labelExpressionInfo": {"value": "{Name}"}
};

var labelClass = new LabelClass(json);
labelClass.symbol = statesLabel;

var symbol = new SimpleFillSymbol(
    SimpleFillSymbol.STYLE_SOLID,
    new SimpleLineSymbol(
      SimpleLineSymbol.STYLE_SOLID,
      new Color([0,112,255,255]),
      2), new Color([173,216,230]));

states.setRenderer(new SimpleRenderer(symbol));

map.removeLayer("https://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer/0");
map.addLayer(states);

//create highlight symbol for hover
var highlightSymbol = new SimpleFillSymbol(
  SimpleFillSymbol.STYLE_SOLID,
  new SimpleLineSymbol(
    SimpleLineSymbol.STYLE_SOLID,
    new Color("#191165"), 1
  ), new Color([ 0, 197, 255]));

map.on("load", function(){
  map.graphics.enableMouseEvents();
});

map.graphics.on("mouse-out", function() {
map.graphics.clear();
map.infoWindow.hide();
});

states.on("mouse-over", function(evt){
  var t = "${Name}";
  var content = esriLang.substitute(evt.graphic.attributes,t);
  var highlightGraphic = new Graphic(evt.graphic.geometry,highlightSymbol);
  map.graphics.add(highlightGraphic);
  map.infoWindow.setContent(content);
  map.infoWindow.setTitle("Region");
  map.infoWindow.show(evt.screenPoint,map.getInfoWindowAnchor(evt.screenPoint));
});

//get region selected on click
var queryTask = new esri.tasks.QueryTask("http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Regions_LAT_2017_NDSC/FeatureServer/0");
var query = new esri.tasks.Query();
query.returnGeometry = true;
query.outFields = ["name"];

map.on("click", function(evt){
    //console.log(evt.graphic);
    $scope.regionGraphic = evt.graphic;
    query.geometry = evt.mapPoint;
    //console.log(evt.mapPoint);
    queryTask.execute(query, function(result){
    $scope.regionpick = result.features[0].attributes.Name;
    $('#mapCarousel').carousel('next');
    $scope.regionMap();
  })
});

    }); //esriLoader ends

  }; //onMapLoad ends

});//angular controller ends
<commit_msg>search by street address<commit_after>'use strict';

angular.module('myModule', ['angular.filter','esri.map'])
    .controller('myController', function($scope, esriLoader, $filter, $http, $window) {

      var map2;
      $scope.mapFlag = 0;

      //get the data from neighborhood spreadsheet
      $http({
            method: 'GET',
            url: 'http://localhost:3000/GS-Neighborhood'
      }).then(function (response){
            $scope.neighborhood = response.data.data;
      });

      //get the data from region spreadsheet
      $http({
            method: 'GET',
            url: 'http://localhost:3000/GS-Region'
      }).then(function (response){
            $scope.regionData = response.data.data;
      });

      //function to move to next slide and set region selected
      $scope.neighborhoods = function(reg){
            $('#mapCarousel').carousel('next');
            $scope.regionpick = reg.region;
            $scope.regionMap();
      }

      //function to set the neigborhood in sessionStorage and go to the specific neighborhood page
      $scope.neighborhoodmap = function(dataset){
            $scope.mapdata = dataset;

            sessionStorage.nhood =  JSON.stringify($scope.mapdata);
            sessionStorage.variable = JSON.stringify("Median Household Income");
            sessionStorage.varUrl = JSON.stringify("http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/Income_MedianHouseholdIncome_2015_NDSC/FeatureServer/0");
      };

      //draw the neighborhoods map on selecting region
      $scope.regionMap = function() {

                  esriLoader.require([
                    "esri/map",
      "esri/geometry/Extent",
      "esri/layers/FeatureLayer",
      "esri/symbols/SimpleLineSymbol",
      "esri/symbols/SimpleFillSymbol",
      "esri/symbols/TextSymbol",
      "esri/renderers/SimpleRenderer",
      "esri/layers/LabelClass",
      "dojo/_base/Color",
      "esri/graphic",
      "esri/lang",
      "esri/tasks/QueryTask",
      "esri/tasks/query",
      "esri/dijit/Search",
      "esri/symbols/PictureMarkerSymbol",
      "esri/tasks/locator",
      "dojo/domReady!"

      ], function(Map, Extent, FeatureLayer, SimpleLineSymbol, SimpleFillSymbol,
      TextSymbol, SimpleRenderer, LabelClass, Color, Graphic, esriLang, QueryTask, Query,Search,PictureMarkerSymbol,Locator) {

      if($scope.mapFlag == 1){
        map2.destroy();
      }

      $scope.mapFlag = 1;
      var url = "http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Neighborhoods_LAT_2017_NDSC/FeatureServer/0";
      var url2 = "http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Regions_LAT_2017_NDSC/FeatureServer/0";
      var info = new esri.InfoTemplate();
      info.setTitle("Neighborhood");
      info.setContent("${name}");

      var mapLayer = new FeatureLayer(url, {
                      id: "regionMap",
                      outFields: ["*"],
                      infoTemplate: info
                      });

    var regionMapLayer = new FeatureLayer(url2, {
                      id: "regionMapLayer",
                      outFields: ["*"],
                      });

    map2 = new Map("map2", {
                    basemap: "gray",
                    center: [-118.2437, 34.2522],
                    zoom: 9,
                    showLabels : true,
                    layers: regionMapLayer
                    });

    var searchNeighborHoodName = new Search({

            sources: [
            {
                featureLayer: mapLayer,
                outFields:["name"],
                displayField: "name",
                suggestionTemplate: "${name}",
                name: "Search",
                placeholder: "Search NeighborHood Name",
                enableSuggestions: true

            }
          ],
            map: map2,

         }, "searchNeighborHoodName");

searchNeighborHoodName.startup();

var searchStreetAddress2 = new Search({

            sources: [
            {

                locator: new   Locator("//geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"),
                singleLineFieldName: "SingleLine",
                outFields: ["Addr_type"],
                name: "Search",
                localSearchOptions: {
                    minScale: 300000,
                    distance: 50000
                },
                placeholder: "Search Street Address",
                highlightSymbol: new PictureMarkerSymbol("img/search-pointer.png", 36, 36).setOffset(9, 18)

            }
          ],
            map: map2,
            zoomScale: 5000000000
         }, "searchStreetAddress2");

searchStreetAddress2.startup();

    // var labelField = "name";
    //
    // var nColor = new Color("#191165");
    // var nLine = new SimpleLineSymbol("solid", nColor, 1.5);
    // var nSymbol = new SimpleFillSymbol("solid", nLine, null);
    // var nRenderer = new SimpleRenderer(nSymbol);
    //
    // var neighborhoodLabel = new TextSymbol().setColor(nColor);
    // neighborhoodLabel.font.setSize("9pt");
    // neighborhoodLabel.font.setFamily("arial");
    //
    // var json = {"labelExpressionInfo": {"value": "{name}"}
    //             };
    //
    // var labelClass = new LabelClass(json);
    // labelClass.symbol = neighborhoodLabel;
    // //mapLayer.setLabelingInfo([ labelClass ]);

    var symbol2 = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,new Color([0,0,0]),2);

    //regionMapLayer.setRenderer(new SimpleRenderer(symbol2));

    var symbol = new SimpleFillSymbol( SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                          new Color([0,112,255,255]),
                          2),new Color([173,216,230]));

    mapLayer.setRenderer(new SimpleRenderer(symbol));
    map2.removeLayer("https://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer");
    map2.addLayer(mapLayer);
    //map2.addLayer(regionMapLayer);

    var regionObject = $filter('filter')($scope.regionData, { region : $scope.regionpick});
    var startExtent = new Extent();
    startExtent.xmin = regionObject[0].minpointx;
    startExtent.ymin = regionObject[0].minpointy;
    startExtent.xmax = regionObject[0].maxpointx;
    startExtent.ymax = regionObject[0].maxpointy;
    map2.setExtent(startExtent);

    //set highlight symbol
    // var highlightSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(
    //                     SimpleLineSymbol.STYLE_SOLID,new Color("#191165"), 1),new Color([ 0, 197, 255]));

    var highlightSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(
                                          SimpleLineSymbol.STYLE_SOLID,new Color([0, 197, 255, 0.35]), 1),new Color([ 0, 197, 255, 0.35]));

    map2.on("load", function(){
              map2.graphics.enableMouseEvents();

              var queryTask = new esri.tasks.QueryTask("http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Regions_LAT_2017_NDSC/FeatureServer/0");
              var query = new esri.tasks.Query();
              query.returnGeometry = true;
              query.where = "Name = '" + $scope.regionpick + "'";

              queryTask.execute(query, function(result){

              console.log(result.features[0]);

              //map2.graphics.clear();
              for (var i=0, il=result.features.length; i<il; i++) {

                var graphic = result.features[i];

                graphic.setSymbol(highlightSymbol);
              // var highlightGraphic = new Graphic(graphic.geometry,highlightSymbol);
              //console.log(highlightGraphic);

              map2.graphics.add(graphic);
              }

              // $scope.regionGraphic = result.features[0];
              // console.log($scope.regionGraphic.geometry);
              // var highlightGraphic = new Graphic($scope.regionGraphic.geometry,highlightSymbol);
              // map2.graphics.add(highlightGraphic);

             });

            var highlightSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(
                                                  SimpleLineSymbol.STYLE_SOLID,new Color("#191165"), 1),new Color([ 0, 197, 255, 0.35]));

            console.log($scope.regionGraphic.geometry);
            var highlightGraphic = new Graphic($scope.regionGraphic.geometry,highlightSymbol);
            map2.graphics.add(highlightGraphic);

            map2.graphics.on("mouse-out", function() {
          map2.graphics.clear();
          //map2.graphics.remove(map.graphics.graphics[map.graphics.graphics.length - 1]);
          map2.infoWindow.hide();
        });

mapLayer.on("mouse-over", function(evt){
                  var t = "${name}";
                  var content = esriLang.substitute(evt.graphic.attributes,t);
                  var highlightGraphic = new Graphic(evt.graphic.geometry,highlightSymbol);
                  //alert(evt);
                  map2.graphics.add(highlightGraphic);
                  map2.infoWindow.setContent(content);
                  map2.infoWindow.setTitle("Neighborhood");
                  map2.infoWindow.show(evt.screenPoint,map2.getInfoWindowAnchor(evt.screenPoint));
                });

        });//end of on load function

		var queryTask = new esri.tasks.QueryTask("http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Neighborhoods_LAT_2017_NDSC/FeatureServer/0");
        var query = new esri.tasks.Query();
        query.returnGeometry = true;
        query.outFields = ["name"];

        map2.on("click", function(evt){
            //console.log(evt.graphic);
            $scope.regionGraphic = evt.graphic;
            query.geometry = evt.mapPoint;
            //console.log(evt.mapPoint);
            queryTask.execute(query, function(result){
            $scope.regionpick = result.features[0].attributes.name;
            $scope.neighborhoodmap($scope.regionpick);

            window.location.href = 'neighborhoodmap.html';

          })
        });

    // map2.graphics.on("mouse-out", function() {
    //           map2.graphics.clear();
    //           map2.infoWindow.hide();
    //         });

    // mapLayer.on("mouse-over", function(evt){
    //                   var t = "${name}";
    //                   var content = esriLang.substitute(evt.graphic.attributes,t);
    //                   var highlightGraphic = new Graphic(evt.graphic.geometry,highlightSymbol);
    //
    //                   map2.graphics.add(highlightGraphic);
    //                   map2.infoWindow.setContent(content);
    //                   map2.infoWindow.setTitle("Neighborhood");
    //                   map2.infoWindow.show(evt.screenPoint,map2.getInfoWindowAnchor(evt.screenPoint));
    //                 });

                    // var highlightSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(
                    //                                     SimpleLineSymbol.STYLE_SOLID,new Color("#191165"), 1),new Color([ 0, 197, 255]));
                    //
                    //     //var content = esriLang.substitute(evt.graphic.attributes,t);
                    //     alert($scope.regionGraphic);
                    //     var highlightGraphic = new Graphic($scope.regionGraphic.geometry,highlightSymbol);
                    //
                    //     map2.graphics.add(highlightGraphic);

                });

              }

//draw the first region map
$scope.onMapLoad = function(map) {

esriLoader.require([
              "esri/map",
"esri/geometry/Extent",
"esri/layers/FeatureLayer",
"esri/symbols/SimpleLineSymbol",
"esri/symbols/SimpleFillSymbol",
"esri/symbols/TextSymbol",
"esri/renderers/SimpleRenderer",
"esri/layers/LabelClass",
"dojo/_base/Color",
"esri/graphic",
"esri/lang",
"esri/tasks/QueryTask",
"esri/tasks/query",
"esri/dijit/Search",
"esri/symbols/PictureMarkerSymbol",
"esri/tasks/locator",
"dojo/domReady!"

], function(Map, Extent, FeatureLayer, SimpleLineSymbol, SimpleFillSymbol,
TextSymbol, SimpleRenderer, LabelClass, Color, Graphic, esriLang, QueryTask, Query,Search,PictureMarkerSymbol,Locator) {

//Setting labels for map
var labelField = "Name";
var statesColor = new Color("#191165");
var statesLine = new SimpleLineSymbol("solid", statesColor, 1.5);
var statesSymbol = new SimpleFillSymbol("solid", statesLine, null);
var statesRenderer = new SimpleRenderer(statesSymbol);

var statesUrl = "http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Regions_LAT_2017_NDSC/FeatureServer/0";

var info = new esri.InfoTemplate();
info.setTitle("Region");
info.setContent("${Name}");

var states = new FeatureLayer(statesUrl, {
id: "states",
outFields: ["*"],
infoTemplate: info,
});
var statesLabel = new TextSymbol().setColor(statesColor);
statesLabel.font.setSize("9pt");
statesLabel.font.setFamily("arial");
var json = {
  "labelExpressionInfo": {"value": "{Name}"}
};

var labelClass = new LabelClass(json);
labelClass.symbol = statesLabel;

var symbol = new SimpleFillSymbol(
    SimpleFillSymbol.STYLE_SOLID,
    new SimpleLineSymbol(
      SimpleLineSymbol.STYLE_SOLID,
      new Color([0,112,255,255]),
      2), new Color([173,216,230]));

states.setRenderer(new SimpleRenderer(symbol));

map.removeLayer("https://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer/0");
map.addLayer(states);

//create highlight symbol for hover
var highlightSymbol = new SimpleFillSymbol(
  SimpleFillSymbol.STYLE_SOLID,
  new SimpleLineSymbol(
    SimpleLineSymbol.STYLE_SOLID,
    new Color("#191165"), 1
  ), new Color([ 0, 197, 255]));

map.on("load", function(){
  map.graphics.enableMouseEvents();
});

map.graphics.on("mouse-out", function() {
map.graphics.clear();
map.infoWindow.hide();
});

states.on("mouse-over", function(evt){
  var t = "${Name}";
  var content = esriLang.substitute(evt.graphic.attributes,t);
  var highlightGraphic = new Graphic(evt.graphic.geometry,highlightSymbol);
  map.graphics.add(highlightGraphic);
  map.infoWindow.setContent(content);
  map.infoWindow.setTitle("Region");
  map.infoWindow.show(evt.screenPoint,map.getInfoWindowAnchor(evt.screenPoint));
});

//get region selected on click
var queryTask = new esri.tasks.QueryTask("http://services1.arcgis.com/ZIL9uO234SBBPGL7/arcgis/rest/services/LA_County_Regions_LAT_2017_NDSC/FeatureServer/0");
var query = new esri.tasks.Query();
query.returnGeometry = true;
query.outFields = ["name"];

map.on("click", function(evt){
    //console.log(evt.graphic);
    $scope.regionGraphic = evt.graphic;
    query.geometry = evt.mapPoint;
    //console.log(evt.mapPoint);
    queryTask.execute(query, function(result){
    $scope.regionpick = result.features[0].attributes.Name;
    $('#mapCarousel').carousel('next');
    $scope.regionMap();
  })
});

var searchRegionName = new Search({

            sources: [
            {
                featureLayer:states,
                outFields:["Name"],
                displayField: "Name",
                suggestionTemplate: "${Name}",
                name: "Search",
                placeholder: "Search Region Name",
                enableSuggestions: true

            }
          ],

            map: map

         }, "searchRegionName");

searchRegionName.startup();

var searchStreetAddress1 = new Search({

            sources: [
            {

                locator: new   Locator("//geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"),
                singleLineFieldName: "SingleLine",
                outFields: ["Addr_type"],
                name: "Search",
                localSearchOptions: {
                    minScale: 300000,
                    distance: 50000
                },
                placeholder: "Search Street Address",
                highlightSymbol: new PictureMarkerSymbol("img/search-pointer.png", 36, 36).setOffset(9, 18)

            }
          ],
            map: map,
            zoomScale: 5000000000
         }, "searchStreetAddress1");

searchStreetAddress1.startup();

    }); //esriLoader ends

  }; //onMapLoad ends

});//angular controller ends
<|endoftext|>


<commit_before>/**
 * @file XML XPath Deep search operator
 * @since 1.0.1
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_START*/ // 0
/*global _gpfDefine*/
/*global _gpfXmlXpathConcatNodes*/
/*global _GpfXmlXPathSub*/ // gpf.xml.xpath.Sub
/*exported _GpfXmlXPathDeep*/ // gpf.xml.xpath.Deep
/*#endif*/

/**
 * Implementation of the // operator
 *
 * @class gpf.xml.xpath.Deep
 * @extend gpf.xml.xpath.Sub
 * @since 1.0.1
 */
var _GpfXmlXPathDeep = _gpfDefine({
    $class: "gpf.xml.xpath.Deep",
    $extend: _GpfXmlXPathSub,

    _getOperator: function () {
        var me = this,
            innerOperator = me.$super(),
            recursiveOperator = {
                execute: function (contextNode, namespaces) {
                    return _gpfXmlXpathConcatNodes(
                        innerOperator.execute(contextNode, namespaces),
                        me._lookup(recursiveOperator, contextNode, namespaces)
                    );
                }
            };
        return recursiveOperator;
    },

    toRelativeString: function () {
        return "//" + this._children[_GPF_START].toString();
    }
});
<commit_msg>Documentation (#326)<commit_after>/**
 * @file XML XPath Deep search operator
 * @since 1.0.1
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_START*/ // 0
/*global _GpfXmlXPathSub*/ // gpf.xml.xpath.Sub
/*global _gpfDefine*/ // Shortcut for gpf.define
/*global _gpfXmlXpathConcatNodes*/ // Returns a list of unique nodes
/*exported _GpfXmlXPathDeep*/ // gpf.xml.xpath.Deep
/*#endif*/

/**
 * Implementation of the // operator
 *
 * @class gpf.xml.xpath.Deep
 * @extend gpf.xml.xpath.Sub
 * @since 1.0.1
 */
var _GpfXmlXPathDeep = _gpfDefine({
    $class: "gpf.xml.xpath.Deep",
    $extend: _GpfXmlXPathSub,

    _getOperator: function () {
        var me = this,
            innerOperator = me.$super(),
            recursiveOperator = {
                execute: function (contextNode, namespaces) {
                    return _gpfXmlXpathConcatNodes(
                        innerOperator.execute(contextNode, namespaces),
                        me._lookup(recursiveOperator, contextNode, namespaces)
                    );
                }
            };
        return recursiveOperator;
    },

    toRelativeString: function () {
        return "//" + this._children[_GPF_START].toString();
    }
});
<|endoftext|>


<commit_before>var db = require('./db'),
    async = require('async');

function nocallback() {
};

var self = module.exports = {
    all: function (callback) {
        if (!callback) {
            callback = nocallback;
        }

        db.get('_all_docs', {'include_docs': true}, function (err, data) {
            if (err) {
                return callback(err, null);
            }

            var rows = [];

            async.eachSeries(data.rows, function (prime, cb) {

                if (prime.doc._id === 'types') {
                    return  cb();
                }

                delete prime.doc._id;
                delete prime.doc._rev;
                rows.push(prime.doc);
                cb();
            }, function (err) {
                if (err) {
                    return callback(err, null);
                }
                return callback(null, rows);
            });
        });
    },
    fetch: function (id, callback) {
        if (!callback) {
            callback = nocallback;
        }

        self.fetchWithDbParams(id, function (err, body) {
            if (err) {
                return callback(err, null);
            }

            // delete couchdb params
            delete body._id;
            delete body._rev;

            return callback(null, body);
        });
    },
    fetchWithDbParams: function (id, callback) {
        if (!callback) {
            callback = nocallback;
        }

        db.get(id, callback);
    },
    add: function (event, callback) {
        if (!callback) {
            callback = nocallback;
        }

        db.insert(event, event.uuid, function (err, body) {
            if (err) {
                return callback(err, null);
            }

            if (event.uuid != body.id) {
                event._id = body.id;
                event._rev = body.rev;
                event.uuid = body.id;

                return self.add(event, callback);
            }

            return callback(null, {"uuid": body.id});
        });
    },
    update: function (event, callback) {
        if (!callback) {
            callback = nocallback;
        }

        self.fetchWithDbParams(event.uuid, function (fetchErr, fetchData) {
            if (fetchErr) {
                return callback(fetchErr, null);
            }

            event._id = fetchData._id
            event._rev = fetchData._rev;

            self.add(event, callback);
        });
    },
    delete: function (id, callback) {
        if (!callback) {
            callback = nocallback;
        }

        self.fetchWithDbParams(id, function (err, data) {
            if (err) {
                return callback(err, null);
            }

            return db.destroy(data._id, data._rev, function (deleteErr, deleteData) {
                if (deleteErr) {
                    return callback(deleteErr, null);
                }

                return callback(null, {"uuid": deleteData.id});
            });
        });
    }
};<commit_msg>Ajout du timestamp<commit_after>var db = require('./db'),
    async = require('async');

function nocallback() {
};

var self = module.exports = {
    all: function (callback) {
        if (!callback) {
            callback = nocallback;
        }

        db.get('_all_docs', {'include_docs': true}, function (err, data) {
            if (err) {
                return callback(err, null);
            }

            var rows = [];

            async.eachSeries(data.rows, function (prime, cb) {

                if (prime.doc._id === 'types') {
                    return cb();
                }

                delete prime.doc._id;
                delete prime.doc._rev;
                rows.push(prime.doc);
                cb();
            }, function (err) {
                if (err) {
                    return callback(err, null);
                }
                return callback(null, rows);
            });
        });
    },
    fetch: function (id, callback) {
        if (!callback) {
            callback = nocallback;
        }

        self.fetchWithDbParams(id, function (err, body) {
            if (err) {
                return callback(err, null);
            }

            // delete couchdb params
            delete body._id;
            delete body._rev;

            return callback(null, body);
        });
    },
    fetchWithDbParams: function (id, callback) {
        if (!callback) {
            callback = nocallback;
        }

        db.get(id, callback);
    },
    add: function (event, callback) {
        if (!callback) {
            callback = nocallback;
        }

        if (!event.timestamp) {
            event.timestamp = Math.floor(Date.now() / 1000);
        }

        db.insert(event, event.uuid, function (err, body) {
            if (err) {
                return callback(err, null);
            }

            if (event.uuid != body.id) {
                event._id = body.id;
                event._rev = body.rev;
                event.uuid = body.id;

                return self.add(event, callback);
            }

            return callback(null, {"uuid": body.id});
        });
    },
    update: function (event, callback) {
        if (!callback) {
            callback = nocallback;
        }

        self.fetchWithDbParams(event.uuid, function (fetchErr, fetchData) {
            if (fetchErr) {
                return callback(fetchErr, null);
            }

            event._id = fetchData._id
            event._rev = fetchData._rev;

            self.add(event, callback);
        });
    },
    delete: function (id, callback) {
        if (!callback) {
            callback = nocallback;
        }

        self.fetchWithDbParams(id, function (err, data) {
            if (err) {
                return callback(err, null);
            }

            return db.destroy(data._id, data._rev, function (deleteErr, deleteData) {
                if (deleteErr) {
                    return callback(deleteErr, null);
                }

                return callback(null, {"uuid": deleteData.id});
            });
        });
    }
};<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 * IO type for Node
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var NodeProperty = require( 'SCENERY/util/NodeProperty' );
  var NumberProperty = require( 'AXON/NumberProperty' );
  var PropertyIO = require( 'AXON/PropertyIO' );
  var scenery = require( 'SCENERY/scenery' );

  // ifphetio
  var assertInstanceOf = require( 'ifphetio!PHET_IO/assertInstanceOf' );
  var BooleanIO = require( 'ifphetio!PHET_IO/types/BooleanIO' );
  var NullableIO = require( 'ifphetio!PHET_IO/types/NullableIO' );
  var ObjectIO = require( 'ifphetio!PHET_IO/types/ObjectIO' );
  var phetioInherit = require( 'ifphetio!PHET_IO/phetioInherit' );

  /**
   * IO type for phet/scenery's Node
   * @param {Node} node
   * @param {string} phetioID
   * @constructor
   */
  function NodeIO( node, phetioID ) {
    assert && assertInstanceOf( node, phet.scenery.Node );
    ObjectIO.call( this, node, phetioID );

    // TODO: This is in-progress work to convert object properties to Axon Properties, see https://github.com/phetsims/phet-io/issues/1326
    var visibleProperty = new NodeProperty( node, 'visibility', 'visible', {

      // pick the following values from the parent Node
      phetioReadOnly: node.phetioReadOnly,
      phetioState: node.phetioState,
      phetioType: PropertyIO( BooleanIO ),

      tandem: node.tandem.createTandem( 'visibleProperty' ),
      phetioInstanceDocumentation: 'Property that controls whether the Node will be visible (and interactive), see the NodeIO documentation for more details.'
    } );

    var pickableProperty = new NodeProperty( node, 'pickability', 'pickable', {

      // pick the following values from the parent Node
      phetioReadOnly: node.phetioReadOnly,
      phetioState: node.phetioState,

      tandem: node.tandem.createTandem( 'pickableProperty' ),
      phetioType: PropertyIO( NullableIO( BooleanIO ) ),
      phetioInstanceDocumentation: 'Set whether the node will be pickable (and hence interactive), see the NodeIO documentation for more details.'
    } );

    // Adapter for the opacity.  Cannot use NodeProperty at the moment because it doesn't handle numeric types
    // properly--we may address this by moving to a mixin pattern.
    var opacityProperty = new NumberProperty( node.opacity, {

      // pick the following values from the parent Node
      phetioReadOnly: node.phetioReadOnly,
      phetioState: node.phetioState,

      tandem: node.tandem.createTandem( 'opacityProperty' ),
      range: { min: 0, max: 1 },
      phetioInstanceDocumentation: 'Opacity of the parent NodeIO, between 0 (invisible) and 1 (fully visible).'
    } );
    opacityProperty.link( function( opacity ) { node.opacity = opacity; } );
    node.on( 'opacity', function() { opacityProperty.value = node.opacity; } );

    // @private
    this.disposeNodeIO = function() {
      visibleProperty.dispose();
      pickableProperty.dispose();
      opacityProperty.dispose();
    };
  }

  phetioInherit( ObjectIO, 'NodeIO', NodeIO, {

    /**
     * @public - called by PhetioObject when the wrapper is done
     */
    dispose: function() {
      this.disposeNodeIO();
    }
  }, {

    /**
     * Since NodeIO has no intrinsic state, we must signify to the PhET-iO serialization engine that this Node should
     * opt out of appearing in the state. We can't achieve this by removing this method, since NodeIO's parent type has
     * a `toStateObject` that causes a cyclical JSON reference.
     *
     * We also don't need matching `fromStateObject` and `setValue` methods because this type won't be added to the state
     * object, and thus setState will never be called on instances of NodeIO.
     *
     * Subtypes can still override this method, and implement their own `fromStateObject` and `setValue` if there is desired
     * serializable data for that type to hold in the state.
     *
     * @returns {undefined} - We don't use null because other types want that value in the state, see `NullableIO` for example.
     * @override
     */
    toStateObject: function() {
      return undefined;
    },

    /**
     * @param {Node} o
     * @returns {Object}
     * @override - to prevent attempted JSON serialization of circular Node
     */
    fromStateObject: function( o ) {
      return o; // Pass through values defined by subclasses, such as AquaRadioButtonIO.enabled
    },

    documentation: 'The base type for graphical and potentially interactive objects.  NodeIO has nested PropertyIO values ' +
                   'for visibility, pickability and opacity.' +
                   '
' +
                   '
' +
                   'Pickable can take one of three values:
' +
                   '
' +
                   '
null: pass-through behavior. Nodes with input listeners are pickable, but nodes without input listeners won\'t block events for nodes behind it.
' +
                   '
false: The node cannot be interacted with, and it blocks events for nodes behind it.
' +
                   '
true: The node can be interacted with (if it has an input listener).
' +
                   '
' +
                   'For more about Scenery node pickability, please see http://phetsims.github.io/scenery/doc/implementation-notes#pickability'
  } );

  scenery.register( 'NodeIO', NodeIO );

  return NodeIO;
} );

<commit_msg>added comment about phetioState in NodeIO, see https://github.com/phetsims/phet-io-wrappers/issues/122<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * IO type for Node
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var NodeProperty = require( 'SCENERY/util/NodeProperty' );
  var NumberProperty = require( 'AXON/NumberProperty' );
  var PropertyIO = require( 'AXON/PropertyIO' );
  var scenery = require( 'SCENERY/scenery' );

  // ifphetio
  var assertInstanceOf = require( 'ifphetio!PHET_IO/assertInstanceOf' );
  var BooleanIO = require( 'ifphetio!PHET_IO/types/BooleanIO' );
  var NullableIO = require( 'ifphetio!PHET_IO/types/NullableIO' );
  var ObjectIO = require( 'ifphetio!PHET_IO/types/ObjectIO' );
  var phetioInherit = require( 'ifphetio!PHET_IO/phetioInherit' );

  /**
   * IO type for phet/scenery's Node
   * @param {Node} node
   * @param {string} phetioID
   * @constructor
   */
  function NodeIO( node, phetioID ) {
    assert && assertInstanceOf( node, phet.scenery.Node );
    ObjectIO.call( this, node, phetioID );

    // TODO: This is in-progress work to convert object properties to Axon Properties, see https://github.com/phetsims/phet-io/issues/1326
    var visibleProperty = new NodeProperty( node, 'visibility', 'visible', {

      // pick the following values from the parent Node
      phetioReadOnly: node.phetioReadOnly,
      phetioState: node.phetioState,
      phetioType: PropertyIO( BooleanIO ),

      tandem: node.tandem.createTandem( 'visibleProperty' ),
      phetioInstanceDocumentation: 'Property that controls whether the Node will be visible (and interactive), see the NodeIO documentation for more details.'
    } );

    var pickableProperty = new NodeProperty( node, 'pickability', 'pickable', {

      // pick the following values from the parent Node
      phetioReadOnly: node.phetioReadOnly,
      phetioState: node.phetioState,

      tandem: node.tandem.createTandem( 'pickableProperty' ),
      phetioType: PropertyIO( NullableIO( BooleanIO ) ),
      phetioInstanceDocumentation: 'Set whether the node will be pickable (and hence interactive), see the NodeIO documentation for more details.'
    } );

    // Adapter for the opacity.  Cannot use NodeProperty at the moment because it doesn't handle numeric types
    // properly--we may address this by moving to a mixin pattern.
    var opacityProperty = new NumberProperty( node.opacity, {

      // pick the following values from the parent Node
      phetioReadOnly: node.phetioReadOnly,
      phetioState: node.phetioState,

      tandem: node.tandem.createTandem( 'opacityProperty' ),
      range: { min: 0, max: 1 },
      phetioInstanceDocumentation: 'Opacity of the parent NodeIO, between 0 (invisible) and 1 (fully visible).'
    } );
    opacityProperty.link( function( opacity ) { node.opacity = opacity; } );
    node.on( 'opacity', function() { opacityProperty.value = node.opacity; } );

    // @private
    this.disposeNodeIO = function() {
      visibleProperty.dispose();
      pickableProperty.dispose();
      opacityProperty.dispose();
    };
  }

  phetioInherit( ObjectIO, 'NodeIO', NodeIO, {

    /**
     * @public - called by PhetioObject when the wrapper is done
     */
    dispose: function() {
      this.disposeNodeIO();
    }
  }, {

    /**
     * Since NodeIO has no intrinsic state, we must signify to the PhET-iO serialization engine that this Node should
     * opt out of appearing in the state. We can't achieve this by removing this method, since NodeIO's parent type has
     * a `toStateObject` that causes a cyclical JSON reference.
     *
     * We also don't need matching `fromStateObject` and `setValue` methods because this type won't be added to the state
     * object, and thus setState will never be called on instances of NodeIO.
     *
     * Subtypes can still override this method, and implement their own `fromStateObject` and `setValue` if there is desired
     * serializable data for that type to hold in the state.
     *
     * We can't declare the Node phetioState: false, like the general pattern that we want to use ( see, because that property
     * bubbles to children, and we want things like visibleProperty to be in the state by default, just not the NodeIO
     * type itself.
     *
     * @returns {undefined} - We don't use null because other types want that value in the state, see `NullableIO` for example.
     * @override
     */
    toStateObject: function() {
      return undefined;
    },

    /**
     * @param {Node} o
     * @returns {Object}
     * @override - to prevent attempted JSON serialization of circular Node
     */
    fromStateObject: function( o ) {
      return o; // Pass through values defined by subclasses, such as AquaRadioButtonIO.enabled
    },

    documentation: 'The base type for graphical and potentially interactive objects.  NodeIO has nested PropertyIO values ' +
                   'for visibility, pickability and opacity.' +
                   '
' +
                   '
' +
                   'Pickable can take one of three values:
' +
                   '
' +
                   '
null: pass-through behavior. Nodes with input listeners are pickable, but nodes without input listeners won\'t block events for nodes behind it.
' +
                   '
false: The node cannot be interacted with, and it blocks events for nodes behind it.
' +
                   '
true: The node can be interacted with (if it has an input listener).
' +
                   '
' +
                   'For more about Scenery node pickability, please see http://phetsims.github.io/scenery/doc/implementation-notes#pickability'
  } );

  scenery.register( 'NodeIO', NodeIO );

  return NodeIO;
} );

<|endoftext|>


<commit_before>/**
 * LinkedList, implementation of an abstract list as a double linked list.
 *
 * @license data-structures
 * Robert Ödling https://github.com/robertodling/data-structures
 * License: MIT (http://www.opensource.org/licenses/mit-license.php)
 */

// 'LinkedList' will be added to global scope.
var LinkedList = (function () {

	'use strict';

	/**
	 * Returns node at specified number of steps after specified node.
	 * @param {number} node
	 * @param {number} steps
	 * @return {object} node
	 * @private
	 */
	function _nodeAfter(node, steps) {

		var i = 0;

		while (i < steps) {
			node = node.next;
			i++;
		}

		return node;
	}

	/**
	 * Inserts newBode after specified node. Assumes that 'this' is bound to LinkedList.
	 * @param {object} node
	 * @param {object} newNode
	 * @private
	 */
	function _insertAfter(node, newNode) {

		newNode.prev = node;
		newNode.next = node.next;

		if (!node.next) {
			this.tail = newNode;
		} else {
			node.next.prev = newNode;
		}
		node.next = newNode;
	}

	/**
	 * Inserts newBode before specified node. Assumes that 'this' is bound to LinkedList.
	 * @param {object} node
	 * @param {object} newNode
	 * @private
	 */
	function _insertBefore(node, newNode) {

		newNode.prev = node.prev;
		newNode.next = node;

		if (!node.prev) {
			this.head = newNode;
		} else {
			node.prev.next = newNode;
		}

		node.prev = newNode;
	}

	/**
	 * Removes a node from list. Assumes that 'this' is bound to LinkedList.
	 * @param {object} node
	 * @private
	 */
	function _removeNode(node) {
		if (!node.prev) {
			this.head = node.next;
		} else {
			node.prev.next = node.next;
		}

		if (!this.next) {
			this.tail = node.prev;
		} else {
			node.next.prev = node.prev;
		}
	}

	/**
	 * Initialize list.
	 * @constructor
	 */
	var LinkedList = function () {
		this.clear();	// set head and tail to null;
	};

	var proto = LinkedList.prototype;	// shorthand

	/**
	 * Clears list
	 */
	proto.clear = function () {
		this.head = this.tail = null;
	};

	/**
	 * Returns number of elements in list.
	 * @param {number}
	 */
	proto.size = function () {

		if (this.isEmpty()) {
			return 0;
		}

		var size = 1;
		var node = this.head;
		while (node.next) {
			node = node.next;
			size++;
		}

		return size;
	};

	/**
	 * Insert specified element first in list, will increment index of all other elements.
	 * @param {object} element
	 */
	proto.insertFirst = function (element) {

		var newNode = {element: element};

		if (this.isEmpty()) {
			this.head = newNode;
			this.tail = newNode;
		} else {
			_insertBefore.call(this, this.head, newNode);
		}
	};

	/**
	 * Insert specified element last in list, will _NOT_ increment index of any elements.
	 * @param {object} element
	 */
	proto.insertLast = function (element) {

		var node = {element: element};

		if (this.isEmpty()) {
			this.insertFirst(element)
		} else {
			_insertAfter.call(this, this.tail, node);
		}

	};

	/**
	 * Insert specified element at specified index, will increment index of all following elements.
	 * @param {number} index
	 * @param {object} element
	 */
	proto.insertAt = function (index, element) {

		// negative index always out bound
		// if empty only allow adding at index 0
		if (index < 0 || this.isEmpty() && index !== 0) {
			throw new Error("OutOfBoundException");
		}

		if (this.isEmpty()) {
			this.insertFirst(element);
		} else {
			var node = _nodeAfter(this.head, index);
			if (!node) {
				throw new Error("OutOfBoundException");
			}
			var newNode = {element: element};
			_insertBefore.call(this, node, newNode);
		}

	};

	/**
	 * Returns element at specified index.
	 * @param {number} index
	 * @return {object}
	 */
	proto.elementAt = function (index) {

		if (!this.head || index < 0) {
			throw new Error("NoSuchElementException");
		}

		var node = _nodeAfter(this.head, index);

		if (!node) {
			throw new Error("NoSuchElementException");
		}

		return node.element;
	};

	/**
	 * Remove first element.
	 */
	proto.removeFirst = function () {
		_removeNode.call(this, this.head);
	};

	/**
	 * Remove last element.
	 */
	proto.removeLast = function () {
		_removeNode.call(this, this.tail);
	};

	/**
	 * Remove element at specified index.
	 * @param {number} index
	 */
	proto.removeAt = function (index) {
		var node = _nodeAfter(this.head, index);
		_removeNode.call(this, node);
	};

	/**
	 * Check if list is empty
	 * @return {boolean}
	 */
	proto.isEmpty = function () {
		return !this.tail;
	};

	/**
	 * Returns list as array
	 * @return {array}
	 */
	proto.toArray = function () {
		if (this.isEmpty()) {
			return [];
		}

		var arr = [];
		var node = this.head;

		arr.push(node.element);

		while (node.next) {
			node = node.next;
			arr.push(node.element);
		}

		return arr;
	};

	// export LinkedList constructor
	return LinkedList;
})();<commit_msg>optimization, keep track of size<commit_after>/**
 * LinkedList, implementation of an abstract list as a double linked list.
 *
 * @license data-structures
 * Robert Ödling https://github.com/robertodling/data-structures
 * License: MIT (http://www.opensource.org/licenses/mit-license.php)
 */

// 'LinkedList' will be added to global scope.
var LinkedList = (function () {

	'use strict';

	/**
	 * Returns node at specified number of steps after specified node.
	 * @param {number} node
	 * @param {number} steps
	 * @return {object} node
	 * @private
	 */
	function _nodeAfter(node, steps) {

		var i = 0;

		while (i < steps) {
			node = node.next;
			i++;
		}

		return node;
	}

	/**
	 * Inserts newBode after specified node. Assumes that 'this' is bound to LinkedList.
	 * @param {object} node
	 * @param {object} newNode
	 * @private
	 */
	function _insertAfter(node, newNode) {

		newNode.prev = node;
		newNode.next = node.next;

		if (!node.next) {
			this.tail = newNode;
		} else {
			node.next.prev = newNode;
		}
		node.next = newNode;

		this._size++;
	}

	/**
	 * Inserts newBode before specified node. Assumes that 'this' is bound to LinkedList.
	 * @param {object} node
	 * @param {object} newNode
	 * @private
	 */
	function _insertBefore(node, newNode) {

		newNode.prev = node.prev;
		newNode.next = node;

		if (!node.prev) {
			this.head = newNode;
		} else {
			node.prev.next = newNode;
		}

		node.prev = newNode;

		this._size++;
	}

	/**
	 * Removes a node from list. Assumes that 'this' is bound to LinkedList.
	 * @param {object} node
	 * @private
	 */
	function _removeNode(node) {
		if (!node.prev) {
			this.head = node.next;
		} else {
			node.prev.next = node.next;
		}

		if (!this.next) {
			this.tail = node.prev;
		} else {
			node.next.prev = node.prev;
		}

		this._size--;
	}

	/**
	 * Initialize list.
	 * @constructor
	 */
	var LinkedList = function () {
		this.clear();	// set head and tail to null;
	};

	var proto = LinkedList.prototype;	// shorthand

	/**
	 * Clears list
	 */
	proto.clear = function () {
		this.head = this.tail = null;
		this._size = 0;
	};

	/**
	 * Returns number of elements in list.
	 * @param {number}
	 */
	proto.size = function () {
		return this._size;
	};

	/**
	 * Insert specified element first in list, will increment index of all other elements.
	 * @param {object} element
	 */
	proto.insertFirst = function (element) {

		var newNode = {element: element};

		if (this.isEmpty()) {
			this.head = newNode;
			this.tail = newNode;
			this._size++;
		} else {
			_insertBefore.call(this, this.head, newNode);
		}
	};

	/**
	 * Insert specified element last in list, will _NOT_ increment index of any elements.
	 * @param {object} element
	 */
	proto.insertLast = function (element) {

		var node = {element: element};

		if (this.isEmpty()) {
			this.insertFirst(element)
		} else {
			_insertAfter.call(this, this.tail, node);
		}

	};

	/**
	 * Insert specified element at specified index, will increment index of all following elements.
	 * @param {number} index
	 * @param {object} element
	 */
	proto.insertAt = function (index, element) {

		// negative index always out bound
		// if empty only allow adding at index 0
		if (index < 0 || this.isEmpty() && index !== 0) {
			throw new Error("OutOfBoundException");
		}

		if (this.isEmpty()) {
			this.insertFirst(element);
		} else {
			var node = _nodeAfter(this.head, index);
			if (!node) {
				throw new Error("OutOfBoundException");
			}
			var newNode = {element: element};
			_insertBefore.call(this, node, newNode);
		}

	};

	/**
	 * Returns element at specified index.
	 * @param {number} index
	 * @return {object}
	 */
	proto.elementAt = function (index) {

		if (!this.head || index < 0) {
			throw new Error("NoSuchElementException");
		}

		var node = _nodeAfter(this.head, index);

		if (!node) {
			throw new Error("NoSuchElementException");
		}

		return node.element;
	};

	/**
	 * Remove first element.
	 */
	proto.removeFirst = function () {
		_removeNode.call(this, this.head);
	};

	/**
	 * Remove last element.
	 */
	proto.removeLast = function () {
		_removeNode.call(this, this.tail);
	};

	/**
	 * Remove element at specified index.
	 * @param {number} index
	 */
	proto.removeAt = function (index) {
		var node = _nodeAfter(this.head, index);
		_removeNode.call(this, node);
	};

	/**
	 * Check if list is empty
	 * @return {boolean}
	 */
	proto.isEmpty = function () {
		return !this.tail;
	};

	/**
	 * Returns list as array
	 * @return {array}
	 */
	proto.toArray = function () {
		if (this.isEmpty()) {
			return [];
		}

		var arr = [];
		var node = this.head;

		arr.push(node.element);

		while (node.next) {
			node = node.next;
			arr.push(node.element);
		}

		return arr;
	};

	// export LinkedList constructor
	return LinkedList;
})();<|endoftext|>


<commit_before>/*global require, module, $, jQuery*/

module.exports = {
    init: function(div, _options){
        var options = $.extend({}, _options);

        $.extend(this, {
            div: div,
            options: options,
            obj_stack: {
                "self": [],
                "en": [],
                "self_ball": [],
                "en_ball": [],
                "others": []
            },
            obj_stack: {},
            rules: {}
        });

        $.each(types, function(i, name){
            this.obj_stack[name] = [];
        }.bind(this));

        return this;
    },

    add: function(type, str, x, y, dx, dy, options){
        var Object = require("./object.js");
        var obj = new Object(this.div, str, x, y, dx, dy, options);

        this.obj_stack[type].push(obj);
        return obj;
    },

    update: function(frame_num){
        var options = this.options;

        $.each(this.obj_stack, (function(key, stack){
            this.obj_stack[key] = $.grep(stack, function(o){
                var ret = o.update();
                if(((o.x<0 || o.y<0 || o.x > options.game_width || o.y > options.game_height)&& !o.options.live_even_outside)){
                    o.clear();
                    return false;
                }
                return ret;
            });
        }).bind(this));

        var is_collision = function(obj1, obj2){
            var c1 = obj1.center();
            var c2 = obj2.center();
            var d_c = Math.sqrt(Math.pow(c1.x - c2.x, 2) + Math.pow(c1.y - c2.y, 2));
            return d_c < (obj1.options.radius + obj2.options.radius);
        };

        $.each(this.obj_stack, (function(key, stack){
            if(typeof this.rules[key] != "undefined"){
                $.each(this.rules[key], function(i, rule){
                    var dst_stack = this.obj_stack[rule.dst];
                    var callback = rule.cb;

                    $.each(stack, function(i, src){
                        $.each(dst_stack, function(i, dst){
                            if(is_collision(src, dst)){
                                callback(src, dst);
                            }
                        });
                    });
                }.bind(this));
            }
        }).bind(this));
    },

    register_collision_rule: function(src, dst, callback){
        if(typeof this.rules[src] == "undefined")
            this.rules[src] = [];

        this.rules[src].push({
            dst: dst,
            cb: callback
        });
    }
};
<commit_msg>Change arguments of obj_manager.init<commit_after>/*global require, module, $, jQuery*/

module.exports = {
    init: function(types, _options){
        var options = $.extend({}, _options);

        $.extend(this, {
            div: options.div,
            options: options,
            obj_stack: {},
            rules: {}
        });

        $.each(types, function(i, name){
            this.obj_stack[name] = [];
        }.bind(this));

        return this;
    },

    add: function(type, str, x, y, dx, dy, options){
        var Object = require("./object.js");
        var obj = new Object(this.div, str, x, y, dx, dy, options);

        this.obj_stack[type].push(obj);
        return obj;
    },

    update: function(frame_num){
        var options = this.options;

        $.each(this.obj_stack, (function(key, stack){
            this.obj_stack[key] = $.grep(stack, function(o){
                var ret = o.update();
                if(((o.x<0 || o.y<0 || o.x > options.game_width || o.y > options.game_height)&& !o.options.live_even_outside)){
                    o.clear();
                    return false;
                }
                return ret;
            });
        }).bind(this));

        var is_collision = function(obj1, obj2){
            var c1 = obj1.center();
            var c2 = obj2.center();
            var d_c = Math.sqrt(Math.pow(c1.x - c2.x, 2) + Math.pow(c1.y - c2.y, 2));
            return d_c < (obj1.options.radius + obj2.options.radius);
        };

        $.each(this.obj_stack, (function(key, stack){
            if(typeof this.rules[key] != "undefined"){
                $.each(this.rules[key], function(i, rule){
                    var dst_stack = this.obj_stack[rule.dst];
                    var callback = rule.cb;

                    $.each(stack, function(i, src){
                        $.each(dst_stack, function(i, dst){
                            if(is_collision(src, dst)){
                                callback(src, dst);
                            }
                        });
                    });
                }.bind(this));
            }
        }).bind(this));
    },

    register_collision_rule: function(src, dst, callback){
        if(typeof this.rules[src] == "undefined")
            this.rules[src] = [];

        this.rules[src].push({
            dst: dst,
            cb: callback
        });
    }
};
<|endoftext|>


<commit_before>var mouseDown = false;
var currentx = 400;
var currenty = 300;
var ltArrow = 37;
var upArrow = 38;
var rtArrow = 39;
var dwArrow = 40;
var size = 20;

function keyHit(evt) {
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');

	var thisKey;
	if (evt) {
		thisKey = evt.which;
	}
	else {
		thisKey = window.event.keyCode;
	}
	switch(thisKey){
		case ltArrow:
			currentx -= size;
			if(currentx<0){currentx = 0;}
			ctx.fillRect(currentx, currenty, size, size);
			break;
		case rtArrow:
			currentx += size;
			ctx.fillRect(currentx, currenty, size, size);
			break;
		case upArrow:
			currenty -= size;
			if(currenty<0){currenty = 0;}
			ctx.fillRect(currentx, currenty, size, size);
			break;
		case dwArrow:
			currenty += size;
			ctx.fillRect(currentx, currenty, size, size);
			break;
		default:
			break;
	}
}

function resetSize(){
	var newLoc = document.getElementById("size");
	newLoc.blur();
	var newSize = newLoc.options[newLoc.selectedIndex].value;
	size = parseInt(newSize);
}

function makeEqual(){
	var canvas = document.getElementById('canvas');
	if (!canvas) return;
	var ctx = canvas.getContext('2d');
	ctx.fillStyle = $('#colorpicker').val();
}

function isMobile() {
	return /Mobi/.test(navigator.userAgent);
}

function resizeCanvas() {
	var canvas = document.getElementById('canvas');
	if (!canvas) return;

	var mobile = isMobile();
	var ctx = canvas.getContext('2d');
    canvas.width = mobile ? window.outerWidth: window.innerWidth;
    canvas.height = (mobile ? window.outerHeight: window.innerHeight) - $('#header').outerHeight() - 5;
    clean();
	ctx.fillStyle = $('#colorpicker').val();
	state = [];
}

function convertCanvas() {
	var canvas = document.getElementById('canvas');
	var img = Canvas2Image.saveAsJPEG(canvas, true);

	if (!img) {
		alert("Sorry, this browser is not capable of saving " + strType + " files!");
		return false;
	}

	img.id = "canvasimage";
	canvas.parentNode.replaceChild(img, canvas);
}

var state = [];

function getTouchCoord(e) {
    var offsets = $('#canvas').offset();
	var currentx, currenty;
	currentx = e.originalEvent.targetTouches[0].pageX - offsets.left;
	currenty = e.originalEvent.targetTouches[0].pageY - offsets.top;
	currentx = parseInt(currentx/size) * size;
	currenty = parseInt(currenty/size) * size;
	return [currentx, currenty];
}

function getMouseCoords(e) {
	var offsets = $('#canvas').offset();
	var currentx, currenty;
	currentx = e.pageX - offsets.left;
	currenty = e.pageY - offsets.top;
	currentx = parseInt(currentx/size) * size;
	currenty = parseInt(currenty/size) * size;
	return [currentx, currenty];
}

function clean() {
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');
	ctx.fillStyle = '#ffffff';
	ctx.fillRect(0,0,canvas.width, canvas.height);
}

function updateUI() {
	// if (state.length == 0) {
	// 	$('#undo').prop('disabled', true);
	// } else {
	// 	$('#undo').prop('disbled', false);
	// }
}

function redraw() {
	clean();
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');
	for (var i=0; i<state.length; i++) {
		size = state[i][0];
		ctx.fillStyle = state[i][1];
		for (var j=2; j<state[i].length; j+=2) {
			ctx.fillRect(state[i][j], state[i][j+1], size, size);
		}
	}

	ctx.fillStyle = $('#colorpicker').val();
}

function updateState(tempstate, coords) {
    tempstate.push(coords[0]);
    tempstate.push(coords[1]);
	currentx = coords[0];
	currenty = coords[1];
}

$(document).ready(function(){
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');
	$('#colorpicker').val('#AA3B0C');

	document.onkeydown = keyHit;
	document.getElementById("size").selectedIndex = 1;
	document.getElementById("size").onchange = resetSize;

	var tempstate = [];

	$('#canvas').on('touchstart', function(e){
		e.preventDefault();
	    mouseDown = true;
	    tempstate = [];
	    tempstate.push(size);
	    tempstate.push($('#colorpicker').val());
	    var coords = getTouchCoords(e);
	    updateState(tempstate, coords);
		ctx.fillRect(coords[0], coords[1], size, size);
	});

	$('#canvas').mousedown(function(e){
		e.preventDefault();
		console.log(e);
		mouseDown = true;
	    tempstate = [];
	    tempstate.push(size);
	    tempstate.push($('#colorpicker').val());
	    var coords = getMouseCoords(e);
	    updateState(tempstate, coords);
		ctx.fillRect(coords[0], coords[1], size, size);
	});

	$(document).on('touchend mouseup', function(e){
		mouseDown = false;
		if (tempstate.length > 0) {
			state.push(tempstate);
			tempstate = [];
		}
	});

	$('#canvas').mousemove(function(e){
	    if(mouseDown == false) return;

	    var coords = getMouseCoords(e);
	    if (coords[0] == currentx && coords[1] == currenty) return;
	    updateState(tempstate, coords);
		ctx.fillRect(coords[0], coords[1], size, size);
	});

	$('#canvas').on('touchmove', function(e){
	    if(mouseDown == false) return;

	    // Mouse click + moving logic here
	    var coords = getTouchCoords(e);
	    if (coords[0] == currentx && coords[1] == currenty) return;
	    updateState(tempstate, coords);
		ctx.fillRect(coords[0], coords[1], size, size);
	});

    // resize the canvas to fill browser window dynamically
    window.addEventListener('resize', resizeCanvas, false);
    resizeCanvas();

	ctx.fillStyle = '#AA3B0C';
	currentx = $('#canvas').width()/2;
	currenty = $('#canvas').height()/2;
	ctx.fillRect(currentx,currenty, 20, 20);
	state.push([size, ctx.fillStyle, currentx, currenty]);

	makeEqual();
	$('#colorpicker').change(makeEqual);

	$('#download').click(function(e) {
		e.preventDefault();
		canvas.toBlob(function(blob) {
		    saveAs(blob, "pixels.jpg");
		},'image/jpeg', 0.95);
	});

	$('#undo').click(function(e) {
		e.preventDefault();
		if (state.length > 0) {
			state.pop();
			redraw();
			updateUI();
		}
	});

	if (!localStorage.pixelUser) {
		localStorage.pixelUser = true;
		$('#welcomeModal').modal('show');
	}
});

<commit_msg>minor fix<commit_after>var mouseDown = false;
var currentx = 400;
var currenty = 300;
var ltArrow = 37;
var upArrow = 38;
var rtArrow = 39;
var dwArrow = 40;
var size = 20;

function keyHit(evt) {
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');

	var thisKey;
	if (evt) {
		thisKey = evt.which;
	}
	else {
		thisKey = window.event.keyCode;
	}
	switch(thisKey){
		case ltArrow:
			currentx -= size;
			if(currentx<0){currentx = 0;}
			ctx.fillRect(currentx, currenty, size, size);
			break;
		case rtArrow:
			currentx += size;
			ctx.fillRect(currentx, currenty, size, size);
			break;
		case upArrow:
			currenty -= size;
			if(currenty<0){currenty = 0;}
			ctx.fillRect(currentx, currenty, size, size);
			break;
		case dwArrow:
			currenty += size;
			ctx.fillRect(currentx, currenty, size, size);
			break;
		default:
			break;
	}
}

function resetSize(){
	var newLoc = document.getElementById("size");
	newLoc.blur();
	var newSize = newLoc.options[newLoc.selectedIndex].value;
	size = parseInt(newSize);
}

function makeEqual(){
	var canvas = document.getElementById('canvas');
	if (!canvas) return;
	var ctx = canvas.getContext('2d');
	ctx.fillStyle = $('#colorpicker').val();
}

function isMobile() {
	return /Mobi/.test(navigator.userAgent);
}

function resizeCanvas() {
	var canvas = document.getElementById('canvas');
	if (!canvas) return;

	var mobile = isMobile();
	var ctx = canvas.getContext('2d');
    canvas.width = mobile ? window.outerWidth: window.innerWidth;
    canvas.height = (mobile ? window.outerHeight: window.innerHeight) - $('#header').outerHeight() - 5;
    clean();
	ctx.fillStyle = $('#colorpicker').val();
	state = [];
}

function convertCanvas() {
	var canvas = document.getElementById('canvas');
	var img = Canvas2Image.saveAsJPEG(canvas, true);

	if (!img) {
		alert("Sorry, this browser is not capable of saving " + strType + " files!");
		return false;
	}

	img.id = "canvasimage";
	canvas.parentNode.replaceChild(img, canvas);
}

var state = [];

function getTouchCoords(e) {
    var offsets = $('#canvas').offset();
	var currentx, currenty;
	currentx = e.originalEvent.targetTouches[0].pageX - offsets.left;
	currenty = e.originalEvent.targetTouches[0].pageY - offsets.top;
	currentx = parseInt(currentx/size) * size;
	currenty = parseInt(currenty/size) * size;
	return [currentx, currenty];
}

function getMouseCoords(e) {
	var offsets = $('#canvas').offset();
	var currentx, currenty;
	currentx = e.pageX - offsets.left;
	currenty = e.pageY - offsets.top;
	currentx = parseInt(currentx/size) * size;
	currenty = parseInt(currenty/size) * size;
	return [currentx, currenty];
}

function clean() {
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');
	ctx.fillStyle = '#ffffff';
	ctx.fillRect(0,0,canvas.width, canvas.height);
}

function updateUI() {
	// if (state.length == 0) {
	// 	$('#undo').prop('disabled', true);
	// } else {
	// 	$('#undo').prop('disbled', false);
	// }
}

function redraw() {
	clean();
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');
	for (var i=0; i<state.length; i++) {
		size = state[i][0];
		ctx.fillStyle = state[i][1];
		for (var j=2; j<state[i].length; j+=2) {
			ctx.fillRect(state[i][j], state[i][j+1], size, size);
		}
	}

	ctx.fillStyle = $('#colorpicker').val();
}

function updateState(tempstate, coords) {
    tempstate.push(coords[0]);
    tempstate.push(coords[1]);
	currentx = coords[0];
	currenty = coords[1];
}

$(document).ready(function(){
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');
	$('#colorpicker').val('#AA3B0C');

	document.onkeydown = keyHit;
	document.getElementById("size").selectedIndex = 1;
	document.getElementById("size").onchange = resetSize;

	var tempstate = [];

	$('#canvas').on('touchstart', function(e){
		e.preventDefault();
	    mouseDown = true;
	    tempstate = [];
	    tempstate.push(size);
	    tempstate.push($('#colorpicker').val());
	    var coords = getTouchCoords(e);
	    updateState(tempstate, coords);
		ctx.fillRect(coords[0], coords[1], size, size);
	});

	$('#canvas').mousedown(function(e){
		e.preventDefault();
		console.log(e);
		mouseDown = true;
	    tempstate = [];
	    tempstate.push(size);
	    tempstate.push($('#colorpicker').val());
	    var coords = getMouseCoords(e);
	    updateState(tempstate, coords);
		ctx.fillRect(coords[0], coords[1], size, size);
	});

	$(document).on('touchend mouseup', function(e){
		mouseDown = false;
		if (tempstate.length > 0) {
			state.push(tempstate);
			tempstate = [];
		}
	});

	$('#canvas').mousemove(function(e){
	    if(mouseDown == false) return;

	    var coords = getMouseCoords(e);
	    if (coords[0] == currentx && coords[1] == currenty) return;
	    updateState(tempstate, coords);
		ctx.fillRect(coords[0], coords[1], size, size);
	});

	$('#canvas').on('touchmove', function(e){
	    if(mouseDown == false) return;

	    // Mouse click + moving logic here
	    var coords = getTouchCoords(e);
	    if (coords[0] == currentx && coords[1] == currenty) return;
	    updateState(tempstate, coords);
		ctx.fillRect(coords[0], coords[1], size, size);
	});

    // resize the canvas to fill browser window dynamically
    window.addEventListener('resize', resizeCanvas, false);
    resizeCanvas();

	ctx.fillStyle = '#AA3B0C';
	currentx = $('#canvas').width()/2;
	currenty = $('#canvas').height()/2;
	ctx.fillRect(currentx,currenty, 20, 20);
	state.push([size, ctx.fillStyle, currentx, currenty]);

	makeEqual();
	$('#colorpicker').change(makeEqual);

	$('#download').click(function(e) {
		e.preventDefault();
		canvas.toBlob(function(blob) {
		    saveAs(blob, "pixels.jpg");
		},'image/jpeg', 0.95);
	});

	$('#undo').click(function(e) {
		e.preventDefault();
		if (state.length > 0) {
			state.pop();
			redraw();
			updateUI();
		}
	});

	if (!localStorage.pixelUser) {
		localStorage.pixelUser = true;
		$('#welcomeModal').modal('show');
	}
});

<|endoftext|>


<commit_before>var _CALLBACK_ = function() {
	$(document).ready(
		function() {
			function parse(v) {
				var t = v.replace(/(“|”)/ig, '"');
				return JSON.parse(t);
			}
			var v = $('.qaletplugin'), r={}, f=[];
			for (var i = 0; i < v.length; i++) {
				var data = $(v[i]).html();
				if (!data) data = $(v[i]).attr('data');
				var o = parse(data);
				if (o.module) {
					r[o.module] = true;
					o.id = o.module + '_plugin_' + i;
					f[f.length] = o;
					 $(v[i]).html('

').fadeIn( "slow");
				}
			}
			console.log(f);
			for (var i=0; i<f.length; i++) {
				if (typeof _QALET_[f[i].module] == 'function') {
					_QALET_[f[i].module](f[i]);
					//$(v[i]).fadeIn( "slow");
				} else {
					console.log('=='+f[i].module+'==');
				}
			}

			$('<link>').appendTo('head').attr({ type: 'text/css', rel: 'stylesheet', href: '//qalet.com/css/bootstrap.min.css' });
			$('<link>').appendTo('head').attr({ type: 'text/css', rel: 'stylesheet', href: '//docviewer.qalet.com/package/docviewer_wp.min.css' });
		//	$.getScript('http://docviewer.qalet.com/package/qalet_plugin_plus.jsx?plus='+Object.keys(r).join(',') + '&callback=_QACALLBACK_');
		}
	);
};
<commit_msg>Update qalet_plugin.js<commit_after>var _CALLBACK_ = function() {
	$(document).ready(
		function() {
			function parse(v) {
				var t = v.replace(/(“|”)/ig, '"');
				return JSON.parse(t);
			}
			var v = $('.qaletplugin'), r={}, f=[];
			for (var i = 0; i < v.length; i++) {
				var data = $(v[i]).html();
				if (!data) data = $(v[i]).attr('data');
				var o = parse(data);
				if (o.module) {
					r[o.module] = true;
					o.id = o.module + '_plugin_' + i;
					f[f.length] = o;
					 $(v[i]).html('

').fadeIn( "slow");
				}
			}
			for (var i=0; i<f.length; i++) {
				if (typeof _QALET_[f[i].module] == 'function') {
					_QALET_[f[i].module](f[i]);
					//$(v[i]).fadeIn( "slow");
				} else {
					console.log('=='+f[i].module+'==');
				}
			}

			$('<link>').appendTo('head').attr({ type: 'text/css', rel: 'stylesheet', href: '//qalet.com/css/bootstrap.min.css' });
			$('<link>').appendTo('head').attr({ type: 'text/css', rel: 'stylesheet', href: '//docviewer.qalet.com/package/docviewer_wp.min.css' });
		//	$.getScript('http://docviewer.qalet.com/package/qalet_plugin_plus.jsx?plus='+Object.keys(r).join(',') + '&callback=_QACALLBACK_');
		}
	);
};
<|endoftext|>


<commit_before>var meaningDisplayFlag = false;
var meaning, word, context;

var backend = chrome.runtime.connect({name: "connectionToBackend"});

$(document).ready(function () {
    $(document).dblclick(function(e){
        var wordObject = window.getSelection();
        word = $.trim(wordObject.toString().toLowerCase());
        var result = word.split(/[\n\r\s]+/);
        // To disable multiple words selection
        // and null selection
        if (result.length != 1 || word == '') {
            return;
        }

        showQtip(document, e);
        fetchMeaningCambridge(word, function(message){
            meaning = message;
            changeQtipText(meaning);
            meaningDisplayFlag = true;
        });

        context = getContext(wordObject);
        console.log(context);
    });

    $(document).on('mousedown', function(){
        if (!meaningDisplayFlag) {
            return;
        }

        if (meaning === noMeaningFoundError || meaning == otherError) {
            // Don't save the word
            return;
        }

        backend.postMessage({type: "saveWord", word: word, meaning: meaning, context: context});
        meaningDisplayFlag = false;
    });
});

function showQtip(selector, e) {
    $(selector).qtip({
        id: 'meaningTooltip',
        content: {
            text: "Searching for meaning....."
        },

        position: {
            target: [e.pageX, e.pageY],
            viewport: $(window),
            adjust: {
                y: 12,
                mouse: false
            }
        },

        show: {
            ready: true
        },

        style: {
            width: "250px",
            height: "100px"
        },

        hide: {
            event: 'mousedown'
        },

        events: {
            hide: function(event, api) {
                api.destroy();
            }
        }
    });

    meaningDisplayFlag = true;
}

function changeQtipText(newText) {
    $('#qtip-meaningTooltip').qtip('option', 'content.text', newText);
}

// Listen for incoming requests from browser_action script
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSelection") {
        sendResponse({data: window.getSelection().toString(), context:getContext(window.getSelection())});
    } else {
        sendResponse({}); // snub them.
    }
});
<commit_msg>Fixes #18<commit_after>var meaningDisplayFlag = false;
var meaning, word, context;

var backend = chrome.runtime.connect({name: "connectionToBackend"});

$(document).ready(function () {
    $(document).dblclick(function(e){
        // Don't show meaning on double click on input
        if ($(document.activeElement).is('input, textarea')) {
            return false;
        }

        var wordObject = window.getSelection();
        word = $.trim(wordObject.toString().toLowerCase());
        var result = word.split(/[\n\r\s]+/);
        // To disable multiple words selection
        // and null selection
        if (result.length != 1 || word == '') {
            return;
        }

        showQtip(document, e);
        fetchMeaningCambridge(word, function(message){
            meaning = message;
            changeQtipText(meaning);
            meaningDisplayFlag = true;
        });

        context = getContext(wordObject);
        console.log(context);
    });

    $(document).on('mousedown', function(){
        if (!meaningDisplayFlag) {
            return;
        }

        if (meaning === noMeaningFoundError || meaning == otherError) {
            // Don't save the word
            return;
        }

        backend.postMessage({type: "saveWord", word: word, meaning: meaning, context: context});
        meaningDisplayFlag = false;
    });
});

function showQtip(selector, e) {
    $(selector).qtip({
        id: 'meaningTooltip',
        content: {
            text: "Searching for meaning....."
        },

        position: {
            target: [e.pageX, e.pageY],
            viewport: $(window),
            adjust: {
                y: 12,
                mouse: false
            }
        },

        show: {
            ready: true
        },

        style: {
            width: "250px",
            height: "100px"
        },

        hide: {
            event: 'mousedown'
        },

        events: {
            hide: function(event, api) {
                api.destroy();
            }
        }
    });

    meaningDisplayFlag = true;
}

function changeQtipText(newText) {
    $('#qtip-meaningTooltip').qtip('option', 'content.text', newText);
}

// Listen for incoming requests from browser_action script
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSelection") {
        sendResponse({data: window.getSelection().toString(), context:getContext(window.getSelection())});
    } else {
        sendResponse({}); // snub them.
    }
});
<|endoftext|>


<commit_before>/**
 * QuickBlox VideoChat WebRTC library
 * version 0.1.0
 *
 * Author: Igor Khomenko (igor@quickblox.com)
 *
 */

/*
  Public methods:
    - call(userID)
    - accept(userID)
    - reject(userID)
    - stop(userID)

  Public callbacks:
    - onCall(fromUserID, sessionDescription)
    - onAccept(fromUserID, sessionDescription)
    - onReject(fromUserID)
    - onStop(fromUserID, reason)
    - onCandidate(fromUserID, candidate)
 */

var SDP_CONSTRAINTS = {
	'mandatory': {
		'OfferToReceiveAudio': true,
		'OfferToReceiveVideo': true
	}
};

var QBVideoChatState = {
	INACTIVE: 'inactive',
	ESTABLISHING: 'establishing',
	ACTIVE: 'active'
};

function QBVideoChat(constraints, localStreamElement, remoteStreamElement, signalingService, sessionID) {
 	var self = this;

	this.candidatesQueue = [];
	this.remoteSessionDescription = null;
	this.onGetUserMediaSuccess = null;
	this.onGetUserMediaError = null;
	this.state = QBVideoChatState.INACTIVE;

	this.constraints = constraints;
	this.localStreamElement = localStreamElement;
	this.remoteStreamElement = remoteStreamElement;

	this.sessionID = sessionID || new Date().getTime();
	traceVC("sessionID " + this.sessionID);

	// Signalling callbacks
	this.addCandidate = function(data) {
		var jsonCandidate, candidate;

		jsonCandidate = self.signalingService.xmppTextToDictionary(data);
		candidate = new RTCIceCandidate(jsonCandidate);

		self.pc.addIceCandidate(candidate);
	};

	this.onAcceptSignalingCallback = function(sessionDescription) {
		self.setRemoteDescription(sessionDescription, "answer"); //TODO: refactor this (hide)
	};

	this.signalingService = signalingService;
	this.signalingService.onCandidateCallback = this.addCandidate;
	this.signalingService.addOnAcceptCallback(this.onAcceptSignalingCallback);

	// MediaStream getUserMedia
	this.getUserMedia = function() {
		traceVC("getUserMedia...");

		getUserMedia(this.constraints, successCallback, errorCallback);

		function successCallback(localMediaStream) {
			traceVC("getUserMedia success");
			attachMediaStream(self.localStreamElement, localMediaStream);
			self.localStream = localMediaStream;
			self.createRTCPeerConnection();
			self.onGetUserMediaSuccess();
		}

		function errorCallback(error) {
			traceVC("getUserMedia error: ", error);
			self.onGetUserMediaSuccess();
		}
	};

	// RTCPeerConnection creation
	this.createRTCPeerConnection = function() {
		traceVC("RTCPeerConnection...");
		try {
			this.pc = new RTCPeerConnection(ICE_SERVERS);
			this.pc.addStream(this.localStream);
			this.pc.onicecandidate = this.onIceCandidateCallback;
			this.pc.onaddstream = this.onRemoteStreamAddedCallback;
			this.pc.onremovestream = this.onRemoteStreamRemovedCallback;

			traceVC('RTCPeerConnnection created');
		} catch (e) {
			traceVC('RTCPeerConnection failed: ' + e.message);
		}
	};

	// onIceCandidate callback
	this.onIceCandidateCallback = function(event) {
		var iceData, iceDataAsmessage, candidate = event.candidate;

		if (candidate) {
			iceData = {
				sdpMLineIndex: candidate.sdpMLineIndex,
				candidate: candidate.candidate,
				sdpMid: candidate.sdpMid
			};

			iceDataAsmessage = self.signalingService.xmppDictionaryToText(iceData);

			if (self.state == QBVideoChatState.INACTIVE)
				self.candidatesQueue.push(iceDataAsmessage);
			else {
				// Send ICE candidate to opponent
				self.signalingService.sendCandidate(self.opponentID, iceDataAsmessage, self.sessionID);
			}
		}
	};

	// onRemoteStreamAdded callback
	this.onRemoteStreamAddedCallback = function(event) {
		traceVC('Remote stream added');
		attachMediaStream(self.remoteStreamElement, event.stream);
		self.remoteStream = event.stream;
	};

	// onRemoteStreamRemoved callback
	this.onRemoteStreamRemovedCallback = function(event) {
		traceVC('Remote stream removed');
	};

	// Set LocalDescription
	this.onGetSessionDescriptionSuccessCallback = function(sessionDescription) {
		traceVC('LocalDescription...');

		self.pc.setLocalDescription(sessionDescription,

                                function onSuccess() {
                                  traceVC('LocalDescription success');
                                  self.localSessionDescription = sessionDescription;

                                  // ICE gathering starts work here
                                  if (sessionDescription.type === 'offer')
                                    self.sendCallRequest();
                                  else if (sessionDescription.type === 'answer')
                                    self.sendAceptRequest();
                                },

                                function onError(error) {
                                  traceVC('LocalDescription error: ' + error);
                                }
		);
	};

	this.onCreateOfferFailureCallback = function(event) {
		traceVC('createOffer() error: ', event);
	};

	// Set RemoteDescription
	this.setRemoteDescription = function(descriptionSDP, descriptionType) {
		traceVC('RemoteDescription...');
		var sessionDescription, candidate;

		this.state = QBVideoChatState.ESTABLISHING;
		sessionDescription = new RTCSessionDescription({sdp: descriptionSDP, type: descriptionType});

		this.pc.setRemoteDescription(sessionDescription,

                                 function onSuccess() {
                                   traceVC("RemoteDescription success");

                                   if (sessionDescription.type === 'offer')
                                     self.pc.createAnswer(self.onGetSessionDescriptionSuccessCallback, self.onCreateAnswerFailureCallback, SDP_CONSTRAINTS);
                                 },

                                 function onError(error) {
                                   traceVC('RemoteDescription error: ' + error);
                                 }
		);

		// send candidates
		for (var i = 0; i < this.candidatesQueue.length; i++) {
			candidate = this.candidatesQueue.pop();
			self.signalingService.sendCandidate(self.opponentID, candidate, self.sessionID);
		}
	};

	this.onCreateAnswerFailureCallback = function(event) {
		traceVC('createAnswer() error: ', event);
	};

	this.sendCallRequest = function() {
		// Send only string representation of sdp
		// http://www.w3.org/TR/webrtc/#rtcsessiondescription-class

		self.signalingService.call(self.opponentID, self.localSessionDescription.sdp, self.sessionID);
	};

	this.sendAceptRequest = function() {
		// Send only string representation of sdp
		// http://www.w3.org/TR/webrtc/#rtcsessiondescription-class

		self.signalingService.accept(self.opponentID, self.localSessionDescription.sdp, self.sessionID);
	};

	// Cleanup
	this.hangup = function() {
		traceVC("Closed RTC");
		self.pc.close();
		self.pc = null;
	};
}

// Call to user
QBVideoChat.prototype.call = function(userID) {
	if (this.localSessionDescription) return;

	this.opponentID = userID;
	this.pc.createOffer(this.onGetSessionDescriptionSuccessCallback, this.onCreateOfferFailureCallback);
};

// Accept call from user
QBVideoChat.prototype.accept = function(userID) {
	this.opponentID = userID;
	this.setRemoteDescription(this.remoteSessionDescription, "offer");
};

// Reject call from user
QBVideoChat.prototype.reject = function(userID) {
	traceVC("reject");
	this.signalingService.reject(userID, this.sessionID);

	this.state = QBVideoChatState.INACTIVE;
};

// Stap call with user
QBVideoChat.prototype.stop = function(userID) {
	traceVC("stop");
	this.signalingService.stops(userID, "manual", this.sessionID);

	this.state = QBVideoChatState.INACTIVE;
};

function traceVC(text) {
	console.log("[qb_videochat]: " + text);
}<commit_msg>small fix<commit_after>/**
 * QuickBlox VideoChat WebRTC library
 * version 0.1.0
 *
 * Author: Igor Khomenko (igor@quickblox.com)
 *
 */

/*
  Public methods:
    - call(userID)
    - accept(userID)
    - reject(userID)
    - stop(userID)

  Public callbacks:
    - onCall(fromUserID, sessionDescription)
    - onAccept(fromUserID, sessionDescription)
    - onReject(fromUserID)
    - onStop(fromUserID, reason)
    - onCandidate(fromUserID, candidate)
 */

var SDP_CONSTRAINTS = {
	'mandatory': {
		'OfferToReceiveAudio': true,
		'OfferToReceiveVideo': true
	}
};

var QBVideoChatState = {
	INACTIVE: 'inactive',
	ESTABLISHING: 'establishing',
	ACTIVE: 'active'
};

function QBVideoChat(constraints, localStreamElement, remoteStreamElement, signalingService, sessionID) {
 	var self = this;

	this.candidatesQueue = [];
	this.remoteSessionDescription = null;
	this.onGetUserMediaSuccess = null;
	this.onGetUserMediaError = null;
	this.state = QBVideoChatState.INACTIVE;

	this.constraints = constraints;
	this.localStreamElement = localStreamElement;
	this.remoteStreamElement = remoteStreamElement;

	this.sessionID = sessionID || new Date().getTime();
	traceVC("sessionID " + this.sessionID);

	// Signalling callbacks
	this.addCandidate = function(data) {
		var jsonCandidate, candidate;

		jsonCandidate = self.signalingService.xmppTextToDictionary(data);
		candidate = new RTCIceCandidate(jsonCandidate);

		self.pc.addIceCandidate(candidate);
	};

	this.onAcceptSignalingCallback = function(sessionDescription) {
		self.setRemoteDescription(sessionDescription, "answer"); //TODO: refactor this (hide)
	};

	this.signalingService = signalingService;
	this.signalingService.onCandidateCallback = this.addCandidate;
	this.signalingService.addOnAcceptCallback(this.onAcceptSignalingCallback);

	// MediaStream getUserMedia
	this.getUserMedia = function() {
		traceVC("getUserMedia...");

		getUserMedia(this.constraints, successCallback, errorCallback);

		function successCallback(localMediaStream) {
			traceVC("getUserMedia success");
			attachMediaStream(self.localStreamElement, localMediaStream);
			self.localStream = localMediaStream;
			self.createRTCPeerConnection();
			self.onGetUserMediaSuccess();
		}

		function errorCallback(error) {
			traceVC("getUserMedia error: ", error);
			self.onGetUserMediaSuccess();
		}
	};

	// RTCPeerConnection creation
	this.createRTCPeerConnection = function() {
		traceVC("RTCPeerConnection...");
		try {
			this.pc = new RTCPeerConnection(ICE_SERVERS);
			this.pc.addStream(this.localStream);
			this.pc.onicecandidate = this.onIceCandidateCallback;
			this.pc.onaddstream = this.onRemoteStreamAddedCallback;
			this.pc.onremovestream = this.onRemoteStreamRemovedCallback;

			traceVC('RTCPeerConnnection created');
		} catch (e) {
			traceVC('RTCPeerConnection failed: ' + e.message);
		}
	};

	// onIceCandidate callback
	this.onIceCandidateCallback = function(event) {
		var iceData, iceDataAsmessage, candidate = event.candidate;

		if (candidate) {
			iceData = {
				sdpMLineIndex: candidate.sdpMLineIndex,
				candidate: candidate.candidate,
				sdpMid: candidate.sdpMid
			};

			iceDataAsmessage = self.signalingService.xmppDictionaryToText(iceData);

			if (self.state == QBVideoChatState.INACTIVE)
				self.candidatesQueue.push(iceDataAsmessage);
			else {
				// Send ICE candidate to opponent
				self.signalingService.sendCandidate(self.opponentID, iceDataAsmessage, self.sessionID);
			}
		}
	};

	// onRemoteStreamAdded callback
	this.onRemoteStreamAddedCallback = function(event) {
		traceVC('Remote stream added');
		attachMediaStream(self.remoteStreamElement, event.stream);
		self.remoteStream = event.stream;
	};

	// onRemoteStreamRemoved callback
	this.onRemoteStreamRemovedCallback = function(event) {
		traceVC('Remote stream removed');
	};

	// Set LocalDescription
	this.onGetSessionDescriptionSuccessCallback = function(sessionDescription) {
		traceVC('LocalDescription...');

		self.pc.setLocalDescription(sessionDescription,

                                function onSuccess() {
                                  traceVC('LocalDescription success');
                                  self.localSessionDescription = sessionDescription;

                                  // ICE gathering starts work here
                                  if (sessionDescription.type === 'offer')
                                    self.sendCallRequest();
                                  else if (sessionDescription.type === 'answer')
                                    self.sendAceptRequest();
                                },

                                function onError(error) {
                                  traceVC('LocalDescription error: ' + error);
                                }
		);
	};

	this.onCreateOfferFailureCallback = function(event) {
		traceVC('createOffer() error: ', event);
	};

	// Set RemoteDescription
	this.setRemoteDescription = function(descriptionSDP, descriptionType) {
		traceVC('RemoteDescription...');
		var sessionDescription, candidate;

		this.state = QBVideoChatState.ESTABLISHING;
		sessionDescription = new RTCSessionDescription({sdp: descriptionSDP, type: descriptionType});

		this.pc.setRemoteDescription(sessionDescription,

                                 function onSuccess() {
                                   traceVC("RemoteDescription success");

                                   if (sessionDescription.type === 'offer')
                                     self.pc.createAnswer(self.onGetSessionDescriptionSuccessCallback, self.onCreateAnswerFailureCallback, SDP_CONSTRAINTS);
                                 },

                                 function onError(error) {
                                   traceVC('RemoteDescription error: ' + error);
                                 }
		);

		// send candidates
		for (var i = 0; i < this.candidatesQueue.length; i++) {
			candidate = this.candidatesQueue.pop();
			self.signalingService.sendCandidate(self.opponentID, candidate, self.sessionID);
		}
	};

	this.onCreateAnswerFailureCallback = function(event) {
		traceVC('createAnswer() error: ', event);
	};

	this.sendCallRequest = function() {
		// Send only string representation of sdp
		// http://www.w3.org/TR/webrtc/#rtcsessiondescription-class

		self.signalingService.call(self.opponentID, self.localSessionDescription.sdp, self.sessionID);
	};

	this.sendAceptRequest = function() {
		// Send only string representation of sdp
		// http://www.w3.org/TR/webrtc/#rtcsessiondescription-class

		self.signalingService.accept(self.opponentID, self.localSessionDescription.sdp, self.sessionID);
	};

	// Cleanup
	this.hangup = function() {
		traceVC("Closed RTC");
		self.pc.close();
		self.pc = null;
	};
}

// Call to user
QBVideoChat.prototype.call = function(userID) {
	if (this.localSessionDescription) return;

	this.opponentID = userID;
	this.pc.createOffer(this.onGetSessionDescriptionSuccessCallback, this.onCreateOfferFailureCallback);
};

// Accept call from user
QBVideoChat.prototype.accept = function(userID) {
	this.opponentID = userID;
	this.setRemoteDescription(this.remoteSessionDescription, "offer");
	this.state = QBVideoChatState.ESTABLISHING;
};

// Reject call from user
QBVideoChat.prototype.reject = function(userID) {
	traceVC("reject");
	this.signalingService.reject(userID, this.sessionID);

	this.state = QBVideoChatState.INACTIVE;
};

// Stap call with user
QBVideoChat.prototype.stop = function(userID) {
	traceVC("stop");
	this.signalingService.stops(userID, "manual", this.sessionID);

	this.state = QBVideoChatState.INACTIVE;
};

function traceVC(text) {
	console.log("[qb_videochat]: " + text);
}<|endoftext|>