<commit_before>describe('The dp-map directive', function () {
    var $compile,
        $rootScope,
        L,
        layers,
        highlight,
        panning,
        zoom,
        variableWidth,
        searchByClick,
        mockedMapState;

    beforeEach(function () {
        angular.mock.module(
            'dpMap',
            {
                mapConfig: {
                    MAP_OPTIONS: {
                        doThisThing: false,
                        someVariable: 4
                    }
                },
                panning: {
                    initialize: function () {},
                    panTo: function () {}
                },
                zoom: {
                    initialize: function () {},
                    setZoom: function () {}
                },
                searchByClick: {
                    initialize: function () {}
                }
            },
            function ($provide) {
                $provide.factory('dpLinkDirective', function () {
                    return {};
                });
            }
        );

        angular.mock.inject(function (
            _$compile_, _$rootScope_, _L_, _layers_, _highlight_, _panning_, _zoom_, _variableWidth_, _searchByClick_) {
                $compile = _$compile_;
                $rootScope = _$rootScope_;
                L = _L_;
                layers = _layers_;
                highlight = _highlight_;
                panning = _panning_;
                zoom = _zoom_;
                variableWidth = _variableWidth_;
                searchByClick = _searchByClick_;
            }
        );

        spyOn(L, 'map').and.returnValue('I_AM_A_FAKE_LEAFLET_MAP');

        spyOn(layers, 'setBaseLayer');
        spyOn(layers, 'addOverlay');
        spyOn(layers, 'removeOverlay');

        spyOn(highlight, 'add');
        spyOn(highlight, 'remove');

        spyOn(panning, 'initialize');
        spyOn(panning, 'panTo');
        spyOn(zoom, 'initialize');
        spyOn(zoom, 'setZoom');
        spyOn(variableWidth, 'initialize');
        spyOn(searchByClick, 'initialize');

        mockedMapState = {
            baseLayer: 'topografie',
            overlays: {},
            viewCenter: [52.789, 4.123],
            zoom: 12
        };
    });

    function getDirective (mapState, markers) {
        var directive,
            element,
            scope;

        element = document.createElement('dp-map');
        element.setAttribute('map-state', 'mapState');
        element.setAttribute('markers', 'markers');

        scope = $rootScope.$new();
        scope.mapState = mapState;
        scope.markers = markers;

        directive = $compile(element)(scope);
        scope.$apply();

        return directive;
    }

    it('creates a Leaflet map with options based on both the map state and mapConfig', function () {
        var directive,
            element;

        directive = getDirective(mockedMapState, []);
        element = directive[0].querySelector('.js-leaflet-map');

        expect(L.map).toHaveBeenCalledWith(element, {
            center: [52.789, 4.123],
            zoom: 12,
            doThisThing: false,
            someVariable: 4
        });
    });

    describe('has a base layer which', function () {
        it('is set on initialization', function () {
            getDirective(mockedMapState, []);

            expect(layers.setBaseLayer).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'topografie');
        });

        it('changes when the mapState changes', function () {
            getDirective(mockedMapState, []);
            expect(layers.setBaseLayer).toHaveBeenCalledTimes(1);

            mockedMapState.baseLayer = 'luchtfoto_2015';
            $rootScope.$apply();

            expect(layers.setBaseLayer).toHaveBeenCalledTimes(2);
            expect(layers.setBaseLayer).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'luchtfoto_2015');
        });
    });

    describe('has overlays which', function () {
        it('can be added on initialization', function () {
            mockedMapState.overlays = {'some_overlay': true};
            getDirective(mockedMapState, []);
            expect(layers.addOverlay).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'some_overlay');
        });

        it('can be added when the mapState changes', function () {
            getDirective(mockedMapState, []);
            expect(layers.addOverlay).not.toHaveBeenCalled();

            mockedMapState.overlays = {'some_overlay': true, 'some_other_overlay': true};
            $rootScope.$apply();

            expect(layers.addOverlay).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'some_overlay');
            expect(layers.addOverlay).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'some_other_overlay');
        });

        it('can be removed when the mapState changes', function () {
            mockedMapState.overlays = {'some_overlay': true, 'some_other_overlay': true};
            getDirective(mockedMapState, []);

            expect(layers.removeOverlay).not.toHaveBeenCalled();

            mockedMapState.overlays = {};
            $rootScope.$apply();

            expect(layers.removeOverlay).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'some_overlay');
            expect(layers.removeOverlay).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'some_other_overlay');
        });
    });

    describe('has markers which', function () {
        it('can be added on initialisation', function () {
            getDirective(mockedMapState, [{id: 'FAKE_HIGHLIGHT_ITEM_A'}, {id: 'FAKE_HIGHLIGHT_ITEM_B'}]);

            expect(highlight.add).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {id: 'FAKE_HIGHLIGHT_ITEM_A'});
            expect(highlight.add).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {id: 'FAKE_HIGHLIGHT_ITEM_B'});
        });

        it('can be added by changing the input', function () {
            var highlightItems = [{id: 'FAKE_HIGHLIGHT_ITEM_A'}, {id: 'FAKE_HIGHLIGHT_ITEM_B'}];

            getDirective(mockedMapState, highlightItems);

            highlightItems.push({id: 'FAKE_HIGHLIGHT_ITEM_C'});
            $rootScope.$apply();

            expect(highlight.add).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {id: 'FAKE_HIGHLIGHT_ITEM_C'});
        });

        it('can be removed from the map', function () {
            var highlightItems = [{id: 'FAKE_HIGHLIGHT_ITEM_A'}, {id: 'FAKE_HIGHLIGHT_ITEM_B'}];

            getDirective(mockedMapState, highlightItems);

            highlightItems.pop();
            $rootScope.$apply();

            expect(highlight.remove).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {id: 'FAKE_HIGHLIGHT_ITEM_B'});

        });

        it('deletes and re-adds changed icons', function () {
            var highlightItems = [{id: 'FAKE_HIGHLIGHT_ITEM_A', geometry: 'FAKE_GEOMETRY_A'}];

            getDirective(mockedMapState, highlightItems);

            expect(highlight.add).toHaveBeenCalledTimes(1);
            expect(highlight.add).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {
                id: 'FAKE_HIGHLIGHT_ITEM_A',
                geometry: 'FAKE_GEOMETRY_A'
            });
            expect(highlight.remove).not.toHaveBeenCalled();

            //Change the marker
            highlightItems[0].geometry = 'FAKE_GEOMETRY_B';
            $rootScope.$apply();

            expect(highlight.remove).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {
                id: 'FAKE_HIGHLIGHT_ITEM_A',
                geometry: 'FAKE_GEOMETRY_A'
            });

            expect(highlight.add).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {
                id: 'FAKE_HIGHLIGHT_ITEM_A',
                geometry: 'FAKE_GEOMETRY_B'
            });
        });
    });

    describe('panning factory', function () {
        var directive,
            container;

        beforeEach(function () {
            directive = getDirective(mockedMapState, []);
            container = directive[0].querySelector('.js-leaflet-map');
        });

        it('is initialized', function () {
            expect(panning.initialize).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP');
        });

        it('is called whenever mapState.viewCenter changes', function () {
            expect(panning.panTo).toHaveBeenCalledTimes(1);
            expect(panning.panTo).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', [52.789, 4.123]);

            mockedMapState.viewCenter = [53, 5];
            $rootScope.$apply();

            expect(panning.panTo).toHaveBeenCalledTimes(2);
            expect(panning.panTo).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', [53, 5]);
        });
    });

    describe('zoom factory', function () {
        var directive,
            container;

        beforeEach(function () {
            directive = getDirective(mockedMapState, []);
            container = directive[0].querySelector('.js-leaflet-map');
        });

        it('is initialized', function () {
            expect(zoom.initialize).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP');
        });

        it('is called whenever mapState.zoom changes', function () {
            expect(zoom.setZoom).toHaveBeenCalledTimes(1);
            expect(zoom.setZoom).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 12);

            mockedMapState.zoom = 11;
            $rootScope.$apply();

            expect(zoom.setZoom).toHaveBeenCalledTimes(2);
            expect(zoom.setZoom).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 11);
        });
    });

    it('initializes the variableWidth factory', function () {
        var directive,
            container;

        directive = getDirective(mockedMapState, []);
        container = directive[0].querySelector('.js-leaflet-map');

        expect(variableWidth.initialize).toHaveBeenCalledWith(container, 'I_AM_A_FAKE_LEAFLET_MAP');
    });

    it('initializes the searchByClick factory', function () {
        getDirective(mockedMapState, []);

        expect(searchByClick.initialize).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP');
    });
});<commit_msg>Adding statusbar mockup to map directive test<commit_after>describe('The dp-map directive', function () {
    var $compile,
        $rootScope,
        L,
        layers,
        highlight,
        panning,
        zoom,
        variableWidth,
        searchByClick,
        mockedMapState;

    beforeEach(function () {
        angular.mock.module(
            'dpMap',
            {
                store: {
                    dispatch: function () {}
                },
                mapConfig: {
                    MAP_OPTIONS: {
                        doThisThing: false,
                        someVariable: 4
                    }
                },
                panning: {
                    initialize: function () {},
                    panTo: function () {}
                },
                zoom: {
                    initialize: function () {},
                    setZoom: function () {}
                },
                searchByClick: {
                    initialize: function () {}
                }
            },

            function ($provide) {
                $provide.factory('dpLinkDirective', function () {
                    return {};
                });
                $provide.factory('dpMapStatusbarComponent', function () {
                    return {};
                });
            }
        );

        angular.mock.inject(function (
            _$compile_, _$rootScope_, _L_, _layers_, _highlight_, _panning_, _zoom_, _variableWidth_, _searchByClick_) {
                $compile = _$compile_;
                $rootScope = _$rootScope_;
                L = _L_;
                layers = _layers_;
                highlight = _highlight_;
                panning = _panning_;
                zoom = _zoom_;
                variableWidth = _variableWidth_;
                searchByClick = _searchByClick_;
            }
        );

        spyOn(L, 'map').and.returnValue('I_AM_A_FAKE_LEAFLET_MAP');

        spyOn(layers, 'setBaseLayer');
        spyOn(layers, 'addOverlay');
        spyOn(layers, 'removeOverlay');
        //spyOn(layers, 'toggleVisibility');
        spyOn(highlight, 'add');
        spyOn(highlight, 'remove');

        spyOn(panning, 'initialize');
        spyOn(panning, 'panTo');
        spyOn(zoom, 'initialize');
        spyOn(zoom, 'setZoom');
        spyOn(variableWidth, 'initialize');
        spyOn(searchByClick, 'initialize');

        mockedMapState = {
            baseLayer: 'topografie',
            overlays: {},
            viewCenter: [52.789, 4.123],
            zoom: 12
        };
    });

    function getDirective (mapState, markers) {
        var directive,
            element,
            scope;

        element = document.createElement('dp-map');
        element.setAttribute('map-state', 'mapState');
        element.setAttribute('markers', 'markers');

        scope = $rootScope.$new();
        scope.mapState = mapState;
        scope.markers = markers;

        directive = $compile(element)(scope);
        scope.$apply();

        return directive;
    }

    it('creates a Leaflet map with options based on both the map state and mapConfig', function () {
        var directive,
            element;

        directive = getDirective(mockedMapState, []);
        element = directive[0].querySelector('.js-leaflet-map');

        expect(L.map).toHaveBeenCalledWith(element, {
            center: [52.789, 4.123],
            zoom: 12,
            doThisThing: false,
            someVariable: 4
        });
    });

    describe('has a base layer which', function () {
        it('is set on initialization', function () {
            getDirective(mockedMapState, []);

            expect(layers.setBaseLayer).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'topografie');
        });

        it('changes when the mapState changes', function () {
            getDirective(mockedMapState, []);
            expect(layers.setBaseLayer).toHaveBeenCalledTimes(1);

            mockedMapState.baseLayer = 'luchtfoto_2015';
            $rootScope.$apply();

            expect(layers.setBaseLayer).toHaveBeenCalledTimes(2);
            expect(layers.setBaseLayer).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'luchtfoto_2015');
        });
    });

    describe('has overlays which', function () {
        it('can be added on initialization', function () {
            mockedMapState.overlays = {'some_overlay': true};
            getDirective(mockedMapState, []);
            expect(layers.addOverlay).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'some_overlay');
        });

        it('can be added when the mapState changes', function () {
            getDirective(mockedMapState, []);
            expect(layers.addOverlay).not.toHaveBeenCalled();

            mockedMapState.overlays = {'some_overlay': true, 'some_other_overlay': true};
            $rootScope.$apply();

            expect(layers.addOverlay).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'some_overlay');
            expect(layers.addOverlay).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'some_other_overlay');
        });

        it('can be removed when the mapState changes', function () {
            mockedMapState.overlays = {'some_overlay': true, 'some_other_overlay': true};
            getDirective(mockedMapState, []);

            expect(layers.removeOverlay).not.toHaveBeenCalled();

            mockedMapState.overlays = {};
            $rootScope.$apply();

            expect(layers.removeOverlay).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'some_overlay');
            expect(layers.removeOverlay).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 'some_other_overlay');
        });
    });

    describe('has markers which', function () {
        it('can be added on initialisation', function () {
            getDirective(mockedMapState, [{id: 'FAKE_HIGHLIGHT_ITEM_A'}, {id: 'FAKE_HIGHLIGHT_ITEM_B'}]);

            expect(highlight.add).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {id: 'FAKE_HIGHLIGHT_ITEM_A'});
            expect(highlight.add).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {id: 'FAKE_HIGHLIGHT_ITEM_B'});
        });

        it('can be added by changing the input', function () {
            var highlightItems = [{id: 'FAKE_HIGHLIGHT_ITEM_A'}, {id: 'FAKE_HIGHLIGHT_ITEM_B'}];

            getDirective(mockedMapState, highlightItems);

            highlightItems.push({id: 'FAKE_HIGHLIGHT_ITEM_C'});
            $rootScope.$apply();

            expect(highlight.add).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {id: 'FAKE_HIGHLIGHT_ITEM_C'});
        });

        it('can be removed from the map', function () {
            var highlightItems = [{id: 'FAKE_HIGHLIGHT_ITEM_A'}, {id: 'FAKE_HIGHLIGHT_ITEM_B'}];

            getDirective(mockedMapState, highlightItems);

            highlightItems.pop();
            $rootScope.$apply();

            expect(highlight.remove).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {id: 'FAKE_HIGHLIGHT_ITEM_B'});

        });

        it('deletes and re-adds changed icons', function () {
            var highlightItems = [{id: 'FAKE_HIGHLIGHT_ITEM_A', geometry: 'FAKE_GEOMETRY_A'}];

            getDirective(mockedMapState, highlightItems);

            expect(highlight.add).toHaveBeenCalledTimes(1);
            expect(highlight.add).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {
                id: 'FAKE_HIGHLIGHT_ITEM_A',
                geometry: 'FAKE_GEOMETRY_A'
            });
            expect(highlight.remove).not.toHaveBeenCalled();

            //Change the marker
            highlightItems[0].geometry = 'FAKE_GEOMETRY_B';
            $rootScope.$apply();

            expect(highlight.remove).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {
                id: 'FAKE_HIGHLIGHT_ITEM_A',
                geometry: 'FAKE_GEOMETRY_A'
            });

            expect(highlight.add).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', {
                id: 'FAKE_HIGHLIGHT_ITEM_A',
                geometry: 'FAKE_GEOMETRY_B'
            });
        });
    });

    describe('panning factory', function () {
        var directive,
            container;

        beforeEach(function () {
            directive = getDirective(mockedMapState, []);
            container = directive[0].querySelector('.js-leaflet-map');
        });

        it('is initialized', function () {
            expect(panning.initialize).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP');
        });

        it('is called whenever mapState.viewCenter changes', function () {
            expect(panning.panTo).toHaveBeenCalledTimes(1);
            expect(panning.panTo).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', [52.789, 4.123]);

            mockedMapState.viewCenter = [53, 5];
            $rootScope.$apply();

            expect(panning.panTo).toHaveBeenCalledTimes(2);
            expect(panning.panTo).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', [53, 5]);
        });
    });

    describe('zoom factory', function () {
        var directive,
            container;

        beforeEach(function () {
            directive = getDirective(mockedMapState, []);
            container = directive[0].querySelector('.js-leaflet-map');
        });

        it('is initialized', function () {
            expect(zoom.initialize).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP');
        });

        it('is called whenever mapState.zoom changes', function () {
            expect(zoom.setZoom).toHaveBeenCalledTimes(1);
            expect(zoom.setZoom).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 12);

            mockedMapState.zoom = 11;
            $rootScope.$apply();

            expect(zoom.setZoom).toHaveBeenCalledTimes(2);
            expect(zoom.setZoom).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP', 11);
        });
    });

    it('initializes the variableWidth factory', function () {
        var directive,
            container;

        directive = getDirective(mockedMapState, []);
        container = directive[0].querySelector('.js-leaflet-map');

        expect(variableWidth.initialize).toHaveBeenCalledWith(container, 'I_AM_A_FAKE_LEAFLET_MAP');
    });

    it('initializes the searchByClick factory', function () {
        getDirective(mockedMapState, []);

        expect(searchByClick.initialize).toHaveBeenCalledWith('I_AM_A_FAKE_LEAFLET_MAP');
    });
});<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {

  var Preferences = options.Preferences;
  /////////////////////////////////////////////////////////////////////////////
  // PrefCheckbox class:

  // Define a constructor that uses an input element as its underlying element.
  var PrefCheckbox = cr.ui.define('input');

  PrefCheckbox.prototype = {
    // Set up the prototype chain
    __proto__: HTMLInputElement.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      this.type = 'checkbox';
      var self = this;

      // Listen to pref changes.
      Preferences.getInstance().addEventListener(this.pref,
          function(event) {
            self.checked = event.value['value'] ? event.value['value']
                                                : event.value;
            self.managed = event.value['managed'] ? event.value['managed']
                                                  : false;
            self.disabled = self.managed;
          });

      // Listen to user events.
      this.addEventListener('click',
          function(e) {
            Preferences.setBooleanPref(self.pref, self.checked, self.metric);
          });
    }
  };

  /**
   * The preference name.
   * @type {string}
   */
  cr.defineProperty(PrefCheckbox, 'pref', cr.PropertyKind.ATTR);

  /**
   * The user metric string.
   * @type {string}
   */
  cr.defineProperty(PrefCheckbox, 'metric', cr.PropertyKind.ATTR);

  /////////////////////////////////////////////////////////////////////////////
  // PrefRadio class:

  //Define a constructor that uses an input element as its underlying element.
  var PrefRadio = cr.ui.define('input');

  PrefRadio.prototype = {
    // Set up the prototype chain
    __proto__: HTMLInputElement.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      this.type = 'radio';
      var self = this;

      // Listen to pref changes.
      Preferences.getInstance().addEventListener(this.pref,
          function(event) {
            var value = event.value['value'] ? event.value['value']
                                             : event.value;
            self.managed = event.value['managed'] ? event.value['managed']
                                                  : false;
            self.checked = String(value) == self.value;
            self.disabled = self.managed;
          });

      // Listen to user events.
      this.addEventListener('change',
          function(e) {
            if(self.value == 'true' || self.value == 'false') {
              Preferences.setBooleanPref(self.pref,
                  self.value == 'true', self.metric);
            } else {
              Preferences.setIntegerPref(self.pref,
                  parseInt(self.value, 10), self.metric);
            }
          });
    },

    /**
     * Getter for preference name attribute.
     */
    get pref() {
      return this.getAttribute('pref');
    },

    /**
     * Setter for preference name attribute.
     */
    set pref(name) {
      this.setAttribute('pref', name);
    }
  };

  /**
   * The user metric string.
   * @type {string}
   */
  cr.defineProperty(PrefRadio, 'metric', cr.PropertyKind.ATTR);

  /////////////////////////////////////////////////////////////////////////////
  // PrefNumeric class:

  // Define a constructor that uses an input element as its underlying element.
  var PrefNumeric = function() {};
  PrefNumeric.prototype = {
    // Set up the prototype chain
    __proto__: HTMLInputElement.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      var self = this;

      // Listen to pref changes.
      Preferences.getInstance().addEventListener(this.pref,
          function(event) {
            self.value = event.value['value'] ? event.value['value']
                                              : event.value;
            self.managed = event.value['managed'] ? event.value['managed']
                                                  : false;
            self.disabled = self.managed;
          });

      // Listen to user events.
      this.addEventListener('change',
          function(e) {
            Preferences.setIntegerPref(self.pref, self.value, self.metric);
          });
    }
  };

  /**
   * The preference name.
   * @type {string}
   */
  cr.defineProperty(PrefNumeric, 'pref', cr.PropertyKind.ATTR);

  /**
   * The user metric string.
   * @type {string}
   */
  cr.defineProperty(PrefNumeric, 'metric', cr.PropertyKind.ATTR);

  /////////////////////////////////////////////////////////////////////////////
  // PrefNumber class:

  // Define a constructor that uses an input element as its underlying element.
  var PrefNumber = cr.ui.define('input');

  PrefNumber.prototype = {
    // Set up the prototype chain
    __proto__: PrefNumeric.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      this.type = 'number';
      PrefNumeric.prototype.decorate.call(this);
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // PrefRange class:

  // Define a constructor that uses an input element as its underlying element.
  var PrefRange = cr.ui.define('input');

  PrefRange.prototype = {
    // Set up the prototype chain
    __proto__: PrefNumeric.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      this.type = 'range';
      PrefNumeric.prototype.decorate.call(this);
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // PrefSelect class:

  // Define a constructor that uses an select element as its underlying element.
  var PrefSelect = cr.ui.define('select');

  PrefSelect.prototype = {
    // Set up the prototype chain
    __proto__: HTMLSelectElement.prototype,

    /**
    * Initialization function for the cr.ui framework.
    */
    decorate: function() {
      var self = this;
      // Listen to pref changes.
      Preferences.getInstance().addEventListener(this.pref,
          function(event) {
            var value = event.value['value'] ? event.value['value']
                                             : event.value;
            self.managed = event.value['managed'] ? event.value['managed']
                                                  : false;
            self.disabled = self.managed;
            for (var i = 0; i < self.options.length; i++) {
              if (self.options[i].value == value) {
                self.selectedIndex = i;
                return;
              }
            }
            // Item not found, select first item.
            self.selectedIndex = 0;
          });

      // Listen to user events.
      this.addEventListener('change',
          function(e) {
            switch(self.dataType) {
              case 'number':
                Preferences.setIntegerPref(self.pref,
                    self.options[self.selectedIndex].value, self.metric);
                break;
              case 'boolean':
                Preferences.setBooleanValue(self.pref,
                    self.options[self.selectedIndex].value, self.metric);
                break;
              case 'string':
                Preferences.setStringPref(self.pref,
                    self.options[self.selectedIndex].value, self.metric);
                break;
            }
          });

      // Initialize options.
      this.ownerDocument.addEventListener('DOMContentLoaded',
          function() {
            var values = self.getAttribute('data-values');
            if (values) {
              self.initializeValues(templateData[values]);
            }
          });
    },

    /**
     * Sets up options in select element.
     * @param {Array} options List of option and their display text.
     * Each element in the array is an array of length 2 which contains options
     * value in the first element and display text in the second element.
     *
     * TODO(zelidrag): move this to that i18n template classes.
     */
    initializeValues: function(options) {
      options.forEach(function (values) {
        if (this.dataType == undefined)
          this.dataType = typeof values[0];
        this.appendChild(new Option(values[1], values[0]));
      }, this);
    }
  };

  /**
   * The preference name.
   * @type {string}
   */
  cr.defineProperty(PrefSelect, 'pref', cr.PropertyKind.ATTR);

  /**
   * The user metric string.
   * @type {string}
   */
  cr.defineProperty(PrefSelect, 'metric', cr.PropertyKind.ATTR);

  /////////////////////////////////////////////////////////////////////////////
  // PrefTextField class:

  // Define a constructor that uses an input element as its underlying element.
  var PrefTextField = cr.ui.define('input');

  PrefTextField.prototype = {
    // Set up the prototype chain
    __proto__: HTMLInputElement.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      var self = this;

      // Listen to pref changes.
      Preferences.getInstance().addEventListener(this.pref,
          function(event) {
            self.value = event.value['value'] ? event.value['value']
                                              : event.value;
            self.managed = event.value['managed'] ? event.value['managed']
                                                  : false;
            self.disabled = self.managed;
          });

      // Listen to user events.
      this.addEventListener('change',
          function(e) {
            Preferences.setStringPref(self.pref, self.value, self.metric);
          });

      window.addEventListener('unload',
          function() {
            if (document.activeElement == self)
              self.blur();
          });
    }
  };

  /**
   * The preference name.
   * @type {string}
   */
  cr.defineProperty(PrefTextField, 'pref', cr.PropertyKind.ATTR);

  /**
   * The user metric string.
   * @type {string}
   */
  cr.defineProperty(PrefTextField, 'metric', cr.PropertyKind.ATTR);

  // Export
  return {
    PrefCheckbox: PrefCheckbox,
    PrefNumber: PrefNumber,
    PrefNumeric: PrefNumeric,
    PrefRadio: PrefRadio,
    PrefRange: PrefRange,
    PrefSelect: PrefSelect,
    PrefTextField: PrefTextField
  };

});

