<commit_before>define(["backbone", "underscore", "app-state", "utils"],
       function(B, _, appState, $u) {
           /**
            * @constructor
            * A collection that keeps track of which items are selected.
            *
            * Events:
            * - selection (collection, ids)
            *   Triggered when the selection changed
            *   ids: ids of all selected children, including those
            *   that have not yet been loaded.
            *
            * - selectionLoaded (collection, ids, loadedIds)
            *   Triggered when the entire selection is loaded (meaning that
            *   there is local data for id in the selection).
            *   ids: ids of all selected children
            *
            * - selectionRemoved (collection, ids, selectedIds)
            *   ids: ids of all deselected children
            *   selectedIds: ids of selected children
            *
            * - selectionAdded (collection, ids)
            *
            * - filtered (collection, models)
            *   Triggered when filters are applied
            *
            * - addedFiltered (model, collection)
            *   A model was added that matches the active filters
            *
            * - removedFiltered (model, collection)
            */
           var SelectableCollection = B.Collection.extend({

               initialize: function(models, options) {
                   B.Collection.prototype.initialize.call(this, models, options);

                   // The ids of the selected members that are loaded
                   // and available.
                   if (options && options.selection)
                       this.selection = options.selection;
                   else
                       this.selection = [];

                   // The ids of selected members that are not loaded
                   // yet.
                   this.pending = [];

                   this.on("add", this.onAdd, this)
                       .on("remove", this.onRemove, this);

                   if (this.hashParam) {
                       var self = this;
                       appState.onStateChange(this.hashParam, function(ids, oldIds) {
                           if (!ids) return;

                           ids = ids.split(",");
                           self._setSelection(ids);
                       });
                   }
               },

               getModelName: function() {
                   return this.model.modelName || "model";
               },

               setSelection: function(selection) {
                   if (!this.hashParam)
                       return this._setSelection(selection);

                   if (!_.isArray(selection))
                       selection = [selection];

                   appState.setHashKey(this.hashParam,
                                       selection.join(","));
                   return null;
               },

               /**
                * @param {number|number[]} selection An id or ids of the
                * model(s) to select.
                * @param {?boolean} add
                */
               _setSelection: function(selection, add) {
                   if (!_.isArray(selection))
                       selection = [selection];
                   if (add)
                       selection = _.union(this.selection, selection);

                   var deselect = _.difference(this.selection, selection);
                   _.each(deselect,
                          function(id) {
                              var member = this.get(id);
                              if (member)
                                  member.set("_selected", false);
                          },
                          this);
                   var select = _.difference(selection, this.selection),
                       pending = [];
                   _.each(select,
                          function(id) {
                              var member = this.get(id);
                              if (member)
                                  member.set("_selected", true);
                              else
                                  pending.push(id);
                          },
                          this);

                   pending = _.union(pending, this.pending);
                   this.pending = pending;
                   this.selection = _.difference(selection, pending);

                   if (select.length || deselect.length)
                       this.trigger("selection", this, selection);
                   if (select.length)
                       this.trigger("selectionAdded", this, select);
                   if (deselect.length)
                       this.trigger("selectionRemoved", this, deselect, select);

                   if (!pending.length)
                       this.trigger("selectionLoaded", this, selection, pending);

               },

               onAdd: function(model, coll) {
                   // Check if the added model is one we're waiting for:
                   if (_.contains(this.pending, model.id)) {
                       this.pending = _.without(this.pending, model.id);
                       this.selection.push(model.id);
                       this.trigger("selection", this, this.selection);

                       if (!this.pending.length)
                           this.trigger("selectionLoaded", this, this.selection,
                                        [model.id]);

                       model.set("_selected", true);
                   }

                   if (this.matchesFilters(model))
                       this.trigger("addedFiltered", model, coll);
               },

               onRemove: function(model, coll) {
                   if (this.matchesFilters(model))
                       this.trigger("removedFiltered", model, coll);
               },

               getSelectedIndex: function() {
                   var id = this.selection[0];

                   return id ?
                       _.findIndex(this.models, $u.idIs(id)) : -1;
               },

               selectRelative: function(dir) {
                   var fs = _.values(this.activeFilters), idx, model;

                   if (fs.length) {
                       var models = this.getFiltered(fs),
                           id = this.selection[0];

                       idx = _.findIndex(models, $u.idIs(id));

                       model = models[idx+dir] ||
                           dir < 0 ? _.last(models) : _.first(models);
                   } else {
                       idx = this.getSelectedIndex();

                       model = this.at(idx+dir) || this.at(dir < 0 ? -1 : 0);
                   }

                   if (model)
                       this.setSelection(model.id);
                   return model;
               },

               /*
                * @returns {?Model}
                */
               selectNext: function() {
                   this.selectRelative(1);
               },

               /*
                * @returns {?Model}
                */
               selectPrev: function() {
                   this.selectRelative(-1);
               },

               /**
                * @return {Proposal[]}
                */
               getSelection: function() {
                   return _.map(this.selection, this.get, this);
               },

               getSelectionIds: function() {
                   return this.selection;
               },

               // Filters:

               /**
                * Applies each of the functions in the array fs to the
                * proposals in the collection. If any of the functions
                * returns false, the Proposal will be updated: its "_excluded"
                * attribute will be set to true.
                *
                * @param {Array} fs
                */
               applyFilters: function(fs) {
                   return this.filter(function(model) {
                       var excluded = model.get("_excluded"),
                           shouldExclude = !$u.everyPred(fs, model);

                       // Is the model already excluded, and should it be?
                       if (excluded !== shouldExclude) {
                           model.set("_excluded", shouldExclude);
                       }

                       return !shouldExclude;
                   });
               },

               matchesFilters: function(model) {
                   var fs = _.values(this.activeFilters);

                   return $u.everyPred(fs, model);
               },

               getFiltered: function() {
                   return this.where({_excluded: false});
               },

               getVisible: function() {
                   return this.where({_excluded: false,
                                      _visible: true});
               },

               // A map of string filter names to functions
               activeFilters: {},

               // Reapply all of the active filters.
               refresh: function() {
                   var ms = this.applyFilters(_.values(this.activeFilters));
                   this.trigger("filtered", this, ms);
               },

               addFilter: function(name, f) {
                   this.activeFilters[name] = f;
                   this.refresh();
               },

               removeFilter: function(name) {
                   delete this.activeFilters[name];
                   this.refresh();
               },

               // Sorting

               /**
                * A map of fieldName -> comparator function
                *
                */
               comparators: {},

               /**
                * @param {String} name
                * @param {Boolean} desc true to sort descending
                */
               sortByField: function(name, desc) {
                   var order = desc ? -1 : 1;
                   this.sortField = name;
                   this.desc = desc;

                   if (!name) {
                       this.comparator = false;
                   } else if (this.comparators[name]) {
                       var cmp = this.comparators[name];
                       this.comparator = desc ?
                           (function(v1, v2) { return -cmp(); }) : cmp;
                       this.sort();
                   } else {
                       this.comparator = function(p1, p2) {
                           var v1 = p1.get(name),
                               v2 = p2.get(name);

                           return order * ((v1 > v2) ? 1 : (v2 > v1) ? -1 : 0);
                       };
                       this.sort();
                   }
               }
           });

           return SelectableCollection;
       });