<commit_msg>dom-ui options: Fix incorrect handling of undefined values in pref UI.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {

  var Preferences = options.Preferences;
  /////////////////////////////////////////////////////////////////////////////
  // PrefCheckbox class:

  // Define a constructor that uses an input element as its underlying element.
  var PrefCheckbox = cr.ui.define('input');

  PrefCheckbox.prototype = {
    // Set up the prototype chain
    __proto__: HTMLInputElement.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      this.type = 'checkbox';
      var self = this;

      // Listen to pref changes.
      Preferences.getInstance().addEventListener(this.pref,
          function(event) {
            self.checked = event.value['value'] != undefined ?
                event.value['value'] : event.value;
            self.managed = event.value['managed'] != undefined ?
                event.value['managed'] : false;
            self.disabled = self.managed;
          });

      // Listen to user events.
      this.addEventListener('click',
          function(e) {
            Preferences.setBooleanPref(self.pref, self.checked, self.metric);
          });
    }
  };

  /**
   * The preference name.
   * @type {string}
   */
  cr.defineProperty(PrefCheckbox, 'pref', cr.PropertyKind.ATTR);

  /**
   * The user metric string.
   * @type {string}
   */
  cr.defineProperty(PrefCheckbox, 'metric', cr.PropertyKind.ATTR);

  /////////////////////////////////////////////////////////////////////////////
  // PrefRadio class:

  //Define a constructor that uses an input element as its underlying element.
  var PrefRadio = cr.ui.define('input');

  PrefRadio.prototype = {
    // Set up the prototype chain
    __proto__: HTMLInputElement.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      this.type = 'radio';
      var self = this;

      // Listen to pref changes.
      Preferences.getInstance().addEventListener(this.pref,
          function(event) {
            var value = event.value['value'] != undefined ?
                event.value['value'] : event.value;
            self.managed = event.value['managed'] != undefined ?
                event.value['managed'] : false;
            self.checked = String(value) == self.value;
            self.disabled = self.managed;
          });

      // Listen to user events.
      this.addEventListener('change',
          function(e) {
            if(self.value == 'true' || self.value == 'false') {
              Preferences.setBooleanPref(self.pref,
                  self.value == 'true', self.metric);
            } else {
              Preferences.setIntegerPref(self.pref,
                  parseInt(self.value, 10), self.metric);
            }
          });
    },

    /**
     * Getter for preference name attribute.
     */
    get pref() {
      return this.getAttribute('pref');
    },

    /**
     * Setter for preference name attribute.
     */
    set pref(name) {
      this.setAttribute('pref', name);
    }
  };

  /**
   * The user metric string.
   * @type {string}
   */
  cr.defineProperty(PrefRadio, 'metric', cr.PropertyKind.ATTR);

  /////////////////////////////////////////////////////////////////////////////
  // PrefNumeric class:

  // Define a constructor that uses an input element as its underlying element.
  var PrefNumeric = function() {};
  PrefNumeric.prototype = {
    // Set up the prototype chain
    __proto__: HTMLInputElement.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      var self = this;

      // Listen to pref changes.
      Preferences.getInstance().addEventListener(this.pref,
          function(event) {
            self.value = event.value['value'] != undefined ?
                event.value['value'] : event.value;
            self.managed = event.value['managed'] != undefined ?
                event.value['managed'] : false;
            self.disabled = self.managed;
          });

      // Listen to user events.
      this.addEventListener('change',
          function(e) {
            Preferences.setIntegerPref(self.pref, self.value, self.metric);
          });
    }
  };

  /**
   * The preference name.
   * @type {string}
   */
  cr.defineProperty(PrefNumeric, 'pref', cr.PropertyKind.ATTR);

  /**
   * The user metric string.
   * @type {string}
   */
  cr.defineProperty(PrefNumeric, 'metric', cr.PropertyKind.ATTR);

  /////////////////////////////////////////////////////////////////////////////
  // PrefNumber class:

  // Define a constructor that uses an input element as its underlying element.
  var PrefNumber = cr.ui.define('input');

  PrefNumber.prototype = {
    // Set up the prototype chain
    __proto__: PrefNumeric.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      this.type = 'number';
      PrefNumeric.prototype.decorate.call(this);
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // PrefRange class:

  // Define a constructor that uses an input element as its underlying element.
  var PrefRange = cr.ui.define('input');

  PrefRange.prototype = {
    // Set up the prototype chain
    __proto__: PrefNumeric.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      this.type = 'range';
      PrefNumeric.prototype.decorate.call(this);
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // PrefSelect class:

  // Define a constructor that uses an select element as its underlying element.
  var PrefSelect = cr.ui.define('select');

  PrefSelect.prototype = {
    // Set up the prototype chain
    __proto__: HTMLSelectElement.prototype,

    /**
    * Initialization function for the cr.ui framework.
    */
    decorate: function() {
      var self = this;
      // Listen to pref changes.
      Preferences.getInstance().addEventListener(this.pref,
          function(event) {
            var value = event.value['value'] != undefined ?
                event.value['value'] : event.value;
            self.managed = event.value['managed'] != undefined ?
                event.value['managed'] : false;
            self.disabled = self.managed;
            for (var i = 0; i < self.options.length; i++) {
              if (self.options[i].value == value) {
                self.selectedIndex = i;
                return;
              }
            }
            // Item not found, select first item.
            self.selectedIndex = 0;
          });

      // Listen to user events.
      this.addEventListener('change',
          function(e) {
            switch(self.dataType) {
              case 'number':
                Preferences.setIntegerPref(self.pref,
                    self.options[self.selectedIndex].value, self.metric);
                break;
              case 'boolean':
                Preferences.setBooleanValue(self.pref,
                    self.options[self.selectedIndex].value, self.metric);
                break;
              case 'string':
                Preferences.setStringPref(self.pref,
                    self.options[self.selectedIndex].value, self.metric);
                break;
            }
          });

      // Initialize options.
      this.ownerDocument.addEventListener('DOMContentLoaded',
          function() {
            var values = self.getAttribute('data-values');
            if (values) {
              self.initializeValues(templateData[values]);
            }
          });
    },

    /**
     * Sets up options in select element.
     * @param {Array} options List of option and their display text.
     * Each element in the array is an array of length 2 which contains options
     * value in the first element and display text in the second element.
     *
     * TODO(zelidrag): move this to that i18n template classes.
     */
    initializeValues: function(options) {
      options.forEach(function (values) {
        if (this.dataType == undefined)
          this.dataType = typeof values[0];
        this.appendChild(new Option(values[1], values[0]));
      }, this);
    }
  };

  /**
   * The preference name.
   * @type {string}
   */
  cr.defineProperty(PrefSelect, 'pref', cr.PropertyKind.ATTR);

  /**
   * The user metric string.
   * @type {string}
   */
  cr.defineProperty(PrefSelect, 'metric', cr.PropertyKind.ATTR);

  /////////////////////////////////////////////////////////////////////////////
  // PrefTextField class:

  // Define a constructor that uses an input element as its underlying element.
  var PrefTextField = cr.ui.define('input');

  PrefTextField.prototype = {
    // Set up the prototype chain
    __proto__: HTMLInputElement.prototype,

    /**
     * Initialization function for the cr.ui framework.
     */
    decorate: function() {
      var self = this;

      // Listen to pref changes.
      Preferences.getInstance().addEventListener(this.pref,
          function(event) {
            self.value = event.value['value'] != undefined ?
                event.value['value'] : event.value;
            self.managed = event.value['managed'] != undefined ?
                event.value['managed'] : false;
            self.disabled = self.managed;
          });

      // Listen to user events.
      this.addEventListener('change',
          function(e) {
            Preferences.setStringPref(self.pref, self.value, self.metric);
          });

      window.addEventListener('unload',
          function() {
            if (document.activeElement == self)
              self.blur();
          });
    }
  };

  /**
   * The preference name.
   * @type {string}
   */
  cr.defineProperty(PrefTextField, 'pref', cr.PropertyKind.ATTR);

  /**
   * The user metric string.
   * @type {string}
   */
  cr.defineProperty(PrefTextField, 'metric', cr.PropertyKind.ATTR);

  // Export
  return {
    PrefCheckbox: PrefCheckbox,
    PrefNumber: PrefNumber,
    PrefNumeric: PrefNumeric,
    PrefRadio: PrefRadio,
    PrefRange: PrefRange,
    PrefSelect: PrefSelect,
    PrefTextField: PrefTextField
  };

});

<|endoftext|>


<commit_before>L.PolyLine.mergeOptions({
    polylineGrab: false
});

L.Handler.PolylineGrab = L.Handler.extend({

    includes: L.Mixin.Events,

    options: {
        overlapRadius: 15, // pixels
        markerFactory: null
    },

    initialize: function (map) {
        if (map.almostOver === undefined) {
            throw 'Leaflet.AlmostOver handler is required on this map.';
        }
        this._map = map;
        this._dragging = false;
        this._attached = [];
        this._marker = null;
        this._snap = null;
        this._layers = [];
    },

    addHooks: function () {
        this._toggleAlmostEvent(true);
        this.on('attach', this._onAttach, this);
        this.on('detach', this._onDetach, this);
    },

    removeHooks: function () {
        this.off('attach', this._onAttach, this);
        this.off('detach', this._onDetach, this);
        this._toggleAlmostEvent(false);
    },

    addGuideLayer: function (l) {
        this._layers.push(l);
    },

    _toggleAlmostEvent: function (state) {
        var method = state ? 'on' : 'off';
        this._map[method]('almost:over', this._onAlmostOver, this);
        this._map[method]('almost:move', this._onAlmostMove, this);
        this._map[method]('almost:out', this._onAlmostOut, this);
    },

    _onAttach: function (e) {
        this._attached.push(e.marker);
    },

    _onDetach: function (e) {
        var idx = this._attached.indexOf(e.marker);
        this._attached.splice(idx, 1);
    },

    _onAlmostOver: function (e) {
        if (this.options.markerFactory) {
            this._marker = this.options.markerFactory(e.latlng);
        }
        else {
            // Default marker and icon
            var grabIcon = L.divIcon({className: 'grab-icon'});
            this._marker = L.marker(e.latlng, {icon: grabIcon});
        }
        this._marker.attached = false;
        this._marker.on('dragstart', this._onDragStart, this);
        this._marker.on('dragend', this._onDragEnd, this);
        this._marker.on('click', this._onClick, this);
    },

    _onAlmostMove: function (e) {
        // Hide current marker when approaching the ones already attached.
        for (var i=0, n=this._attached.length; i<n; i++) {
            var attached = this._attached[i],
                space = L.GeometryUtil.distance(this._map,
                                                attached.getLatLng(),
                                                e.latlng);
            if (space < this.options.overlapRadius) {
                this._map.removeLayer(this._marker);
                return;
            }
        }
        // No attached marker around
        if (i == n) {
            this._map.addLayer(this._marker);
            this._marker.dragging = new L.Handler.MarkerDrag(this._marker);
            this._marker.dragging.enable();
        }
        this._marker.setLatLng(e.latlng);
    },

    _onAlmostOut: function (e) {
        this._marker.off('dragstart', this._onDragStart, this);
        this._marker.off('dragend', this._onDragEnd, this);
        this._marker.off('click', this._onClick, this);
        this._map.removeLayer(this._marker);
        this._marker = null;
    },

    // When marker starts dragging :
    //  - ignore map mouse moves
    //  - detach if was attached
    //  - initialize snapping if new marker
    _onDragStart: function (e) {
        this._toggleAlmostEvent(false);

        var marker = e.target;

        if (!!marker.attached) {
            this._detach(marker);
        }
        else {
            marker.snapediting = new L.Handler.MarkerSnap(this._map, marker, {snapVertices: false});
            for (var i=0, n=this._layers.length; i<n; i++) {
                marker.snapediting.addGuideLayer(this._layers[i]);
            }
        }
        marker.snapediting.enable();
        marker.on('snap', this._onSnap, this);
        marker.on('unsnap', this._onUnsnap, this);
        // Don't listen to click while dragging
        marker.off('click', this._onClick, this);
    },

    _onSnap: function (e) {
        this._snap = e.layer;
    },

    _onUnsnap: function (e) {
        this._snap = null;
    },

    // When marker dragging stops :
    //  - 'attach' and start again if marker was snapped
    //  - 'detach' if marker was previously attached
    _onDragEnd: function (e) {
        var marker = e.target;
        marker.snapediting.disable();
        marker.off('snap', this._onSnap, this);
        marker.off('unsnap', this._onUnsnap, this);

        if (this._snap) {
            this._attach(marker, this._snap);
            // Start over with new marker
            this._onAlmostOver({latlng: marker.getLatLng()});
        }
        else {
            this._map.removeLayer(marker);
        }
        this._toggleAlmostEvent(true);
    },

    _attach: function (marker, layer) {
        marker.attached = true;
        this.fire('attach', {marker: marker, layer: layer});
        if (marker._icon) L.DomUtil.addClass(marker._icon, 'marker-attached');

        // Detach on click
        marker.on('click', function (e) {
            this._detach(marker);
            this._map.removeLayer(e.target);
        }, this);
    },

    _detach: function (marker) {
        marker.attached = false;
        this.fire('detach', {marker: marker});
        if (marker._icon) L.DomUtil.removeClass(marker._icon, 'marker-attached');
    },

    _onClick: function (e) {
        // Simulate drag-snap on click
        var marker = e.target;
        this._onDragStart(e);
        marker.fire('move');
        this._onDragEnd(e);
    },
});