<commit_msg>Bug fix: SelectableCollection<commit_after>define(["backbone", "underscore", "app-state", "utils"],
       function(B, _, appState, $u) {
           /**
            * @constructor
            * A collection that keeps track of which items are selected.
            *
            * Events:
            * - selection (collection, ids)
            *   Triggered when the selection changed
            *   ids: ids of all selected children, including those
            *   that have not yet been loaded.
            *
            * - selectionLoaded (collection, ids, loadedIds)
            *   Triggered when the entire selection is loaded (meaning that
            *   there is local data for id in the selection).
            *   ids: ids of all selected children
            *
            * - selectionRemoved (collection, ids, selectedIds)
            *   ids: ids of all deselected children
            *   selectedIds: ids of selected children
            *
            * - selectionAdded (collection, ids)
            *
            * - filtered (collection, models)
            *   Triggered when filters are applied
            *
            * - addedFiltered (model, collection)
            *   A model was added that matches the active filters
            *
            * - removedFiltered (model, collection)
            *
            * NOTE: Selection ids are always stored as strings.
            */
           var SelectableCollection = B.Collection.extend({

               initialize: function(models, options) {
                   B.Collection.prototype.initialize.call(this, models, options);

                   // The ids of the selected members that are loaded
                   // and available.
                   if (options && options.selection)
                       this.selection = options.selection;
                   else
                       this.selection = [];

                   // The ids of selected members that are not loaded
                   // yet.
                   this.pending = [];

                   this.on("add", this.onAdd, this)
                       .on("remove", this.onRemove, this);

                   if (this.hashParam) {
                       var self = this;
                       appState.onStateChange(this.hashParam, function(ids, oldIds) {
                           ids = ids ? ids.split(",") : [];
                           self._setSelection(ids);
                       });
                   }
               },

               getModelName: function() {
                   return this.model.modelName || "model";
               },

               setSelection: function(selection) {
                   if (!this.hashParam)
                       return this._setSelection(selection);

                   if (!_.isArray(selection))
                       selection = [selection];

                   appState.setHashKey(this.hashParam,
                                       selection.join(","));
                   return null;
               },

               /**
                * @param {number|number[]} selection An id or ids of the
                * model(s) to select.
                * @param {?boolean} add
                */
               _setSelection: function(selection, add) {
                   if (!_.isArray(selection))
                       selection = [selection];

                   if (add)
                       selection = _.union(this.selection, selection);
                   else
                       this.pending = [];

                   var deselect = _.difference(this.selection, selection);
                   _.each(deselect,
                          function(id) {
                              var member = this.get(id);
                              if (member)
                                  member.set("_selected", false);
                          },
                          this);
                   var select = _.difference(selection, this.selection),
                       pending = [];
                   _.each(select,
                          function(id) {
                              var member = this.get(id);
                              if (member)
                                  member.set("_selected", true);
                              else
                                  pending.push(id);
                          },
                          this);

                   pending = _.union(pending, this.pending);
                   this.pending = pending;
                   this.selection = _.difference(selection, pending);

                   if (select.length || deselect.length)
                       this.trigger("selection", this, selection);
                   if (select.length)
                       this.trigger("selectionAdded", this, select);
                   if (deselect.length)
                       this.trigger("selectionRemoved", this, deselect, select);

                   if (!pending.length)
                       this.trigger("selectionLoaded", this, selection, pending);

               },

               onAdd: function(model, coll) {
                   // Check if the added model is one we're waiting for:
                   var id = "" + model.id;
                   if (_.contains(this.pending, id)) {
                       this.pending = _.without(this.pending, id);
                       this.selection.push(id);
                       this.trigger("selection", this, this.selection);

                       if (!this.pending.length)
                           this.trigger("selectionLoaded", this, this.selection,
                                        [id]);

                       model.set("_selected", true);
                   }

                   if (this.matchesFilters(model))
                       this.trigger("addedFiltered", model, coll);
               },

               onRemove: function(model, coll) {
                   if (this.matchesFilters(model))
                       this.trigger("removedFiltered", model, coll);
               },

               getSelectedIndex: function() {
                   var id = this.selection[0];

                   return id ?
                       _.findIndex(this.models, $u.idIs(id)) : -1;
               },

               selectRelative: function(dir) {
                   var fs = _.values(this.activeFilters), idx, model;

                   if (fs.length) {
                       var models = this.getFiltered(fs),
                           id = this.selection[0];

                       idx = _.findIndex(models, $u.idIs(id));

                       model = models[idx+dir] ||
                           dir < 0 ? _.last(models) : _.first(models);
                   } else {
                       idx = this.getSelectedIndex();

                       model = this.at(idx+dir) || this.at(dir < 0 ? -1 : 0);
                   }

                   if (model)
                       this.setSelection("" + model.id);
                   return model;
               },

               /*
                * @returns {?Model}
                */
               selectNext: function() {
                   this.selectRelative(1);
               },

               /*
                * @returns {?Model}
                */
               selectPrev: function() {
                   this.selectRelative(-1);
               },

               /**
                * @return {Proposal[]}
                */
               getSelection: function() {
                   return _.map(this.selection, this.get, this);
               },

               getSelectionIds: function() {
                   return this.selection;
               },

               // Filters:

               /**
                * Applies each of the functions in the array fs to the
                * proposals in the collection. If any of the functions
                * returns false, the Proposal will be updated: its "_excluded"
                * attribute will be set to true.
                *
                * @param {Array} fs
                */
               applyFilters: function(fs) {
                   return this.filter(function(model) {
                       var excluded = model.get("_excluded"),
                           shouldExclude = !$u.everyPred(fs, model);

                       // Is the model already excluded, and should it be?
                       if (excluded !== shouldExclude) {
                           model.set("_excluded", shouldExclude);
                       }

                       return !shouldExclude;
                   });
               },

               matchesFilters: function(model) {
                   var fs = _.values(this.activeFilters);

                   return $u.everyPred(fs, model);
               },

               getFiltered: function() {
                   return this.where({_excluded: false});
               },

               getVisible: function() {
                   return this.where({_excluded: false,
                                      _visible: true});
               },

               // A map of string filter names to functions
               activeFilters: {},

               // Reapply all of the active filters.
               refresh: function() {
                   var ms = this.applyFilters(_.values(this.activeFilters));
                   this.trigger("filtered", this, ms);
               },

               addFilter: function(name, f) {
                   this.activeFilters[name] = f;
                   this.refresh();
               },

               removeFilter: function(name) {
                   delete this.activeFilters[name];
                   this.refresh();
               },

               // Sorting

               /**
                * A map of fieldName -> comparator function
                *
                */
               comparators: {},

               /**
                * @param {String} name
                * @param {Boolean} desc true to sort descending
                */
               sortByField: function(name, desc) {
                   var order = desc ? -1 : 1;
                   this.sortField = name;
                   this.desc = desc;

                   if (!name) {
                       this.comparator = false;
                   } else if (this.comparators[name]) {
                       var cmp = this.comparators[name];
                       this.comparator = desc ?
                           (function(v1, v2) { return -cmp(); }) : cmp;
                       this.sort();
                   } else {
                       this.comparator = function(p1, p2) {
                           var v1 = p1.get(name),
                               v2 = p2.get(name);

                           return order * ((v1 > v2) ? 1 : (v2 > v1) ? -1 : 0);
                       };
                       this.sort();
                   }
               }
           });

           return SelectableCollection;
       });
<|endoftext|>