L.Map.addInitHook('addHandler', 'polylineGrab', L.Handler.PolylineGrab);
<commit_msg>Move from map handler to polyline mixin<commit_after>L.Handler.PolylineGrab = L.Handler.extend({

    includes: L.Mixin.Events,

    options: {
        overlapRadius: 15, // pixels
        markerFactory: null
    },

    initialize: function (map) {
        L.Handler.prototype.initialize.call(this, map);

        if (map.almostOver === undefined) {
            throw 'Leaflet.AlmostOver handler is required on this map.';
        }
        this._dragging = false;
        this._attached = [];
        this._marker = null;
        this._snap = null;
        this._layers = [];
    },

    addHooks: function () {
        this._toggleAlmostEvent(true);
        this.on('attach', this._onAttach, this);
        this.on('detach', this._onDetach, this);
    },

    removeHooks: function () {
        this.off('attach', this._onAttach, this);
        this.off('detach', this._onDetach, this);
        this._toggleAlmostEvent(false);
    },

    addGuideLayer: function (l) {
        this._layers.push(l);
    },

    _toggleAlmostEvent: function (state) {
        var method = state ? 'on' : 'off';
        this._map[method]('almost:over', this._onAlmostOver, this);
        this._map[method]('almost:move', this._onAlmostMove, this);
        this._map[method]('almost:out', this._onAlmostOut, this);
    },

    _onAttach: function (e) {
        this._attached.push(e.marker);
    },

    _onDetach: function (e) {
        var idx = this._attached.indexOf(e.marker);
        this._attached.splice(idx, 1);
    },

    _onAlmostOver: function (e) {
        if (this.options.markerFactory) {
            this._marker = this.options.markerFactory(e.latlng);
        }
        else {
            // Default marker and icon
            var grabIcon = L.divIcon({className: 'grab-icon'});
            this._marker = L.marker(e.latlng, {icon: grabIcon});
        }
        this._marker.attached = false;
        this._marker.on('dragstart', this._onDragStart, this);
        this._marker.on('dragend', this._onDragEnd, this);
        this._marker.on('click', this._onClick, this);
    },

    _onAlmostMove: function (e) {
        // Hide current marker when approaching the ones already attached.
        for (var i=0, n=this._attached.length; i<n; i++) {
            var attached = this._attached[i],
                space = L.GeometryUtil.distance(this._map,
                                                attached.getLatLng(),
                                                e.latlng);
            if (space < this.options.overlapRadius) {
                this._map.removeLayer(this._marker);
                return;
            }
        }
        // No attached marker around
        if (i == n) {
            this._map.addLayer(this._marker);
            this._marker.dragging = new L.Handler.MarkerDrag(this._marker);
            this._marker.dragging.enable();
        }
        this._marker.setLatLng(e.latlng);
    },

    _onAlmostOut: function (e) {
        this._marker.off('dragstart', this._onDragStart, this);
        this._marker.off('dragend', this._onDragEnd, this);
        this._marker.off('click', this._onClick, this);
        this._map.removeLayer(this._marker);
        this._marker = null;
    },

    // When marker starts dragging :
    //  - ignore map mouse moves
    //  - detach if was attached
    //  - initialize snapping if new marker
    _onDragStart: function (e) {
        this._toggleAlmostEvent(false);

        var marker = e.target;

        if (!!marker.attached) {
            this._detach(marker);
        }
        else {
            marker.snapediting = new L.Handler.MarkerSnap(this._map, marker, {snapVertices: false});
            for (var i=0, n=this._layers.length; i<n; i++) {
                marker.snapediting.addGuideLayer(this._layers[i]);
            }
        }
        marker.snapediting.enable();
        marker.on('snap', this._onSnap, this);
        marker.on('unsnap', this._onUnsnap, this);
        // Don't listen to click while dragging
        marker.off('click', this._onClick, this);
    },

    _onSnap: function (e) {
        this._snap = e.layer;
    },

    _onUnsnap: function (e) {
        this._snap = null;
    },

    // When marker dragging stops :
    //  - 'attach' and start again if marker was snapped
    //  - 'detach' if marker was previously attached
    _onDragEnd: function (e) {
        var marker = e.target;
        marker.snapediting.disable();
        marker.off('snap', this._onSnap, this);
        marker.off('unsnap', this._onUnsnap, this);

        if (this._snap) {
            this._attach(marker, this._snap);
            // Start over with new marker
            this._onAlmostOver({latlng: marker.getLatLng()});
        }
        else {
            this._map.removeLayer(marker);
        }
        this._toggleAlmostEvent(true);
    },

    _attach: function (marker, layer) {
        marker.attached = true;
        this.fire('attach', {marker: marker, layer: layer});
        if (marker._icon) L.DomUtil.addClass(marker._icon, 'marker-attached');

        // Detach on click
        marker.on('click', function (e) {
            this._detach(marker);
            this._map.removeLayer(e.target);
        }, this);
    },

    _detach: function (marker) {
        marker.attached = false;
        this.fire('detach', {marker: marker});
        if (marker._icon) L.DomUtil.removeClass(marker._icon, 'marker-attached');
    },

    _onClick: function (e) {
        // Simulate drag-snap on click
        var marker = e.target;
        this._onDragStart(e);
        marker.fire('move');
        this._onDragEnd(e);
    },
});