<commit_before>define(['marionette', 'views/form',
    'collections/visits',
    'collections/labcontacts',
    'collections/shipments',
    'collections/dewars',
    'modules/shipment/collections/dewarhistory',

    'modules/shipment/models/dispatch',

    'templates/shipment/dispatch.html',
    'jquery',
    'backbone',
    'backbone-validation',

    ], function(Marionette, FormView,
        Visits, LabContacts, Shipments, Dewars, DewarHistory,
        DispatchModel,
        template, $_, Backbone) {

    var VVisits = Visits.extend({
        valueAttribute: 'VISIT',
    })

    return FormView.extend({
        template: template,

        events: {
            'change @ui.lc': 'getlcdetails',
            'change @ui.exp': 'updateLC',
            'click @ui.useAnotherCourierAccount': 'toggleCourierAccountDisplay'
        },

        ui: {
            lc: 'select[name=LABCONTACTID]',

            exp: 'select[name=VISIT]',
            lco: 'input[name=LOCALCONTACT]',
            loc: 'input[name=LOCATION]',

            gn: 'input[name=GIVENNAME]',
            fn: 'input[name=FAMILYNAME]',
            addr: 'textarea[name=ADDRESS]',
            em: 'input[name=EMAILADDRESS]',
            ph: 'input[name=PHONENUMBER]',
            lab: 'input[name=LABNAME]',

            courier: 'span.courier',
            useAnotherCourierAccount: 'input[name=USE_ANOTHER_COURIER_ACCOUNT]'
        },

        templateHelpers: function() {
            return {
                DEWAR: this.getOption('dewar').toJSON()
            }
        },

        createModel: function() {
            this.model = new DispatchModel({
                FACILITYCODE: this.getOption('dewar').get('FACILITYCODE'),
                DEWARID: this.getOption('dewar').get('DEWARID'),
                LABCONTACTID: this.getOption('dewar').get('LABCONTACTID'),
                VISIT: this.getOption('dewar').get('FIRSTEXPERIMENT')
            })
        },

        success: function(model, response, options) {
            console.log('success from dispatch req')
            app.trigger('shipment:show', this.getOption('dewar').get('SHIPPINGID'))
        },

        failure: function(model, response, options) {
            console.log('failure from dispatch req')
            app.alert({ message: 'Something went wrong registering this dispatch request, please try again'})
        },

        onRender: function() {
            this.date('input[name=DELIVERYAGENT_SHIPPINGDATE]')

            var d = new Date()
            var today = (d.getDate() < 10 ? '0'+d.getDate() : d.getDate()) + '-' + (d.getMonth() < 9 ? '0'+(d.getMonth()+1) : d.getMonth()+1) + '-' + d.getFullYear()
            this.$el.find('input[name=DELIVERYAGENT_SHIPPINGDATE]').val(today)

            this.ui.courier.html('<input type="text" name="DELIVERYAGENT_AGENTNAME" />')
            this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').val(this.dewar.get('DELIVERYAGENT_AGENTNAME'))
            this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').val(this.dewar.get('DELIVERYAGENT_AGENTCODE'))

            this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').attr('disabled', true)
            this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').attr('disabled', true)

            var self = this
            this.ready.done(function() {
                self.ui.exp.html(self.visits.opts()).val(self.model.get('VISIT'))
                self.updateLC()
            })
        },

        initialize: function(options) {
            this.dewar = options.dewar
            this.contacts = new LabContacts(null, { state: { pageSize: 9999 } })
            this.listenTo(this.contacts, 'sync', this.updateContacts)
            this.refreshContacts()

            var self = this
            this.visits = new VVisits(null, { state: { pageSize: 9999 } })
            this.ready = this.visits.fetch()

            this.history = new DewarHistory(null, { queryParams: { did: this.getOption('dewar').get('DEWARID') }})
            this.history.fetch().done(function() {
                var h = self.history.at(0)
                if (h) self.ui.loc.val(h.get('STORAGELOCATION'))
            })
        },

        updateLC: function() {
            var vis = this.visits.findWhere({ VISIT: this.ui.exp.val() })
            if (vis) {
                var lc = vis.get('LC')
                if (lc) {
                    var lcs = lc.split(',')
                    this.ui.lco.val(lcs[0].trim())
                } else this.ui.lco.val('')
            }

        },

        refreshContacts: function() {
            this.contacts.fetch()
        },

        updateContacts: function() {
            this.ui.lc.html(this.contacts.opts()).val(this.getOption('dewar').get('RETURNLABCONTACTID'))
            this.getlcdetails()
        },

        getlcdetails: function() {
            var lc = this.contacts.findWhere({ LABCONTACTID: this.ui.lc.val() })
            if (lc) {
                this.ui.gn.val(lc.get('GIVENNAME'))
                this.ui.fn.val(lc.get('FAMILYNAME'))
                this.ui.em.val(lc.get('EMAILADDRESS'))
                this.ui.ph.val(lc.get('PHONENUMBER'))
                this.ui.addr.val([lc.get('ADDRESS'),lc.get('CITY'),lc.get('POSTCODE'),lc.get('COUNTRY')].join("\n"))
                this.ui.lab.val(lc.get('LABNAME'))
            }
        },

        toggleCourierAccountDisplay: function(event) {
            if (event.target.checked) {
                this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').attr('disabled', false)
                this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').attr('disabled', false)
            } else {
                this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').val(this.dewar.get('DELIVERYAGENT_AGENTNAME'))
                this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').val(this.dewar.get('DELIVERYAGENT_AGENTCODE'))

                this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').attr('disabled', true)
                this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').attr('disabled', true)
            }
        }
    })

})<commit_msg>refactor: change name of method for handling courier account toggling<commit_after>define(['marionette', 'views/form',
    'collections/visits',
    'collections/labcontacts',
    'collections/shipments',
    'collections/dewars',
    'modules/shipment/collections/dewarhistory',

    'modules/shipment/models/dispatch',

    'templates/shipment/dispatch.html',
    'jquery',
    'backbone',
    'backbone-validation',

    ], function(Marionette, FormView,
        Visits, LabContacts, Shipments, Dewars, DewarHistory,
        DispatchModel,
        template, $_, Backbone) {

    var VVisits = Visits.extend({
        valueAttribute: 'VISIT',
    })

    return FormView.extend({
        template: template,

        events: {
            'change @ui.lc': 'getlcdetails',
            'change @ui.exp': 'updateLC',
            'click @ui.useAnotherCourierAccount': 'toggleCourierAccountEditing'
        },

        ui: {
            lc: 'select[name=LABCONTACTID]',

            exp: 'select[name=VISIT]',
            lco: 'input[name=LOCALCONTACT]',
            loc: 'input[name=LOCATION]',

            gn: 'input[name=GIVENNAME]',
            fn: 'input[name=FAMILYNAME]',
            addr: 'textarea[name=ADDRESS]',
            em: 'input[name=EMAILADDRESS]',
            ph: 'input[name=PHONENUMBER]',
            lab: 'input[name=LABNAME]',

            courier: 'span.courier',
            useAnotherCourierAccount: 'input[name=USE_ANOTHER_COURIER_ACCOUNT]'
        },

        templateHelpers: function() {
            return {
                DEWAR: this.getOption('dewar').toJSON()
            }
        },

        createModel: function() {
            this.model = new DispatchModel({
                FACILITYCODE: this.getOption('dewar').get('FACILITYCODE'),
                DEWARID: this.getOption('dewar').get('DEWARID'),
                LABCONTACTID: this.getOption('dewar').get('LABCONTACTID'),
                VISIT: this.getOption('dewar').get('FIRSTEXPERIMENT')
            })
        },

        success: function(model, response, options) {
            console.log('success from dispatch req')
            app.trigger('shipment:show', this.getOption('dewar').get('SHIPPINGID'))
        },

        failure: function(model, response, options) {
            console.log('failure from dispatch req')
            app.alert({ message: 'Something went wrong registering this dispatch request, please try again'})
        },

        onRender: function() {
            this.date('input[name=DELIVERYAGENT_SHIPPINGDATE]')

            var d = new Date()
            var today = (d.getDate() < 10 ? '0'+d.getDate() : d.getDate()) + '-' + (d.getMonth() < 9 ? '0'+(d.getMonth()+1) : d.getMonth()+1) + '-' + d.getFullYear()
            this.$el.find('input[name=DELIVERYAGENT_SHIPPINGDATE]').val(today)

            this.ui.courier.html('<input type="text" name="DELIVERYAGENT_AGENTNAME" />')
            this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').val(this.dewar.get('DELIVERYAGENT_AGENTNAME'))
            this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').val(this.dewar.get('DELIVERYAGENT_AGENTCODE'))

            this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').attr('disabled', true)
            this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').attr('disabled', true)

            var self = this
            this.ready.done(function() {
                self.ui.exp.html(self.visits.opts()).val(self.model.get('VISIT'))
                self.updateLC()
            })
        },

        initialize: function(options) {
            this.dewar = options.dewar
            this.contacts = new LabContacts(null, { state: { pageSize: 9999 } })
            this.listenTo(this.contacts, 'sync', this.updateContacts)
            this.refreshContacts()

            var self = this
            this.visits = new VVisits(null, { state: { pageSize: 9999 } })
            this.ready = this.visits.fetch()

            this.history = new DewarHistory(null, { queryParams: { did: this.getOption('dewar').get('DEWARID') }})
            this.history.fetch().done(function() {
                var h = self.history.at(0)
                if (h) self.ui.loc.val(h.get('STORAGELOCATION'))
            })
        },

        updateLC: function() {
            var vis = this.visits.findWhere({ VISIT: this.ui.exp.val() })
            if (vis) {
                var lc = vis.get('LC')
                if (lc) {
                    var lcs = lc.split(',')
                    this.ui.lco.val(lcs[0].trim())
                } else this.ui.lco.val('')
            }

        },

        refreshContacts: function() {
            this.contacts.fetch()
        },

        updateContacts: function() {
            this.ui.lc.html(this.contacts.opts()).val(this.getOption('dewar').get('RETURNLABCONTACTID'))
            this.getlcdetails()
        },

        getlcdetails: function() {
            var lc = this.contacts.findWhere({ LABCONTACTID: this.ui.lc.val() })
            if (lc) {
                this.ui.gn.val(lc.get('GIVENNAME'))
                this.ui.fn.val(lc.get('FAMILYNAME'))
                this.ui.em.val(lc.get('EMAILADDRESS'))
                this.ui.ph.val(lc.get('PHONENUMBER'))
                this.ui.addr.val([lc.get('ADDRESS'),lc.get('CITY'),lc.get('POSTCODE'),lc.get('COUNTRY')].join("\n"))
                this.ui.lab.val(lc.get('LABNAME'))
            }
        },

        toggleCourierAccountEditing: function(event) {
            if (event.target.checked) {
                this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').attr('disabled', false)
                this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').attr('disabled', false)
            } else {
                this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').val(this.dewar.get('DELIVERYAGENT_AGENTNAME'))
                this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').val(this.dewar.get('DELIVERYAGENT_AGENTCODE'))

                this.$el.find('input[name=DELIVERYAGENT_AGENTNAME]').attr('disabled', true)
                this.$el.find('input[name=DELIVERYAGENT_AGENTCODE]').attr('disabled', true)
            }
        }
    })

})<|endoftext|>


<commit_before>/**
  Copyright 2010-2011 Mateusz Paprocki <mattpap@gmail.com>
  Copyright 2011 Christian Iversen <ci@sikkerhed.org>

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
**/

py_builtins.hasattr = function(obj, name) {
    return bool(obj["PY$" + name] !== undefined);
};

py_builtins.getattr = function(obj, name, value) {
    var val = obj["PY$" + name];

    if (val !== undefined) {
        return val;
    } else {
        if (value !== undefined) {
            return value;
        } else {
            throw py_builtins.AttributeError(obj, name);
        }
    }
};

py_builtins.setattr = function(obj, name, value) {
    obj["PY$" + name] = value;
};

py_builtins.js_getattr = function(obj, name, value) {
    var val = obj[name];

    if (val !== undefined) {
        return val;
    } else {
        if (value !== undefined) {
            return value;
        } else {
            throw py_builtins.AttributeError(obj, name);
        }
    }
};

py_builtins.js_setattr = function(obj, name, value) {
    obj[name] = value;
};

py_builtins.delattr = function(obj, name) {
    if (obj["PY$" + name] !== undefined) {
        delete obj["PY$" + name];
    } else {
        throw py_builtins.AttributeError(obj, name);
    }
};

py_builtins.hash = function(obj) {
    if (py_builtins.hasattr(obj, '__hash__') == true) {
        return obj.PY$__hash__();
    } else if (typeof(obj) === 'number') {
        return obj === -1 ? -2 : obj;
    } else {
        throw py_builtins.AttributeError('__hash__');
    }
};

py_builtins.len = function(obj) {
    if (py_builtins.hasattr(obj, '__len__') == true) {
        return obj.PY$__len__();
    } else {
        throw py_builtins.AttributeError('__len__');
    }
};

py_builtins.dir = function(obj) {
    var res = list();
    for (var i in obj) {
        res.PY$append($PY.str(i));
    }
    return res;
};

py_builtins.cmp = function(x, y) {
  return x.PY$__cmp__(y);
};

py_builtins.repr = function(obj) {
    if (obj == undefined) {
        return "None";
    } else if (py_builtins.hasattr(obj, '__repr__') == true) {
        return obj.PY$__repr__(obj);
    } else if (py_builtins.hasattr(obj, '__str__') == true) {
        return obj.PY$__str__(obj);
    } else if (obj.toString !=! undefined) {
        return obj.toString();
    } else {
        throw py_builtins.AttributeError('__repr__, __str__ or toString not found on ' + typeof(obj));
    }
};

py_builtins.range = function(start, end, step) {
    start = js(start);

    if (end === undefined) {
        end = start;
        start = 0;
    } else {
        end = js(end);
    }

    if (step === undefined) {
        step = 1;
    } else {
        step = js(step);
    }

    var seq = [];

    for (var i = start; i < end; i += step) {
        seq.push(i);
    }

    if (py_builtins.PY$__python3__)
        return iter(seq);
    else
        return list(seq);
};

py_builtins.xrange = function(start, end, step) {
    return iter(py_builtins.range(start, end, step));
};

py_builtins.map = function() {
    if (arguments.length < 2) {
        throw py_builtins.TypeError("py_builtins.map() requires at least two args");
    }

    if (arguments.length > 2) {
        throw py_builtins.NotImplementedError("only one sequence allowed in py_builtins.map()");
    }

    var func = arguments[0];
    var items = list();

    iterate(arguments[1], function(item) {
        items.PY$append(func(item));
    });

    if (py_builtins.PY$__python3__)
        return iter(items);
    else
        return items;
};

py_builtins.enumerate = function(obj) {
    if (arguments.length != 1) {
        throw py_builtins.NotImplementedError("enumerate() only supports 1 argument");
    }
    var items = list();
    var count = 0;
    iterate(obj, function(elm) {
                items.PY$append(tuple([count++, elm]));
            });
    return items;
};

py_builtins.zip = function() {
    if (!arguments.length) {
        return list();
    }

    var iters = list();
    var i;

    for (i = 0; i < arguments.length; i++) {
        iters.PY$append(iter(arguments[i]));
    }

    var items = list();

    while (true) {
        var item = list();

        for (i = 0; i < arguments.length; i++) {
            try {
                var value = iters.PY$__getitem__(i).PY$next();
            } catch (exc) {
                if ($PY.isinstance(exc, py_builtins.StopIteration) == true) {
                    return items;
                } else {
                    throw exc;
                }
            }

            item.PY$append(value);
        }

        items.PY$append(tuple(item));
    }
    return None;
};

py_builtins.isinstance = function(obj, cls) {
    if (cls.PY$__class__ === tuple) {
        var length = cls.PY$__len__();

        if (length.PY$__eq__($c0) == true) {
            return False;
        }

        for (var i = 0; i < length; i++) {
            var _cls = cls.PY$__getitem__(i);

            if ($PY.isinstance(obj, _cls) == true) {
                return True;
            }
        }

        return False;
    } else {
        var c = obj.PY$__class__;
        while (c) {
            if (c === cls)
                return True;
            c = c.PY$__super__;
        }
        return False;
    }
};

py_builtins.__not__ = function(obj) {
   if (py_builtins.hasattr(obj, '__nonzero__') == true) {
       return bool(!js(obj.PY$__nonzero__()));
   } else if (py_builtins.hasattr(obj, '__len__') == true) {
       return bool(js(obj.PY$__len__()) === 0);
   } else {
       return bool(!js(obj));
   }
};

py_builtins.__is__ = function(a, b) {
    return bool(a === b);
};

py_builtins.max = function(list) {
    if (py_builtins.len(list).PY$__eq__($c0) == true)
        throw py_builtins.ValueError("max() arg is an empty sequence");
    else {
        var result = null;

        iterate(list, function(item) {
                if ((result === null) || js(item.PY$__gt__(result)))
                    result = item;
        });

        return result;
    }
};

py_builtins.min = function(list) {
    if (py_builtins.len(list).PY$__eq__($c0) == true)
        throw py_builtins.ValueError("min() arg is an empty sequence");
    else {
        var result = null;

        iterate(list, function(item) {
                if ((result === null) || js(item.PY$__lt__(result)))
                    result = item;
        });

        return result;
    }
};

py_builtins.sum = function(list) {
    var result = 0;

    iterate(list, function(item) {
        result += js(item);
    });

    return result;
};

py_builtins.filter = function(f, l) {
   var res = list();
   iterate(l, function(item) {
     if (bool(f(item)) == true) {
       res.PY$append(item);
     }
   });
   return res;
};

py_builtins.reduce = function(func, seq) {
    var initial;
    if (arguments.length == 3) {
        initial = arguments[2];
    } else {
        initial = null;
    }
    if (py_builtins.len(seq) < 2) {
        return initial;
    }
    var accum, start;
    if (arguments.length == 3) {
        accum = initial;
        start = 0;
    } else {
        accum = func(seq.PY$__getitem__(0), seq.PY$__getitem__(1));
        start = 2;
    }
    for (var i = start; i < py_builtins.len(seq); i++) {
        accum = func(accum, seq.PY$__getitem__(i));
    }
    return accum;
};

if (typeof console !== 'undefined' && console.log !== undefined) {
    py_builtins.print = function()  {
        console.log.apply(null, arguments);
    };
} else if (typeof window === 'undefined' || window.print !== print) {
    py_builtins.print = function() {
        if (arguments.length <= 1) {
            if (arguments[0] !== undefined) {
                print($PY.str(arguments[0]));
            } else {
                print("");
            }
        } else {
            var args = tuple(Array.prototype.slice.call(arguments, 0));
            print($PY.str(" ").PY$join(args));
        }
    };
} else {
    py_builtins.print = function() {
        var args = tuple(Array.prototype.slice.call(arguments, 0));
        alert($PY.str(" ").PY$join(args));
    };
}
<commit_msg> + Added initial sorted() builtin<commit_after>/**
  Copyright 2010-2011 Mateusz Paprocki <mattpap@gmail.com>
  Copyright 2011 Christian Iversen <ci@sikkerhed.org>

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
**/