L.Polyline.mergeOptions({
    polylineGrab: false
});

L.PolylineGrabMixin = {
    __onAdd: L.Polyline.prototype.onAdd,
    __onRemove: L.Polyline.prototype.onRemove,

    onAdd: function (map) {
        this.__onAdd.call(this, map);

        this.polylineGrab = new L.Handler.PolylineGrab(map);
        if (this.options.polylineGrab) {
            this.polylineGrab.enable();
        }
    },

    onRemove: function (map) {
        this.polylineGrab.disable();
        this.__onRemove.call(this, map);
    },
};

L.Polyline.include(L.PolylineGrabMixin);
<|endoftext|>


<commit_before>var
    esPhinx,
    Iterable;

(function($) {
    "use strict";

    $.prototype.extend({

        autocomplete: function(elementsList, options, callback) {
            var
                charactersNumber,
                searchTextBox = this,
                nonCharacterKeysPattern = new RegExp($
                    .nonCharacterKeysPattern()),
                inline = false,
                elements2Recovery = [],
                afterAmountCharacters = options.afterAmountChar,

                fillInToRecovery = function(object, times) {
                    var
                        i = 0;

                    while (i++ < Math.abs(times)) {
                        elements2Recovery.push(object);
                    }
                },

                resolveArguments = function(options) {
                    if (Object.getPrototypeOf(options) !=
                        Object.getPrototypeOf({})) {
                        options = {};
                    }

                    if (typeof options.caseSensitive != "boolean") {
                        options.caseSensitive = false;
                    }

                    if (typeof options.orderlySearch != "boolean") {
                        options.orderlySearch = false;
                    }

                    if (typeof afterAmountCharacters != "number") {
                        afterAmountCharacters = 1;
                    }

                },

                inlineSearch = function(element, options) {
                    var
                        eventListenerMethod,
                        previousSearchText = searchTextBox.value();

                    if (typeof eventListenerMethod == "function") {
                        searchTextBox.off("input", eventListenerMethod);
                        searchTextBox.off("focus", eventListenerMethod);
                    }

                    eventListenerMethod = function(e) {
                        var
                            resolvedList,
                            resolvedElementsParent,
                            foundElements,
                            exclusionIndex,
                            finalIndex,
                            previousElements = element,
                            parent = element.clone(),
                            searchTextLength = searchTextBox.value().length,

                            restartList = function() {
                                previousElements = elements;
                            };

                        if (searchTextBox.value()) {
                            charactersNumber = previousSearchText.length -
                                searchTextLength;

                            exclusionIndex = searchTextBox.cursorPosition();
                            finalIndex = exclusionIndex + charactersNumber - 1;

                            // when delete
                            if (searchTextLength < previousSearchText.length &&
                                searchTextLength >= afterAmountCharacters) {

                                // debugger
                                if (exclusionIndex === 0) {
                                    elements2Recovery.delete(exclusionIndex,
                                        finalIndex);
                                } else {
                                    elements2Recovery.delete(exclusionIndex,
                                        elements2Recovery.lastIndex());
                                }

                                previousElements = elements2Recovery[
                                        elements2Recovery.lastIndex()];
                                // debugger
                            }

                            // debugger
                            resolvedList = resolveList(previousElements,
                                options.order);
                            foundElements = resolvedList.elements;

                            if (searchTextLength > afterAmountCharacters ||
                                afterAmountCharacters == 1) {

                                if (foundElements.some()) {
                                    if (charactersNumber < 0) {
                                        fillInToRecovery(parent
                                                         .append(foundElements),
                                                       charactersNumber);
                                    }

                                    previousElements = parent
                                        .append(foundElements);
                                } else {
                                    fillInToRecovery(parent
                                                     .append(previousElements),
                                                   charactersNumber);
                                }

                            }
                            // debugger

                            previousSearchText = searchTextBox.value();
                            callback.call($(this), foundElements, resolvedList
                                          .maps, e);
                        } else {
                            // reset
                            elements2Recovery = [];
                            previousSearchText = "";
                            previousElements = element;
                            callback.call($(this), $(), e);
                        }

                    };

                    searchTextBox.on("input", eventListenerMethod);
                    searchTextBox.on("focus", eventListenerMethod);
                },

                remoteSearch = function(options) {
                    var
                        word,
                        prevText,
                        nextText,
                        element,
                        URLParameters,
                        resolvedList,
                        clipboardData,

                        request = function(e) {
                            if (options.remote.URLParameters) {
                                URLParameters = options.remote.URLParameters
                                    .call(searchTextBox);
                            }

                            $.Ajax.new(options.remote.url.call(searchTextBox))
                                .get({
                                    URLParameters: URLParameters,
                                    progress: function(xhr) {
                                        if (options.remote.loading) {
                                            options.remote
                                                .loading(xhr, e);
                                        }
                                    },
                                    complete: function() {
                                        $(e.target).off("keypress");
                                    },
                                    success: function(r) {
                                        element = $(r);

                                        if (element.some()) {
                                            charactersNumber = (searchTextBox
                                                .value().length -
                                                afterAmountCharacters) + 1;

                                            fillInToRecovery(element,
                                                           charactersNumber);
                                        }

                                        resolvedList = resolveList(element,
                                                                options.order);
                                        callback.call(searchTextBox,
                                            resolvedList.elements,
                                            resolvedList.maps, e);
                                        if (element.length) {
                                            inlineSearch(element, options);
                                        }
                                    }
                                });
                        };

                    searchTextBox.on("keyup", function(e) {
                        word = searchTextBox.value();

                        if (word.length > afterAmountCharacters) {
                            inline = true;
                        } else if (word.length < afterAmountCharacters) {
                            inline = false;
                        }

                        if (word.length == afterAmountCharacters &&
                            !nonCharacterKeysPattern.test(e.key) &&
                            !inline &&
                            options.remote) {
                            $(e.target).on("keypress", function(e) {
                                e.preventDefault();
                            });

                            request(e);
                        }

                    });

                    searchTextBox.on("paste", function(e) {
                        word = searchTextBox.value();
                        prevText = word
                            .slice(0, searchTextBox.cursorPosition());
                        nextText = word
                            .slice(searchTextBox.selectionEnd(), word.length);

                        clipboardData = e.clipboardData.getData("text");

                        if (word.length >= afterAmountCharacters) {
                            inline = true;
                        } else {
                            inline = false;
                        }

                        word = prevText + clipboardData + nextText;

                        if (word.length >= afterAmountCharacters &&
                            !inline &&
                            options.remote) {
                            searchTextBox.value(word);

                            request(e);
                            e.preventDefault();
                        }
                    });

                },

                mapIf = function(searchTextAsArray, textNodeAsArray) {
                    var
                        iterator,
                        sliceIndex,
                        regexp,
                        textNodeHashSet = Object
                            .asCountableLiteralObject(textNodeAsArray),
                        mapped = {},
                        count = 0,
                        index = 0,
                        previousIndex = -1;

                    if (textNodeHashSet.length >= searchTextAsArray.length) {
                        iterator = Iterable.Proxy.new(searchTextAsArray);
                        iterator.each(function(slice) {
                            slice = slice.trim();
                            index = Object.firstFromASlice(textNodeHashSet,
                                                             slice, index,
                                                             options
                                                             .caseSensitive);

                            if (index && ((options.orderlySearch &&
                                index > previousIndex) ||
                                !options.orderlySearch) &&
                                textNodeAsArray.countSlice(slice,
                                    options.caseSensitive) >=
                                    searchTextAsArray.count(slice)) {

                                previousIndex = index;

                                if (options.caseSensitive) {
                                    regexp = new RegExp(slice);
                                } else {
                                    regexp = new RegExp(slice, "i");
                                }

                                sliceIndex = textNodeAsArray[index]
                                    .search(regexp);
                                mapped[index] = textNodeAsArray[index]
                                    .slice(sliceIndex, sliceIndex + slice
                                           .length);
                                Object.delete(textNodeHashSet, index);
                                count += 1;
                            } else {
                                this.finalize();
                            }
                        });

                        if (count == searchTextAsArray.length) {
                            return mapped;
                        }
                    }

                    return false;
                },

                // resolveList = function(list, order = "desc") {
                resolveList = function(list, order) {
                    if (order != "asc") {order = "desc";}
                    var
                        textNode,
                        mapped,
                        textNodeAsArray,
                        sorted,
                        found = {elements: $(), maps: []},
                        textBoxContentArr = searchTextBox.value().split(" ")
                            .compact();

                    if (list.elements().count() == 1 &&
                        list.isA(window.Element)) {
                        list = list.childElements().clone(true);
                    }

                    if (order == "asc") {
                        sorted = list.ascendingSortTextNode();
                    } else {
                        sorted = list.descendingSortTextNode();
                    }

                    sorted.each(function(element) {
                        textNode = $(element).textContent().trim();
                        textNodeAsArray = textNode.split(" ");
                        mapped = mapIf(textBoxContentArr, textNodeAsArray);
                        if (mapped) {
                            found.elements.push(element);
                            found.maps.push(mapped);
                        }
                    });

                    return found;
                };

            resolveArguments(options);

            // init
            if (Object.getPrototypeOf(elementsList) != Object.prototype) {
                inlineSearch(elementsList, options);
            } else {
                options = elementsList;
                remoteSearch(options);
            }
        }

    });

})(esPhinx);
<commit_msg>rename vars<commit_after>var
    esPhinx,
    Iterable;