py_builtins.hasattr = function(obj, name) {
    return bool(obj["PY$" + name] !== undefined);
};

py_builtins.getattr = function(obj, name, value) {
    var val = obj["PY$" + name];

    if (val !== undefined) {
        return val;
    } else {
        if (value !== undefined) {
            return value;
        } else {
            throw py_builtins.AttributeError(obj, name);
        }
    }
};

py_builtins.setattr = function(obj, name, value) {
    obj["PY$" + name] = value;
};

py_builtins.js_getattr = function(obj, name, value) {
    var val = obj[name];

    if (val !== undefined) {
        return val;
    } else {
        if (value !== undefined) {
            return value;
        } else {
            throw py_builtins.AttributeError(obj, name);
        }
    }
};

py_builtins.js_setattr = function(obj, name, value) {
    obj[name] = value;
};

py_builtins.delattr = function(obj, name) {
    if (obj["PY$" + name] !== undefined) {
        delete obj["PY$" + name];
    } else {
        throw py_builtins.AttributeError(obj, name);
    }
};

py_builtins.hash = function(obj) {
    if (py_builtins.hasattr(obj, '__hash__') == true) {
        return obj.PY$__hash__();
    } else if (typeof(obj) === 'number') {
        return obj === -1 ? -2 : obj;
    } else {
        throw py_builtins.AttributeError('__hash__');
    }
};

py_builtins.len = function(obj) {
    if (py_builtins.hasattr(obj, '__len__') == true) {
        return obj.PY$__len__();
    } else {
        throw py_builtins.AttributeError('__len__');
    }
};

py_builtins.dir = function(obj) {
    var res = list();
    for (var i in obj) {
        res.PY$append($PY.str(i));
    }
    return res;
};

py_builtins.cmp = function(x, y) {
  return x.PY$__cmp__(y);
};

py_builtins.repr = function(obj) {
    if (obj == undefined) {
        return "None";
    } else if (py_builtins.hasattr(obj, '__repr__') == true) {
        return obj.PY$__repr__(obj);
    } else if (py_builtins.hasattr(obj, '__str__') == true) {
        return obj.PY$__str__(obj);
    } else if (obj.toString !=! undefined) {
        return obj.toString();
    } else {
        throw py_builtins.AttributeError('__repr__, __str__ or toString not found on ' + typeof(obj));
    }
};

py_builtins.range = function(start, end, step) {
    start = js(start);

    if (end === undefined) {
        end = start;
        start = 0;
    } else {
        end = js(end);
    }

    if (step === undefined) {
        step = 1;
    } else {
        step = js(step);
    }

    var seq = [];

    for (var i = start; i < end; i += step) {
        seq.push(i);
    }

    if (py_builtins.PY$__python3__)
        return iter(seq);
    else
        return list(seq);
};

py_builtins.xrange = function(start, end, step) {
    return iter(py_builtins.range(start, end, step));
};

py_builtins.map = function() {
    if (arguments.length < 2) {
        throw py_builtins.TypeError("py_builtins.map() requires at least two args");
    }

    if (arguments.length > 2) {
        throw py_builtins.NotImplementedError("only one sequence allowed in py_builtins.map()");
    }

    var func = arguments[0];
    var items = list();

    iterate(arguments[1], function(item) {
        items.PY$append(func(item));
    });

    if (py_builtins.PY$__python3__)
        return iter(items);
    else
        return items;
};

py_builtins.enumerate = function(obj) {
    if (arguments.length != 1) {
        throw py_builtins.NotImplementedError("enumerate() only supports 1 argument");
    }
    var items = list();
    var count = 0;
    iterate(obj, function(elm) {
                items.PY$append(tuple([count++, elm]));
            });
    return items;
};

py_builtins.zip = function() {
    if (!arguments.length) {
        return list();
    }

    var iters = list();
    var i;

    for (i = 0; i < arguments.length; i++) {
        iters.PY$append(iter(arguments[i]));
    }

    var items = list();

    while (true) {
        var item = list();

        for (i = 0; i < arguments.length; i++) {
            try {
                var value = iters.PY$__getitem__(i).PY$next();
            } catch (exc) {
                if ($PY.isinstance(exc, py_builtins.StopIteration) == true) {
                    return items;
                } else {
                    throw exc;
                }
            }

            item.PY$append(value);
        }

        items.PY$append(tuple(item));
    }
    return None;
};

py_builtins.isinstance = function(obj, cls) {
    if (cls.PY$__class__ === tuple) {
        var length = cls.PY$__len__();

        if (length.PY$__eq__($c0) == true) {
            return False;
        }

        for (var i = 0; i < length; i++) {
            var _cls = cls.PY$__getitem__(i);

            if ($PY.isinstance(obj, _cls) == true) {
                return True;
            }
        }

        return False;
    } else {
        var c = obj.PY$__class__;
        while (c) {
            if (c === cls)
                return True;
            c = c.PY$__super__;
        }
        return False;
    }
};

py_builtins.__not__ = function(obj) {
   if (py_builtins.hasattr(obj, '__nonzero__') == true) {
       return bool(!js(obj.PY$__nonzero__()));
   } else if (py_builtins.hasattr(obj, '__len__') == true) {
       return bool(js(obj.PY$__len__()) === 0);
   } else {
       return bool(!js(obj));
   }
};

py_builtins.__is__ = function(a, b) {
    return bool(a === b);
};

py_builtins.max = function(list) {
    if (py_builtins.len(list).PY$__eq__($c0) == true)
        throw py_builtins.ValueError("max() arg is an empty sequence");
    else {
        var result = null;

        iterate(list, function(item) {
                if ((result === null) || js(item.PY$__gt__(result)))
                    result = item;
        });

        return result;
    }
};

py_builtins.min = function(list) {
    if (py_builtins.len(list).PY$__eq__($c0) == true)
        throw py_builtins.ValueError("min() arg is an empty sequence");
    else {
        var result = null;

        iterate(list, function(item) {
                if ((result === null) || js(item.PY$__lt__(result)))
                    result = item;
        });

        return result;
    }
};

py_builtins.sum = function(list) {
    var result = 0;

    iterate(list, function(item) {
        result += js(item);
    });

    return result;
};

py_builtins.filter = function(f, l) {
   var res = list();
   iterate(l, function(item) {
     if (bool(f(item)) == true) {
       res.PY$append(item);
     }
   });
   return res;
};

py_builtins.reduce = function(func, seq) {
    var initial;
    if (arguments.length == 3) {
        initial = arguments[2];
    } else {
        initial = null;
    }
    if (py_builtins.len(seq) < 2) {
        return initial;
    }
    var accum, start;
    if (arguments.length == 3) {
        accum = initial;
        start = 0;
    } else {
        accum = func(seq.PY$__getitem__(0), seq.PY$__getitem__(1));
        start = 2;
    }
    for (var i = start; i < py_builtins.len(seq); i++) {
        accum = func(accum, seq.PY$__getitem__(i));
    }
    return accum;
};

py_builtins.sorted = function(iterable) {
    var l = list(iterable);
    l.PY$sort();
    return l;
};

if (typeof console !== 'undefined' && console.log !== undefined) {
    py_builtins.print = function()  {
        console.log.apply(null, arguments);
    };
} else if (typeof window === 'undefined' || window.print !== print) {
    py_builtins.print = function() {
        if (arguments.length <= 1) {
            if (arguments[0] !== undefined) {
                print($PY.str(arguments[0]));
            } else {
                print("");
            }
        } else {
            var args = tuple(Array.prototype.slice.call(arguments, 0));
            print($PY.str(" ").PY$join(args));
        }
    };
} else {
    py_builtins.print = function() {
        var args = tuple(Array.prototype.slice.call(arguments, 0));
        alert($PY.str(" ").PY$join(args));
    };
}
<|endoftext|>


<commit_before>var MODULE = require(LIBS_DIR + '/module').Module;

var logger = require(LIBS_DIR + '/logger');

function ModuleManager(dispatcher, config) {
	this._modules = {};
	if (typeof dispatcher === 'object') {
		this.dispatcher = dispatcher;
	} else {
		this.dispatcher = new(require('events').EventEmitter)();
		this.dispatcher.setMaxListeners(0);
	}
	if (typeof config === 'object') {
		this.config = config;
	} else {
		this.config = require(LIBS_DIR + '/config').create();
	}
}

ModuleManager.prototype.getModules = function() {
	return Object.keys(this._modules); //return loaded module names
};

ModuleManager.prototype.exists = ModuleManager.prototype.has = ModuleManager.prototype.contains = function(name) {
	if (name instanceof MODULE) {
		name = name.name;
	} else if (typeof name !== 'string' || name === '') {
		return false;
	}
	return this._modules[name] !== undefined;
};

ModuleManager.prototype.get = ModuleManager.prototype.find = function(name) {
	if (name instanceof MODULE) {
		return name;
	} else if (typeof name !== 'string' || name === '') {
		return null;
	}
	if (this._modules[name] !== undefined) {
		return this._modules[name];
	}
	return null;
};

ModuleManager.prototype.load = ModuleManager.prototype.enable = function(name, callback) {
	var error = null;
	var module = null;
	if (typeof name !== 'string' || name === '') {
		error = new Error('Please enter a name!');
	} else if (this.exists(name)) {
		module = this.get(name);
	} else {
		if (typeof this[name] !== 'undefined') {
			error = new Error('Reserved module name! Please rename your module!');
		} else {
			try {
				module = new MODULE(name);
			} catch (e) {
				error = new Error('Error happened during module construction: ' + e.message);
				module = null;
			}
			if (module instanceof MODULE) {
				if (typeof module.injectModuleManager === 'function') module.injectModuleManager(this);
				if (typeof module.injectConfig === 'function') module.injectConfig(require(LIBS_DIR + '/config').create(this.config[name]));
				if (typeof module.injectDispatcher === 'function') module.injectDispatcher(this.dispatcher);

				try {
					if (typeof module.init === 'function') module.init();
				} catch (e) {
					error = new Error('Error happened during module initialization: ' + e.message);
					module = null;
				}

				if (!error) {
					this._modules[name] = module;

					//add as property for quick access
					Object.defineProperty(this, name, {
						configurable: true,
						value: module
					});
				}
			} else {
				error = new Error('Cannot load \'' + name + '\' module!');
				module = null;
			}
		}
	}

	logger.debug('Load of \'' + name + '\' module' + (error ? ' failed' : ' is success') + '.');

	if (callback) callback(error, module, this);
	else if (error) throw error;
	return this;
};

ModuleManager.prototype.unload = ModuleManager.prototype.disable = function(name, callback) {
	var error = null;
	if (name instanceof MODULE) {
		name = name.name;
	}
	if (typeof name !== 'string' || name === '') {
		error = new Error('Please enter a name!');
	} else {
		if (this.exists(name)) {
			var module = this.get(name);

			//disable event binding on halt with uncatched exception so users gets kicked in face
			if (typeof module.dispatcher === 'object') {
				module.dispatcher.on = module.dispatcher.once = module.dispatcher.addListener = function() {
					throw new Error('You cannot bind events on module halt!');
				};
			}

			try {
				if (typeof module.halt === 'function') module.halt();
			} catch (e) {
				//ignore all exceptions in halt
				logger.warn('Got error in module \'' + name + '\' halt: ' + e);
			}

			//puff it
			delete this._modules[name];
			if (this[name] === module) delete this[name];
		} else {
			error = new Error('Module \'' + name + '\' is not loaded!');
		}
	}

	logger.debug('Unload of \'' + name + '\' module' + (error ? ' failed' : ' is success') + '.');

	if (callback) callback(error, name, this);
	else if (error) throw error;
	return this;
};

//reload module context
ModuleManager.prototype.reload = function(name, callback) {
	var mm = this;
	var error = null;

	var module = this.find(name);

	if (module) {
		try {
			module.reload(undefined, require(LIBS_DIR + '/config').create(this.config[name])); //reload with new config
		} catch (e) {
			error = new Error('Error happened during module reload: ' + e.message);
		}
	} else {
		error = new Error('Module \'' + name + '\' is not loaded!');
	}

	logger.debug('Reload of \'' + name + '\' module' + (error ? ' failed' : ' is success') + '.');

	if (callback) callback(error, module, this);
	else if (error) throw error;

	return this;
};

ModuleManager.prototype.require = function(name) {
	if (typeof name !== 'string' || name === '') {
		throw new Error('Please enter a name!');
	} else if (!this.exists(name)) {
		this.load(name);
	}

	return this.get(name);
};

module.exports.ModuleManager = ModuleManager;
module.exports.create = function(dispatcher) {
	return new ModuleManager(dispatcher);
};<commit_msg>MM load error if module already loaded<commit_after>var MODULE = require(LIBS_DIR + '/module').Module;

var logger = require(LIBS_DIR + '/logger');

function ModuleManager(dispatcher, config) {
	this._modules = {};
	if (typeof dispatcher === 'object') {
		this.dispatcher = dispatcher;
	} else {
		this.dispatcher = new(require('events').EventEmitter)();
		this.dispatcher.setMaxListeners(0);
	}
	if (typeof config === 'object') {
		this.config = config;
	} else {
		this.config = require(LIBS_DIR + '/config').create();
	}
}

ModuleManager.prototype.getModules = function() {
	return Object.keys(this._modules); //return loaded module names
};

ModuleManager.prototype.exists = ModuleManager.prototype.has = ModuleManager.prototype.contains = function(name) {
	if (name instanceof MODULE) {
		name = name.name;
	} else if (typeof name !== 'string' || name === '') {
		return false;
	}
	return this._modules[name] !== undefined;
};

ModuleManager.prototype.get = ModuleManager.prototype.find = function(name) {
	if (name instanceof MODULE) {
		return name;
	} else if (typeof name !== 'string' || name === '') {
		return null;
	}
	if (this._modules[name] !== undefined) {
		return this._modules[name];
	}
	return null;
};

ModuleManager.prototype.load = ModuleManager.prototype.enable = function(name, callback) {
	var error = null;
	var module = null;
	if (typeof name !== 'string' || name === '') {
		error = new Error('Please enter a name!');
	} else if (this.exists(name)) {
		error = new Error('Module \'' + name + '\' is already loaded!');
	} else {
		if (typeof this[name] !== 'undefined') {
			error = new Error('Reserved module name! Please rename your module!');
		} else {
			try {
				module = new MODULE(name);
			} catch (e) {
				error = new Error('Error happened during module construction: ' + e.message);
				module = null;
			}
			if (module instanceof MODULE) {
				if (typeof module.injectModuleManager === 'function') module.injectModuleManager(this);
				if (typeof module.injectConfig === 'function') module.injectConfig(require(LIBS_DIR + '/config').create(this.config[name]));
				if (typeof module.injectDispatcher === 'function') module.injectDispatcher(this.dispatcher);

				try {
					if (typeof module.init === 'function') module.init();
				} catch (e) {
					error = new Error('Error happened during module initialization: ' + e.message);
					module = null;
				}

				if (!error) {
					this._modules[name] = module;

					//add as property for quick access
					Object.defineProperty(this, name, {
						configurable: true,
						value: module
					});
				}
			} else {
				error = new Error('Cannot load \'' + name + '\' module!');
				module = null;
			}
		}
	}

	logger.debug('Load of \'' + name + '\' module' + (error ? ' failed' : ' is success') + '.');

	if (callback) callback(error, module, this);
	else if (error) throw error;
	return this;
};

ModuleManager.prototype.unload = ModuleManager.prototype.disable = function(name, callback) {
	var error = null;
	if (name instanceof MODULE) {
		name = name.name;
	}
	if (typeof name !== 'string' || name === '') {
		error = new Error('Please enter a name!');
	} else {
		if (this.exists(name)) {
			var module = this.get(name);

			//disable event binding on halt with uncatched exception so users gets kicked in face
			if (typeof module.dispatcher === 'object') {
				module.dispatcher.on = module.dispatcher.once = module.dispatcher.addListener = function() {
					throw new Error('You cannot bind events on module halt!');
				};
			}

			try {
				if (typeof module.halt === 'function') module.halt();
			} catch (e) {
				//ignore all exceptions in halt
				logger.warn('Got error in module \'' + name + '\' halt: ' + e);
			}

			//puff it
			delete this._modules[name];
			if (this[name] === module) delete this[name];
		} else {
			error = new Error('Module \'' + name + '\' is not loaded!');
		}
	}

	logger.debug('Unload of \'' + name + '\' module' + (error ? ' failed' : ' is success') + '.');

	if (callback) callback(error, name, this);
	else if (error) throw error;
	return this;
};