(function($) {
    "use strict";

    $.prototype.extend({

        autocomplete: function(elementsList, options, callback) {
            var
                charactersNumber,
                searchTextBox = this,
                nonCharacterKeysPattern = new RegExp($
                    .nonCharacterKeysPattern()),
                inline = false,
                elements2Recovery = [],
                afterAmountCharacters = options.afterAmountChar,

                fillInToRecovery = function(object, times) {
                    var
                        i = 0;

                    while (i++ < Math.abs(times)) {
                        elements2Recovery.push(object);
                    }
                },

                resolveArguments = function(options) {
                    if (Object.getPrototypeOf(options) !=
                        Object.getPrototypeOf({})) {
                        options = {};
                    }

                    if (typeof options.caseSensitive != "boolean") {
                        options.caseSensitive = false;
                    }

                    if (typeof options.orderlySearch != "boolean") {
                        options.orderlySearch = false;
                    }

                    if (typeof afterAmountCharacters != "number") {
                        afterAmountCharacters = 1;
                    }

                },

                inlineSearch = function(element, options) {
                    var
                        eventListenerMethod,
                        previousSearchText = searchTextBox.value();

                    if (typeof eventListenerMethod == "function") {
                        searchTextBox.off("input", eventListenerMethod);
                        searchTextBox.off("focus", eventListenerMethod);
                    }

                    eventListenerMethod = function(e) {
                        var
                            resolvedList,
                            foundElements,
                            startingIndex,
                            finalIndex,
                            previousElement = element,
                            parent = element.clone(),
                            searchTextLength = searchTextBox.value().length;

                        if (searchTextBox.value()) {
                            charactersNumber = previousSearchText.length -
                                searchTextLength;

                            startingIndex = searchTextBox.cursorPosition();
                            finalIndex = startingIndex + charactersNumber - 1;

                            // when delete
                            if (searchTextLength < previousSearchText.length &&
                                searchTextLength >= afterAmountCharacters) {

                                // debugger
                                if (startingIndex === 0) {
                                    elements2Recovery.delete(startingIndex,
                                        finalIndex);
                                } else {
                                    elements2Recovery.delete(startingIndex,
                                        elements2Recovery.lastIndex());
                                }

                                previousElement = elements2Recovery[
                                        elements2Recovery.lastIndex()];
                                // debugger
                            }

                            // debugger
                            resolvedList = resolveList(previousElement,
                                options.order);
                            foundElements = resolvedList.elements;

                            if (searchTextLength > afterAmountCharacters ||
                                afterAmountCharacters == 1) {

                                if (foundElements.some()) {
                                    if (charactersNumber < 0) {
                                        fillInToRecovery(parent
                                                         .append(foundElements),
                                                       charactersNumber);
                                    }

                                    previousElement = parent
                                        .append(foundElements);
                                } else {
                                    fillInToRecovery(parent
                                                     .append(previousElement),
                                                   charactersNumber);
                                }

                            }
                            // debugger

                            previousSearchText = searchTextBox.value();
                            callback.call($(this), foundElements, resolvedList
                                          .maps, e);
                        } else {
                            // reset
                            elements2Recovery = [];
                            previousSearchText = "";
                            previousElement = element;
                            callback.call($(this), $(), e);
                        }

                    };

                    searchTextBox.on("input", eventListenerMethod);
                    searchTextBox.on("focus", eventListenerMethod);
                },

                remoteSearch = function(options) {
                    var
                        word,
                        prevText,
                        nextText,
                        element,
                        URLParameters,
                        resolvedList,
                        clipboardData,

                        request = function(e) {
                            if (options.remote.URLParameters) {
                                URLParameters = options.remote.URLParameters
                                    .call(searchTextBox);
                            }

                            $.Ajax.new(options.remote.url.call(searchTextBox))
                                .get({
                                    URLParameters: URLParameters,
                                    progress: function(xhr) {
                                        if (options.remote.loading) {
                                            options.remote
                                                .loading(xhr, e);
                                        }
                                    },
                                    complete: function() {
                                        $(e.target).off("keypress");
                                    },
                                    success: function(r) {
                                        element = $(r);

                                        if (element.some()) {
                                            charactersNumber = (searchTextBox
                                                .value().length -
                                                afterAmountCharacters) + 1;

                                            fillInToRecovery(element,
                                                           charactersNumber);
                                        }

                                        resolvedList = resolveList(element,
                                                                options.order);
                                        callback.call(searchTextBox,
                                            resolvedList.elements,
                                            resolvedList.maps, e);
                                        if (element.length) {
                                            inlineSearch(element, options);
                                        }
                                    }
                                });
                        };

                    searchTextBox.on("keyup", function(e) {
                        word = searchTextBox.value();

                        if (word.length > afterAmountCharacters) {
                            inline = true;
                        } else if (word.length < afterAmountCharacters) {
                            inline = false;
                        }

                        if (word.length == afterAmountCharacters &&
                            !nonCharacterKeysPattern.test(e.key) &&
                            !inline &&
                            options.remote) {
                            $(e.target).on("keypress", function(e) {
                                e.preventDefault();
                            });

                            request(e);
                        }

                    });

                    searchTextBox.on("paste", function(e) {
                        word = searchTextBox.value();
                        prevText = word
                            .slice(0, searchTextBox.cursorPosition());
                        nextText = word
                            .slice(searchTextBox.selectionEnd(), word.length);

                        clipboardData = e.clipboardData.getData("text");

                        if (word.length >= afterAmountCharacters) {
                            inline = true;
                        } else {
                            inline = false;
                        }

                        word = prevText + clipboardData + nextText;

                        if (word.length >= afterAmountCharacters &&
                            !inline &&
                            options.remote) {
                            searchTextBox.value(word);

                            request(e);
                            e.preventDefault();
                        }
                    });

                },

                mapIf = function(searchTextAsArray, textNodeAsArray) {
                    var
                        iterator,
                        sliceIndex,
                        regexp,
                        textNodeHashSet = Object
                            .asCountableLiteralObject(textNodeAsArray),
                        mapped = {},
                        count = 0,
                        index = 0,
                        previousIndex = -1;

                    if (textNodeHashSet.length >= searchTextAsArray.length) {
                        iterator = Iterable.Proxy.new(searchTextAsArray);
                        iterator.each(function(slice) {
                            slice = slice.trim();
                            index = Object.firstFromASlice(textNodeHashSet,
                                                             slice, index,
                                                             options
                                                             .caseSensitive);

                            if (index && ((options.orderlySearch &&
                                index > previousIndex) ||
                                !options.orderlySearch) &&
                                textNodeAsArray.countSlice(slice,
                                    options.caseSensitive) >=
                                    searchTextAsArray.count(slice)) {

                                previousIndex = index;

                                if (options.caseSensitive) {
                                    regexp = new RegExp(slice);
                                } else {
                                    regexp = new RegExp(slice, "i");
                                }

                                sliceIndex = textNodeAsArray[index]
                                    .search(regexp);
                                mapped[index] = textNodeAsArray[index]
                                    .slice(sliceIndex, sliceIndex + slice
                                           .length);
                                Object.delete(textNodeHashSet, index);
                                count += 1;
                            } else {
                                this.finalize();
                            }
                        });

                        if (count == searchTextAsArray.length) {
                            return mapped;
                        }
                    }

                    return false;
                },

                // resolveList = function(list, order = "desc") {
                resolveList = function(list, order) {
                    if (order != "asc") {order = "desc";}
                    var
                        textNode,
                        mapped,
                        textNodeAsArray,
                        sorted,
                        found = {elements: $(), maps: []},
                        textBoxContentArr = searchTextBox.value().split(" ")
                            .compact();

                    if (list.elements().count() == 1 &&
                        list.isA(window.Element)) {
                        list = list.childElements().clone(true);
                    }

                    if (order == "asc") {
                        sorted = list.ascendingSortTextNode();
                    } else {
                        sorted = list.descendingSortTextNode();
                    }

                    sorted.each(function(element) {
                        textNode = $(element).textContent().trim();
                        textNodeAsArray = textNode.split(" ");
                        mapped = mapIf(textBoxContentArr, textNodeAsArray);
                        if (mapped) {
                            found.elements.push(element);
                            found.maps.push(mapped);
                        }
                    });

                    return found;
                };

            resolveArguments(options);

            // init
            if (Object.getPrototypeOf(elementsList) != Object.prototype) {
                inlineSearch(elementsList, options);
            } else {
                options = elementsList;
                remoteSearch(options);
            }
        }

    });

})(esPhinx);
<|endoftext|>