//reload module context
ModuleManager.prototype.reload = function(name, callback) {
	var mm = this;
	var error = null;

	var module = this.find(name);

	if (module) {
		try {
			module.reload(undefined, require(LIBS_DIR + '/config').create(this.config[name])); //reload with new config
		} catch (e) {
			error = new Error('Error happened during module reload: ' + e.message);
		}
	} else {
		error = new Error('Module \'' + name + '\' is not loaded!');
	}

	logger.debug('Reload of \'' + name + '\' module' + (error ? ' failed' : ' is success') + '.');

	if (callback) callback(error, module, this);
	else if (error) throw error;

	return this;
};

ModuleManager.prototype.require = function(name) {
	if (typeof name !== 'string' || name === '') {
		throw new Error('Please enter a name!');
	} else if (!this.exists(name)) {
		this.load(name);
	}

	return this.get(name);
};

module.exports.ModuleManager = ModuleManager;
module.exports.create = function(dispatcher) {
	return new ModuleManager(dispatcher);
};<|endoftext|>


<commit_before>'use strict';

angular.module('pumprApp')
  .factory('facilityIdFactory', function ($http) {
    // Service logic
    // ...
    var facilityids = {
        wfids: [
          {
            tag: /(WHYD)\d*/,
            name: 'Water Hydrants',
            server: 'waterMs'
          },
          {
            tag: /(WSV)\d*/,
            name: 'Water System Valves',
            server: 'waterMs'
          },
          {
            tag: /(WFIT)\d*/,
            name: 'Water Fittings',
            server: 'waterMs'
          },
          {
            tag: /(WSC)\d*/,
            name: 'Water Service Connections',
            server: 'waterMs'
          },
          {
            tag: /(WSS)\d*/,
            name: 'Water Sampling Stations',
            server: 'waterMs'
          },
          {
            tag: /(WCV)\d*/,
            name: 'Water Control Valves',
            server: 'waterMs'
          },
          {
            tag: /(WNS)\d*/,
            name: 'Water Network Structures',
            server: 'waterMs'
          },
          {
            tag: /(WMN)\d*/,
            name: 'Water Pressure Mains',
            server: 'waterMs'
          },
          {
            tag: /(WGM)\d*/,
            name: 'Water Gravity Mains',
            server: 'waterMs'
          },
          {
            tag: /(WLAT)\d*/,
            name: 'Water Lateral Lines',
            server: 'waterMs'
          }
        ],
        sfids: [
          {
            tag: /(SNS)\d*/,
            name: 'Sewer Pump Stations',
            server: 'sewerMs'
          },
          {
            tag: /(SMH)\d*/,
            name: 'Sewer Manhole',
            server: 'sewerMs'
          },
          {
            tag: /(SFMN)\d*/,
            name: 'Force Main',
            server: 'sewerMs'
          },
          {
            tag: /(SGMN)\d*/,
            name: 'Gravity Sewer',
            server: 'sewerMs'
          },
          {
            tag: /(SLAT)\d*/,
            name: 'Lateral',
            server: 'sewerMs'
          }
        ]
      };

    // Public API here
    return (facilityids);

  });
<commit_msg>Updated constructor<commit_after>/**
 * FacilityId Service
 * @namespace Service/Factory
 * @desc Contains all facility id constructors
 */

(function(){
  'use strict';

  angular
    .module('pumprApp')
    .factory('facilityIdFactory', facilityIdFactory);

    function facilityIdFactory() {

      //Water Services
      var wControlValves = new WaterFacilityId(/(WCV)\d*/, 'Water Control Valves');
      var wFittings = new WaterFacilityId(/(WFIT)\d*/, 'Water Fittings');
      var wGravityMains = new WaterFacilityId(/(WGM)\d*/, 'Water Gravity Mains');
      var wHydrants = new WaterFacilityId(/(WHYD)\d*/, 'Water Hydrants');
      var wLaterals = new WaterFacilityId(/(WLAT)\d*/, 'Water Lateral Lines');
      var wNetStruct = new WaterFacilityId(/(WNS)\d*/, 'Water Network Structures');
      var wPressureMains = new WaterFacilityId(/(WMN)\d*/, 'Water Pressure Mains');
      var wSamplingStation = new WaterFacilityId(/(WSS)\d*/, 'Water Sampling Stations');
      var wServiceConnection = new WaterFacilityId(/(WSC)\d*/, 'Water Service Connections');
      var wSystemValves = new WaterFacilityId(/(WSV)\d*/, 'Water System Valves');

      //Sewer Services
      var ssForceMains = new SewerFacilityId(/(SFMN)\d*/, 'Force Main');
      var ssGravityMain = new SewerFacilityId(/(SGMN)\d*/, 'Gravity Sewer');
      var ssLateral = new SewerFacilityId(/(SLAT)\d*/, 'Lateral');
      var ssManHoles = new SewerFacilityId(/(SMH)\d*/, 'Sewer Manhole');
      var ssPumpStation = new SewerFacilityId(/(SNS)\d*/, 'Sewer Pump Stations');

      var service = {
        wfids: [wControlValves, wFittings, wGravityMains, wHydrants, wLaterals, wNetStruct, wPressureMains, wSamplingStation, wServiceConnection, wSystemValves],
        sfids: [ssForceMains, ssGravityMain, ssLateral, ssManHoles, ssPumpStation]
      };

      return service;

      /**
      * @desc Represents a FacilityId
      * @constructor
      * @param {RegEx} tag - Regular Express that identifies the feature class.
      * @param {string} name - Name of the layer in the Map Service.
      */
      function FacilityId(tag, name, server) {
        var self = this;
        self.tag = tag;
        self.name = name;
        self.server = server;
        return self;
      }

      /**
      * @desc Represents a Water Service FacilityId
      * @constructor
      * @param {RegEx} tag - Regular Express that identifies the feature class.
      * @param {string} name - Name of the layer in the Map Service.
      */
      function WaterFacilityId(tag, name){
        var self = this;
        FacilityId.call(self, tag, name, 'waterMs');
        return self;
      }

      /**
      * @desc Represents a Sewer Service FacilityId
      * @constructor
      * @param {RegEx} tag - Regular Express that identifies the feature class.
      * @param {string} name - Name of the layer in the Map Service.
      */
      function SewerFacilityId(tag, name){
        var self = this;
        FacilityId.call(self, tag, name, 'sewerMs');
        return self;
      }
    }

})();
<|endoftext|>


<commit_before>var JS_GAME = {};

JS_GAME.game = (function () {
	var socket;
	var user = "";
	var pass1 = "";
	var pass2 = "";

	function init() {
		user = document.getElementById("loginInfo").user.value;
		pass1 = document.getElementById("loginInfo").pass1.value;
		pass2 = document.getElementById("loginInfo").pass2.value;
		if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
			document.getElementById("loginInfo").user.value = "INVALID INPUT";
			return;
		}
		if (pass1 != pass2){
			document.getElementById("loginInfo").pass1.value = "PASSWORDS DO NOT MATCH";
			return;
		}
		socket = new WebSocket("ws:167.88.120.57:38734");

		socket.onopen = function() {
			connected = true;
			socket.send("add:" + user + "," + pass1);
		};
		socket.onmessage = function(message) {
			if (message.data.indexOf("valid") == 0){
				window.location.href = "http://monolc.com/FellJS";
			} else {
				document.getElementById("loginInfo").pass1.value = "Creating Failed";
			}
		};
		socket.onclose = function() {
			window.location.reload(false);
		};
		socket.onerror = function() {

		};
	}

	return {
		init: init
	};
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});<commit_msg>Also for creating a new user<commit_after>var JS_GAME = {};