<commit_before>// This object allows the user to perform multiple calculations over multiple cores
//

// Example usage:
// ScriptName="SimulationToRun.js";
// CommonData=[InfoBlock];//All sims will have access to this information
// SimSpecificDataArray=[67, 33, 99, 55, 88];//can be an array of any type (including other classes). Uses array length to determine the number of simulations to run.
// NoCores=6;//The number of cores you want the simulation to run over
// SimulationObject=new MulticoreSim(ScriptName, CommonData, SimSpecificDataArray, NoCores); // getting it ready
// SimulationObject.Start(); // Start the simulations running

// Sample set up of SimulationToRun.js
// ----------------------------------------------------------
// importScripts("usefulscripts1.js", "usefulscripts2.js");//Scripts your function needs to use (note; only scripts in the same folder can be used)
//
// self.onmessage = function (e) {
// 		var SimNumber = e.data.SimNumber;
// 		var SimData = e.data.SimData;
// 		var CommonData = e.data.CommonData;
//
//		...//Where you do the calculations
//
//		Result.Value1=24;//Stores the results
//		Result.Value2=25;
//
//		self.postMessage({SimNumber: e.data.SimNumber, Result: Result});//All simulations should end with this line
//}

function MulticoreSim(ScriptName, CommonData, SimDataArray, NoCores){
	console.log("Creating MulticoreSim object");

	this.ScriptName=ScriptName;
	this.CommonData=CommonData;
	this.SimDataArray=SimDataArray;//an array of values or objects to be passed to the specified script
	this.NoCores=NoCores;
	this.Worker=[];//An array of workers
	this.NoSims=SimDataArray.length;

	this.CurrentlyRunning=false;
	this.Complete=false;
	this.NoSimsCurrentlyRunning=0;

	this.SimsStarted=0;
	this.SimsComplete=0;
	this.Result=[];

	this.UseSimProgressBar=false;
	this.SimProgressBarID="SimProgressBar";//To allow a progress bar to be installed into the page
	this.UseWithinSimProgressBar=false;
	this.WithinSimProgressBarID="WithinSimProgressBar";

}