JS_GAME.game = (function () {
	var socket;
	var user = "";
	var pass1 = "";
	var pass2 = "";

	function init() {
		user = document.getElementById("loginInfo").user.value;
		pass1 = document.getElementById("loginInfo").pass1.value;
		pass2 = document.getElementById("loginInfo").pass2.value;
		if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
			document.getElementById("loginInfo").user.value = "INVALID INPUT";
			return;
		}
		if (pass1 != pass2){
			document.getElementById("loginInfo").pass1.value = "PASSWORDS DO NOT MATCH";
			return;
		}
		socket = new WebSocket("ws:167.88.120.57:38734");

		socket.onopen = function() {
			connected = true;
			var ret = {"add": {
				 	"user": user,
				 	"pass": pass
				}
			};
			socket.send("add:" + user + "," + pass1);
		};
		socket.onmessage = function(message) {
			if (message.data.indexOf("valid") == 0){
				window.location.href = "http://monolc.com/FellJS";
			} else {
				document.getElementById("loginInfo").pass1.value = "Creating Failed";
			}
		};
		socket.onclose = function() {
			window.location.reload(false);
		};
		socket.onerror = function() {

		};
	}

	return {
		init: init
	};
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
	e.preventDefault();
	JS_GAME.game.init();
	return false;
  });
});<|endoftext|>


<commit_before>
describe("table-tags", function() {
  var tags
    , tables
    , user
    , tagsView;

  beforeEach(function() {
    tables = new cdb.admin.Tables();
    user = new cdb.admin.User({ id : "1" });
    tags = new cdb.admin.Tags();

    tagsView = new cdb.admin.dashboard.TagsView({
      tables: tables,
      model: tags
    });

    tagsView.model.fetch = function() { }

    this.server = sinon.fakeServer.create();
    var tableArray = [];
    for(var i = 0; i < _TABLES_PER_PAGE; i++) {
      tableArray.push({id: i, name: 'test'+i, privacy: 'PRIVATE', rows_counted: 1, updated_at: new Date(), tags: 'a', table_size: 100, description: 'test'});
    }

    this.server.respondWith("GET", "irrelevant.json",
                                [200, { "Content-Type": "application/json" },
                                 '{"total_entries":'+(_TABLES_PER_PAGE+2)+', "tables": '+JSON.stringify(tableArray)+'}']);

  });

  it("should update table tags when tables model is updated from server", function() {
    spyOn(tagsView.model, 'fetch');
    tables.trigger('reset')
    expect(tagsView.model.fetch).toHaveBeenCalled();
  });

  it("should update user tags when a table is removed", function() {
    spyOn(tagsView.model, 'fetch');
    tables.trigger('remove')

    expect(tagsView.model.fetch).toHaveBeenCalled();
  });

  it("should render", function() {
    var container = $('

');
    container.appendTo($("body"));
    tagsView.el = container;
    tagsView.$el = $(container);
    tagsView.render();
    expect(container.html()).toBeTruthy();
    container.remove();
  });
  it("should not render 'view_all' button if there aren't enough tags", function() {
    var container = $('

');
    container.appendTo($("body"));
    tagsView.el = container;
    tagsView.$el = $(container);

    tagsView.render();

    expect(container.find('li.view_all a').length).toBeFalsy()
    container.remove();
  })

});
<commit_msg>tests for view all tags<commit_after>
describe("table-tags", function() {
  var tags
    , tables
    , user
    , tagsView;

  beforeEach(function() {
    tables = new cdb.admin.Tables();
    user = new cdb.admin.User({ id : "1" });
    tags = new cdb.admin.Tags();

    tagsView = new cdb.admin.dashboard.TagsView({
      tables: tables,
      model: tags
    });

    tagsView.model.fetch = function() { }

    this.server = sinon.fakeServer.create();
    var tableArray = [];
    for(var i = 0; i < _TABLES_PER_PAGE; i++) {
      tableArray.push({id: i, name: 'test'+i, privacy: 'PRIVATE', rows_counted: 1, updated_at: new Date(), tags: 'a', table_size: 100, description: 'test'});
    }

    this.server.respondWith("GET", "irrelevant.json",
                                [200, { "Content-Type": "application/json" },
                                 '{"total_entries":'+(_TABLES_PER_PAGE+2)+', "tables": '+JSON.stringify(tableArray)+'}']);

  });

  it("should update table tags when tables model is updated from server", function() {
    spyOn(tagsView.model, 'fetch');
    tables.trigger('reset')
    expect(tagsView.model.fetch).toHaveBeenCalled();
  });

  it("should update user tags when a table is removed", function() {
    spyOn(tagsView.model, 'fetch');
    tables.trigger('remove')

    expect(tagsView.model.fetch).toHaveBeenCalled();
  });

  it("should render", function() {
    var container = $('

');
    container.appendTo($("body"));
    tagsView.el = container;
    tagsView.$el = $(container);
    tagsView.render();
    expect(container.html()).toBeTruthy();
    container.remove();
  });
  it("should not render 'view_all' button if there aren't enough tags", function() {
    var container = $('

');
    container.appendTo($("body"));
    tagsView.el = container;
    tagsView.$el = $(container);

    tagsView.render();

    expect(container.find('li.view_all a').length).toBeFalsy()
    container.remove();
  })
  it("should not render 'view_all' button if there aren't enough tags", function() {
    var container = $('

');
    container.appendTo($("body"));
    tagsView.el = container;
    tagsView.$el = $(container);

    tagsView.render();

    expect(container.find('li.view_all a').length).toBeFalsy()
    container.remove();
  })
  it("should render 'view_all' button if there are enough tags", function() {
    var container = $('

');
    container.appendTo($("body"));
    for(var i = 0; i <= tagsView._TAG_AMOUNT; i++ ) {
      tags.set(i, {'name': i, 'count': 1})
    }
    tagsView.el = container;
    tagsView.$el = $(container);

    tagsView.render();

    expect(container.find('li.view_all a').length).toBeTruthy()
    container.remove();
  })

  it("should show a dialog with all the available tags", function() {
    var container = $('

');
    container.appendTo($("body"));
    for(var i = 0; i <= tagsView._TAG_AMOUNT; i++ ) {
      tags.set(i, {'name': i, 'count': 1})
    }
    tagsView.el = container;
    tagsView.$el = $(container);

    tagsView.render();

    tagsView._showAllTags();

    expect(tagsView.dialog).toBeTruthy();
    tagsView.dialog.remove();
    container.remove();

  });
});
<|endoftext|>


<commit_before>import React, { StyleSheet, View, Component } from 'react-native';
import RNChart from 'react-native-chart';

class HistogramChart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      studentData: [],
      transformedData: [],
      xLabels: ['A', 'B', 'C', 'D']
    }
  }

  componentWillReceiveProps(newData) {
    var updatedStudentData = newData.data;

    this.setState({
      studentData : updatedStudentData,
      transformedData: transformMultiChoiceData(updatedStudentData),
      color: '#219dff'
    });

    var displayData = transformMultiChoiceData(updatedStudentData);
  }

  render() {
    return (
      <View style={styles.container}>
      </View>
    );
  }
}

var transformMultiChoiceData = (responses) => {
  var allResponses = {};

  responses.forEach((answer) => {
    allResponses[answer] = allResponses[answer] || 0;
    allResponses[answer]++;
  });

  return [allResponses['A'] || 0, allResponses['B'] || 0, allResponses['C'] || 0, allResponses['D'] || 0];
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  chart: {
    position: 'absolute',
    top: 15,
    left: 15,
    bottom: 4,
    right: 15,
  }
});

module.exports = HistogramChart;

<commit_msg>Add animated to Histogram<commit_after>import React, { StyleSheet, View, Component, Animated } from 'react-native';

class HistogramChart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      studentData: [],
      transformedData: [],
      animators: [new Animated.Value(0), new Animated.Value(0), new Animated.Value(0), new Animated.Value(0)],
      xLabels: ['A', 'B', 'C', 'D']
    }
  }

  componentWillReceiveProps(newData) {
    var updatedStudentData = newData.data;

    this.setState({
      studentData : updatedStudentData,
      transformedData: transformMultiChoiceData(updatedStudentData),
    });

    var displayData = transformMultiChoiceData(updatedStudentData);
    var total = displayData.reduce((a,b) => {return a + b});
    for(var i = 0 ; i < displayData.length; i++) {
      Animated.timing(
        this.state.animators[i],
        {toValue: displayData[i] / total},
      ).start();
    }
  }

  render() {
    return (
      <View style={styles.container}>
      </View>
    );
  }
}

var transformMultiChoiceData = (responses) => {
  var allResponses = {};

  responses.forEach((answer) => {
    allResponses[answer] = allResponses[answer] || 0;
    allResponses[answer]++;
  });

  return [allResponses['A'] || 0, allResponses['B'] || 0, allResponses['C'] || 0, allResponses['D'] || 0];
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  chart: {
    position: 'absolute',
    top: 15,
    left: 15,
    bottom: 4,
    right: 15,
  }
});

module.exports = HistogramChart;

<|endoftext|>