MulticoreSim.prototype.Start=function() {
	console.log("Starting MulticoreSim object");

	//Check that nothing else is running
	if (this.CurrentlyRunning==true){
		console.log("Warning: worker currently running");
		return 0;
	};
	this.CurrentlyRunning=true;
	this.NoSimsCurrentlyRunning=0;

	// Set progress bar to zero
	if (this.UseSimProgressBar==true){
		document.getElementById(this.NoSimsCompleteProgressBarID).value=0;
	}

	//Create workers
	this.RampUpSims();
};

MulticoreSim.prototype.RampUpSims=function() {
	console.log("Started rampup");
	while (this.NoSimsCurrentlyRunning<this.NoCores){//there are spare cores available
		if (this.SimsStarted<this.NoSims){//if there are sims that have yet to be started
			SimID=this.SimsStarted++;//run this sim, increment by 1
			this.NoSimsCurrentlyRunning++;//indicate that another core has become used
			console.log("Started sim: "+SimID);

			this.Worker= new Worker(this.ScriptName);
			var BoundHandler = MulticoreSimMessageHandler(this, null);
			this.Worker.onmessage = BoundHandler;
			//this.Worker.onmessage = function (e){MulticoreSimMessageHandler(e, this)};
			this.Worker.postMessage({ SimNumber: SimID, CommonData: this.CommonData, SimData: this.SimDataArray[SimID]});

		}
	}

	//Determine if this is the last sim to complete
	if (this.SimsComplete>=this.NoSims){
		this.Terminate();//close all the workers
	}
}

MulticoreSimMessageHandler=function(MulticoreSimObject, e) {
	// There are 3 main message types that are handled
	// Messages to the StatusText (to be put somewhere on screen to indicate what is currently occurring)
	// Messages to the ProgressBar
	// Message to return result/indicate completeness

	console.log("Mulit");
	console.log(MulticoreSimObject);

	// Messages to the StatusText
	if (typeof e.data.StatusText != 'undefined'){
		console.log(e.data.WorkerStatusText);
	}
	// Messages to the ProgressBar
	if (typeof e.data.ProgressBarValue != 'undefined'){
		if (MulticoreSimObject.UseSimProgressBar==true){
			document.getElementById(MulticoreSimObject.WithinSimProgressBarID).value=e.data.ProgressBarValue;
		}
	}
	if (typeof e.data.Result != 'undefined'){
		MulticoreSimObject.NoSimsCurrentlyRunning--;
		SimNumber=e.data.SimNumber;
		MulticoreSimObject.Result[SimNumber]=e.data.Result;//Store the results of the simulation
		MulticoreSimObject.SimsComplete++;

		MulticoreSimObject.RampUpSims();//Try to run more sims

		//Update the progress bar about completion
		if (MulticoreSimObject.UseSimProgressBar==true){
			document.getElementById(MulticoreSimObject.NoSimsCompleteProgressBarID).value=MulticoreSimObject.SimsComplete/MulticoreSimObject.NoSims;
		}
	}
};

MulticoreSim.prototype.Terminate=function() {//close down all workers
	this.Worker.terminate();
	this.CurrentlyRunning==false;
};

<commit_msg>Changing this<commit_after>// This object allows the user to perform multiple calculations over multiple cores
//

// Example usage:
// ScriptName="SimulationToRun.js";
// CommonData=[InfoBlock];//All sims will have access to this information
// SimSpecificDataArray=[67, 33, 99, 55, 88];//can be an array of any type (including other classes). Uses array length to determine the number of simulations to run.
// NoCores=6;//The number of cores you want the simulation to run over
// SimulationObject=new MulticoreSim(ScriptName, CommonData, SimSpecificDataArray, NoCores); // getting it ready
// SimulationObject.Start(); // Start the simulations running

// Sample set up of SimulationToRun.js
// ----------------------------------------------------------
// importScripts("usefulscripts1.js", "usefulscripts2.js");//Scripts your function needs to use (note; only scripts in the same folder can be used)
//
// self.onmessage = function (e) {
// 		var SimNumber = e.data.SimNumber;
// 		var SimData = e.data.SimData;
// 		var CommonData = e.data.CommonData;
//
//		...//Where you do the calculations
//
//		Result.Value1=24;//Stores the results
//		Result.Value2=25;
//
//		self.postMessage({SimNumber: e.data.SimNumber, Result: Result});//All simulations should end with this line
//}

function MulticoreSim(ScriptName, CommonData, SimDataArray, NoCores){
	console.log("Creating MulticoreSim object");

	this.ScriptName=ScriptName;
	this.CommonData=CommonData;
	this.SimDataArray=SimDataArray;//an array of values or objects to be passed to the specified script
	this.NoCores=NoCores;
	this.Worker=[];//An array of workers
	this.NoSims=SimDataArray.length;

	this.CurrentlyRunning=false;
	this.Complete=false;
	this.NoSimsCurrentlyRunning=0;

	this.SimsStarted=0;
	this.SimsComplete=0;
	this.Result=[];

	this.UseSimProgressBar=false;
	this.SimProgressBarID="SimProgressBar";//To allow a progress bar to be installed into the page
	this.UseWithinSimProgressBar=false;
	this.WithinSimProgressBarID="WithinSimProgressBar";

}

MulticoreSim.prototype.Start=function() {
	console.log("Starting MulticoreSim object");

	//Check that nothing else is running
	if (this.CurrentlyRunning==true){
		console.log("Warning: worker currently running");
		return 0;
	};
	this.CurrentlyRunning=true;
	this.NoSimsCurrentlyRunning=0;

	// Set progress bar to zero
	if (this.UseSimProgressBar==true){
		document.getElementById(this.NoSimsCompleteProgressBarID).value=0;
	}

	//Create workers
	this.RampUpSims();
};

MulticoreSim.prototype.RampUpSims=function() {
	console.log("Started rampup");
	while (this.NoSimsCurrentlyRunning<this.NoCores){//there are spare cores available
		if (this.SimsStarted<this.NoSims){//if there are sims that have yet to be started
			SimID=this.SimsStarted++;//run this sim, increment by 1
			this.NoSimsCurrentlyRunning++;//indicate that another core has become used
			console.log("Started sim: "+SimID);

			this.Worker= new Worker(this.ScriptName);
			var BoundHandler = MulticoreSimMessageHandler(this, null);
			this.Worker.onmessage = BoundHandler;
			//this.Worker.onmessage = function (e){MulticoreSimMessageHandler(e, this)};
			this.Worker.postMessage({ SimNumber: SimID, CommonData: this.CommonData, SimData: this.SimDataArray[SimID]});

		}
	}

	//Determine if this is the last sim to complete
	if (this.SimsComplete>=this.NoSims){
		this.Terminate();//close all the workers
	}
}

MulticoreSimMessageHandler=function(e) {
	// There are 3 main message types that are handled
	// Messages to the StatusText (to be put somewhere on screen to indicate what is currently occurring)
	// Messages to the ProgressBar
	// Message to return result/indicate completeness

	console.log("Mulit");
	console.log(this);

	// Messages to the StatusText
	if (typeof e.data.StatusText != 'undefined'){
		console.log(e.data.WorkerStatusText);
	}
	// Messages to the ProgressBar
	if (typeof e.data.ProgressBarValue != 'undefined'){
		if (this.UseSimProgressBar==true){
			document.getElementById(this.WithinSimProgressBarID).value=e.data.ProgressBarValue;
		}
	}
	if (typeof e.data.Result != 'undefined'){
		this.NoSimsCurrentlyRunning--;
		SimNumber=e.data.SimNumber;
		this.Result[SimNumber]=e.data.Result;//Store the results of the simulation
		this.SimsComplete++;

		this.RampUpSims();//Try to run more sims

		//Update the progress bar about completion
		if (this.UseSimProgressBar==true){
			document.getElementById(this.NoSimsCompleteProgressBarID).value=this.SimsComplete/this.NoSims;
		}
	}
};

MulticoreSim.prototype.Terminate=function() {//close down all workers
	this.Worker.terminate();
	this.CurrentlyRunning==false;
};

<|endoftext|>