<commit_before>"use strict";

describe('configurator', function() {
  var mock1 = {};
  var mock2 = {};

  // stubs that mimick the markup of configuration JSON files.
  // Drawn out to different variables for easier testing, usually this
  // would come as a single file.

  var mainConf,
    morphConf,
    morphAttributes,
    morphRetrieverConf,
    perseidsRoute,
    perseidsConf,
    conf1;

  // We have to restore the conf variables before every spec,
  // as we might mangle with these values.
  beforeEach(function() {
    mainConf = {
      template: 'templates/main.html',
      retrievers: {
        'treebankRetriever': {
          resource: perseidsConf
        }
      },
      plugins: [
        'text',
        'morph'
      ]
    };

    morphConf = {
      name: 'morph',
      template: 'templates/morph.html',
      retrievers: {
        'fakeMorphRetriever' : morphRetrieverConf,
        'bspMorphRetriever' : {}
      },
      attributes: {
        fileUrl: 'configs/morph/aldt.json'
      }
    };

    morphAttributes = {
      postagSchema: []
    };

    morphRetrieverConf = {
      resource: 'morphologyService'
    };

    perseidsRoute = "http://services.perseids.org/:doc.xml";

    perseidsConf = {
      route: perseidsRoute,
      params: ["doc"]
    };

    conf1 = {
      main: mainConf,

      navbar: {
        template: 'templates/navbar.html'
      },

      plugins: {
        text: {
          name: 'text',
          main: true,
          template: 'templates/text2.html'
        },
        morph: morphConf
      },

      resources: {
        perseids: perseidsConf,
        morphologyService: {
          route: "http://services.perseids.org/bsp"
        }
      }
    };
  });

  beforeEach(module('arethusa', function($provide) {
    $provide.value('x', mock1);
    $provide.value('y', mock2);
  }));

  var $httpBackend;

  beforeEach(inject(function($injector) {
    $httpBackend = $injector.get('$httpBackend');
  }));

  var configurator;

  beforeEach(inject(function(_configurator_) {
    configurator = _configurator_;
  }));

  describe('this.defineConfiguration', function() {
    it('sets a configuration file', inject(function(configurator) {
      expect(configurator.configuration).toBeUndefined();
      configurator.defineConfiguration(conf1);
      expect(configurator.configuration).toBeDefined();
    }));

    xit('resolves references to external files inside a configuration', inject(function(configurator) {
      // the morph plugin's conf includes a fileUrl property
      expect(morphConf.attributes.fileUrl).toBeDefined();
      // the defineConfiguration function will resolve this property
      // and replace it with the contents of an external file
      $httpBackend.when('GET', morphConf.attributes.fileUrl).respond(morphAttributes);

      configurator.defineConfiguration(conf1);
      $httpBackend.flush();

      var morphAttributesConf =
        configurator.configuration.plugins.morph.attributes;

      expect(morphAttributesConf).toEqual(morphAttributes);
    }));

    xit('resolves references recursively - when an external file itself uses external files', inject(function(configurator) {
      var conf = {
        a: 1,
        fileUrl: 'x'
      };

      var file1 = {
        b: 2,
        fileUrl: 'y'
      };

      var file2 = {
        c: 3
      };

      var result = {
        a: 1,
        b: 2,
        c: 3
      };

      $httpBackend.when('GET', 'x').respond(file1);
      $httpBackend.when('GET', 'y').respond(file2);

      configurator.defineConfiguration(conf);
      $httpBackend.flush();

      expect(configurator.configuration).toEqual(result);
    }));
  });

  describe('this.mergeConfigurations', function() {
    it('merges two conf files', inject(function(configurator) {
      var conf1 = {
        x: {
          a: 1,
          d: [5],
          e: 7
        },
      };

      var conf2 = {
        x: {
          b: 2,
          d: [6],
          e: 8
        },
        y: {
          c: 3
        }
      };

      var expected = {
        x: {
          a: 1,
          b: 2,
          d: [5, 6],
          e: 8
        },
        y: {
          c: 3
        }
      };

      var actual = configurator.mergeConfigurations(conf1, conf2);
      expect(actual).toEqual(expected);
    }));
  });

  describe('this.configurationFor', function() {
    it('provides the configuration for a given plugin', inject(function(configurator) {
      // the configuration is usually provide from an external route
      configurator.configuration = { "text" : 'conf' };
      expect(configurator.configurationFor('text')).toEqual('conf');
    }));

    it('works on the top level (like main), as well as on sublevels (like plugins)', inject(function(configurator) {
      configurator.configuration = conf1;
      var getConf = function(name) {
        return configurator.configurationFor(name);
      };

      // main level
      expect(getConf('main')).toEqual(mainConf);
      // plugins
      expect(getConf('morph')).toEqual(morphConf);
      // resources
      expect(getConf('perseids')).toEqual(perseidsConf);
    }));
  });

  describe('this.delegateConf', function() {
    it('delegates a basic set of conf options to a given object', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      var defaultKeys = [
        'name',
        'main',
        'template',
        'external',
        'contextMenu',
        'contextMenuTemplate',
        'noView',
        'mode'
      ];

      obj.conf = configurator.configurationFor('morph');
      configurator.delegateConf(obj);

      angular.forEach(defaultKeys, function(key, i) {
        expect(obj.hasOwnProperty(key)).toBeTruthy();
      });
    }));

    it('an array of additional properties to delegate can be given', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      var results = [
        'name',
        'main',
        'template',
        'external',
        'contextMenu',
        'contextMenuTemplate',
        'noView',
        'a',
        'b'
      ];

      obj.conf = configurator.configurationFor('morph');
      configurator.delegateConf(obj, ['a', 'b']);

      angular.forEach(results, function(key, i) {
        expect(obj.hasOwnProperty(key)).toBeTruthy();
      });
    }));

    it('reads from an optional defaultConf property if need be', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {
        defaultConf: {
          contextMenu: true
        }
      };
      obj.conf = configurator.configurationFor('morph');

      configurator.delegateConf(obj);
      expect(obj.contextMenu).toBeTruthy();
    }));

    it('sets global default values', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      obj.conf = configurator.configurationFor('morph');
      configurator.delegateConf(obj);
      expect(obj.mode).toEqual('editor');
    }));

    it("defaults don't override when they shouldn't", inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      var conf = configurator.configurationFor('morph');
      obj.conf = angular.extend({ mode: 'viewer' }, conf);

      configurator.delegateConf(obj);
      expect(obj.mode).toEqual('viewer');
    }));

    it('globalDefaults can be configured', inject(function(configurator) {
      configurator.configuration = {
        main: {
          globalDefaults: {
            mode: 'customMode'
          },
          plugins: ['aPlugin']
        },
        plugins: {
          aPlugin: {}
        }
      };
      var obj = {
        conf: configurator.configurationFor('aPlugin')
      };

      configurator.delegateConf(obj);
      expect(obj.mode).toEqual('customMode');
    }));

    it('can honor sticky arguments through a third true arguemnt', function() {
      configurator.configuration = conf1;
      var obj = { conf: configurator.configurationFor('morph') };
      obj.defaultConf = {
        x: true,
        y: true
      };

      configurator.delegateConf(obj, ['x', 'y']);
      expect(obj.x).toBeTruthy();
      expect(obj.y).toBeTruthy();

      obj.x = false;
      obj.y = false;

      configurator.delegateConf(obj, ['x', 'y'], true);
      expect(obj.x).toBeFalsy();
      expect(obj.y).toBeFalsy();
    });
  });

  describe('this.getConfAndDelegate', function() {
    it('convenience fn to get conf and delegate in one step', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      configurator.getConfAndDelegate('morph', obj, ['a']);
      expect(obj.name).toEqual('morph');
      expect(obj.conf).toBeTruthy();
      expect(obj.hasOwnProperty('a')).toBeTruthy();
    }));

    it('returns the given object', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      var res = configurator.getConfAndDelegate('morph', obj);
      expect(obj).toBe(res);
    }));
  });

  describe('this.getStickyConf', function() {
    function setup() {
      configurator.configuration = conf1;
      var obj = {
       defaultConf: { preselect: true }
      };
      configurator.getStickyConf('morph', obj, ['preselect']);
      return obj;
    }

    it('acts just like getConfAndDelegate when the value is undefined', inject(function(configurator) {
      var obj = setup();
      expect(obj.preselect).toBeTruthy();
    }));

    it('will not override a manually set value on a second call', function() {
      var obj = setup();
      expect(obj.preselect).toBeTruthy();
      obj.preselect = false;
      configurator.getStickyConf('morph', obj, ['preselect']);
      expect(obj.preselect).toBeFalsy();
    });
  });

  describe('this.getService', function() {
    it('retrieves an angular instance by name', inject(function(configurator) {
      expect(configurator.getService('x')).toEqual(mock1);
    }));
  });

  describe('this.getServices', function() {
    it('retrieves an object of angular instances by name', inject(function(configurator) {
      var names = ['x', 'y'];
      var services = configurator.getServices(names);
      expect(services).toEqual({ 'x' : mock1, 'y' : mock2 });
    }));

    it('returns an empty array when no service names are given', inject(function(configurator) {
      var services = configurator.getServices(undefined);
      expect(services).toEqual([]);
    }));
  });

  describe('this.provideResource', function() {
    it('provides resource objects', inject(function(configurator) {
      configurator.configuration = conf1;
      var perseidsResource = configurator.provideResource('perseids');

      expect(perseidsResource.route).toEqual(perseidsRoute);
    }));
  });
});
<commit_msg>Add spec for configurator.shallowMerge()<commit_after>"use strict";

describe('configurator', function() {
  var mock1 = {};
  var mock2 = {};

  // stubs that mimick the markup of configuration JSON files.
  // Drawn out to different variables for easier testing, usually this
  // would come as a single file.

  var mainConf,
    morphConf,
    morphAttributes,
    morphRetrieverConf,
    perseidsRoute,
    perseidsConf,
    conf1;

  // We have to restore the conf variables before every spec,
  // as we might mangle with these values.
  beforeEach(function() {
    mainConf = {
      template: 'templates/main.html',
      retrievers: {
        'treebankRetriever': {
          resource: perseidsConf
        }
      },
      plugins: [
        'text',
        'morph'
      ]
    };

    morphConf = {
      name: 'morph',
      template: 'templates/morph.html',
      retrievers: {
        'fakeMorphRetriever' : morphRetrieverConf,
        'bspMorphRetriever' : {}
      },
      attributes: {
        fileUrl: 'configs/morph/aldt.json'
      }
    };

    morphAttributes = {
      postagSchema: []
    };

    morphRetrieverConf = {
      resource: 'morphologyService'
    };

    perseidsRoute = "http://services.perseids.org/:doc.xml";

    perseidsConf = {
      route: perseidsRoute,
      params: ["doc"]
    };

    conf1 = {
      main: mainConf,

      navbar: {
        template: 'templates/navbar.html'
      },

      plugins: {
        text: {
          name: 'text',
          main: true,
          template: 'templates/text2.html'
        },
        morph: morphConf
      },

      resources: {
        perseids: perseidsConf,
        morphologyService: {
          route: "http://services.perseids.org/bsp"
        }
      }
    };
  });

  beforeEach(module('arethusa', function($provide) {
    $provide.value('x', mock1);
    $provide.value('y', mock2);
  }));

  var $httpBackend;

  beforeEach(inject(function($injector) {
    $httpBackend = $injector.get('$httpBackend');
  }));

  var configurator;

  beforeEach(inject(function(_configurator_) {
    configurator = _configurator_;
  }));

  describe('this.defineConfiguration', function() {
    it('sets a configuration file', inject(function(configurator) {
      expect(configurator.configuration).toBeUndefined();
      configurator.defineConfiguration(conf1);
      expect(configurator.configuration).toBeDefined();
    }));

    xit('resolves references to external files inside a configuration', inject(function(configurator) {
      // the morph plugin's conf includes a fileUrl property
      expect(morphConf.attributes.fileUrl).toBeDefined();
      // the defineConfiguration function will resolve this property
      // and replace it with the contents of an external file
      $httpBackend.when('GET', morphConf.attributes.fileUrl).respond(morphAttributes);

      configurator.defineConfiguration(conf1);
      $httpBackend.flush();

      var morphAttributesConf =
        configurator.configuration.plugins.morph.attributes;

      expect(morphAttributesConf).toEqual(morphAttributes);
    }));

    xit('resolves references recursively - when an external file itself uses external files', inject(function(configurator) {
      var conf = {
        a: 1,
        fileUrl: 'x'
      };

      var file1 = {
        b: 2,
        fileUrl: 'y'
      };

      var file2 = {
        c: 3
      };

      var result = {
        a: 1,
        b: 2,
        c: 3
      };

      $httpBackend.when('GET', 'x').respond(file1);
      $httpBackend.when('GET', 'y').respond(file2);

      configurator.defineConfiguration(conf);
      $httpBackend.flush();

      expect(configurator.configuration).toEqual(result);
    }));
  });

  describe('this.mergeConfigurations', function() {
    it('merges two conf files', inject(function(configurator) {
      var conf1 = {
        x: {
          a: 1,
          d: [5],
          e: 7
        },
      };

      var conf2 = {
        x: {
          b: 2,
          d: [6],
          e: 8
        },
        y: {
          c: 3
        }
      };

      var expected = {
        x: {
          a: 1,
          b: 2,
          d: [5, 6],
          e: 8
        },
        y: {
          c: 3
        }
      };

      var actual = configurator.mergeConfigurations(conf1, conf2);
      expect(actual).toEqual(expected);
    }));
  });

  describe('this.shallowMerge', function() {
    it('shallow merges two configuration files', inject(function(configurator) {
      var conf1 = {
        main: {
          debug: true,
          showKeys: false,
          plugins: ["text", "morph"]
        },
        plugins: {
          text: {
            main: false
          },
          morph: {
            retrievers: {
              morphRetriever: {
                resource: 'x'
              }
            },
            noRetrieval: false,
            attributes: {
              pos: 'posVal'
            }
          }
        }
      };

      var conf2 = {
        main: {
          foldSidepanel: true,
          showKeys: true,
          plugins: ["text", "morph", "sg"]
        },
        plugins: {
          text: {
            main: true
          },
          morph: {
            retrievers: {
              morphRetriever: {
                resource: 'y'
              }
            },
            noRetrieval: true,
            attributes: {
              tmp: 'tmpVal'
            }
          }
        }
      };

      var result = {
        main: {
          debug: true,
          foldSidepanel: true,
          showKeys: true,
          plugins: ["text", "morph", "sg"]
        },
        plugins: {
          text: {
            main: true
          },
          morph: {
            retrievers: {
              morphRetriever: {
                resource: 'y'
              }
            },
            noRetrieval: true,
            attributes: {
              tmp: 'tmpVal'
            }
          }
        }
      };

      configurator.shallowMerge(conf1, conf2);
      expect(conf1).toEqual(result);
    }));
  });

  describe('this.configurationFor', function() {
    it('provides the configuration for a given plugin', inject(function(configurator) {
      // the configuration is usually provide from an external route
      configurator.configuration = { "text" : 'conf' };
      expect(configurator.configurationFor('text')).toEqual('conf');
    }));

    it('works on the top level (like main), as well as on sublevels (like plugins)', inject(function(configurator) {
      configurator.configuration = conf1;
      var getConf = function(name) {
        return configurator.configurationFor(name);
      };

      // main level
      expect(getConf('main')).toEqual(mainConf);
      // plugins
      expect(getConf('morph')).toEqual(morphConf);
      // resources
      expect(getConf('perseids')).toEqual(perseidsConf);
    }));
  });

  describe('this.delegateConf', function() {
    it('delegates a basic set of conf options to a given object', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      var defaultKeys = [
        'name',
        'main',
        'template',
        'external',
        'contextMenu',
        'contextMenuTemplate',
        'noView',
        'mode'
      ];

      obj.conf = configurator.configurationFor('morph');
      configurator.delegateConf(obj);

      angular.forEach(defaultKeys, function(key, i) {
        expect(obj.hasOwnProperty(key)).toBeTruthy();
      });
    }));

    it('an array of additional properties to delegate can be given', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      var results = [
        'name',
        'main',
        'template',
        'external',
        'contextMenu',
        'contextMenuTemplate',
        'noView',
        'a',
        'b'
      ];

      obj.conf = configurator.configurationFor('morph');
      configurator.delegateConf(obj, ['a', 'b']);

      angular.forEach(results, function(key, i) {
        expect(obj.hasOwnProperty(key)).toBeTruthy();
      });
    }));

    it('reads from an optional defaultConf property if need be', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {
        defaultConf: {
          contextMenu: true
        }
      };
      obj.conf = configurator.configurationFor('morph');

      configurator.delegateConf(obj);
      expect(obj.contextMenu).toBeTruthy();
    }));

    it('sets global default values', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      obj.conf = configurator.configurationFor('morph');
      configurator.delegateConf(obj);
      expect(obj.mode).toEqual('editor');
    }));

    it("defaults don't override when they shouldn't", inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      var conf = configurator.configurationFor('morph');
      obj.conf = angular.extend({ mode: 'viewer' }, conf);

      configurator.delegateConf(obj);
      expect(obj.mode).toEqual('viewer');
    }));

    it('globalDefaults can be configured', inject(function(configurator) {
      configurator.configuration = {
        main: {
          globalDefaults: {
            mode: 'customMode'
          },
          plugins: ['aPlugin']
        },
        plugins: {
          aPlugin: {}
        }
      };
      var obj = {
        conf: configurator.configurationFor('aPlugin')
      };

      configurator.delegateConf(obj);
      expect(obj.mode).toEqual('customMode');
    }));

    it('can honor sticky arguments through a third true arguemnt', function() {
      configurator.configuration = conf1;
      var obj = { conf: configurator.configurationFor('morph') };
      obj.defaultConf = {
        x: true,
        y: true
      };

      configurator.delegateConf(obj, ['x', 'y']);
      expect(obj.x).toBeTruthy();
      expect(obj.y).toBeTruthy();

      obj.x = false;
      obj.y = false;

      configurator.delegateConf(obj, ['x', 'y'], true);
      expect(obj.x).toBeFalsy();
      expect(obj.y).toBeFalsy();
    });
  });

  describe('this.getConfAndDelegate', function() {
    it('convenience fn to get conf and delegate in one step', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      configurator.getConfAndDelegate('morph', obj, ['a']);
      expect(obj.name).toEqual('morph');
      expect(obj.conf).toBeTruthy();
      expect(obj.hasOwnProperty('a')).toBeTruthy();
    }));

    it('returns the given object', inject(function(configurator) {
      configurator.configuration = conf1;
      var obj = {};
      var res = configurator.getConfAndDelegate('morph', obj);
      expect(obj).toBe(res);
    }));
  });

  describe('this.getStickyConf', function() {
    function setup() {
      configurator.configuration = conf1;
      var obj = {
       defaultConf: { preselect: true }
      };
      configurator.getStickyConf('morph', obj, ['preselect']);
      return obj;
    }

    it('acts just like getConfAndDelegate when the value is undefined', inject(function(configurator) {
      var obj = setup();
      expect(obj.preselect).toBeTruthy();
    }));

    it('will not override a manually set value on a second call', function() {
      var obj = setup();
      expect(obj.preselect).toBeTruthy();
      obj.preselect = false;
      configurator.getStickyConf('morph', obj, ['preselect']);
      expect(obj.preselect).toBeFalsy();
    });
  });

  describe('this.getService', function() {
    it('retrieves an angular instance by name', inject(function(configurator) {
      expect(configurator.getService('x')).toEqual(mock1);
    }));
  });

  describe('this.getServices', function() {
    it('retrieves an object of angular instances by name', inject(function(configurator) {
      var names = ['x', 'y'];
      var services = configurator.getServices(names);
      expect(services).toEqual({ 'x' : mock1, 'y' : mock2 });
    }));

    it('returns an empty array when no service names are given', inject(function(configurator) {
      var services = configurator.getServices(undefined);
      expect(services).toEqual([]);
    }));
  });

  describe('this.provideResource', function() {
    it('provides resource objects', inject(function(configurator) {
      configurator.configuration = conf1;
      var perseidsResource = configurator.provideResource('perseids');

      expect(perseidsResource.route).toEqual(perseidsRoute);
    }));
  });
});
<|endoftext|>


<commit_before>(function($) {
    var templates = [
        'activity',
        'activity_list',
        'alert',
        'breadcrumbs',
        'change_password',
        'collection_picklist',
        'comment',
        'comment_list',
        'copy_workfile',
        'dashboard',
        'dashboard_sidebar',
        'dashboard_workspace_list',
        'dashboard_workspace_list_footer',
		'data_table',
        'default_content_header',
        'header',
        'image_upload',
        'image_workfile_content',
        'instance_account',
        'instance_index_content_details',
        'instance_list',
        'instance_list_sidebar',
        'instance',
        'instances_edit',
        'instances_new',
        'instance_permissions',
        'link_menu',
        'list_content_details',
        'loading_section',
        'logged_in_layout',
        'login',
        'main_content',
        'notes_new',
        'notes_new_file_attachment',
        'plain_text',
        'results_console',
        'sandbox_new',
        'sandbox_new_instance_mode',
        'sandbox_new_standalone_mode',
        'schema_functions',
        'schema_metadata_list',
        'shuttle_widget',
        'sql_workfile_content',
        'sql_workfile_content_details',
        'sub_nav',
        'tab_control',
        'text_workfile_content',
        'truncated_text',
        'user_edit',
        'user_list',
        'user_new',
        'user_show',
        'user_show_sidebar',
        'validating',
        'workfile_content_details',
        'workfile_header',
        'workfile_list',
        'workfile_list_sidebar',
        'workfile_new_version',
        'workfile_show_sidebar',
        'workfiles_import',
        'workfiles_sql_new',
        'workfiles_attach',
        'workspace_detail',
        'workspace_edit_members',
        'workspace_index_content_header',
        'workspace_list',
        'workspace_members_more',
        'workspace_settings',
        'workspace_summary_sidebar',
        'workspaces_new'
    ];

    var loadTemplatesOnce = _.once(function() {
        var allTemplatesLoaded = false;

        runs(loadAllTemplates);
        waitsFor(function() {
            return allTemplatesLoaded;
        }, "all templates to be loaded", 1000);

        function loadAllTemplates() {
            var templateContainer = $("
");
            var requests = _.map(templates, function(templateName) {
                return $.ajax({
                    async: true,
                    cache: false,
                    dataType: 'html',
                    url: '/templates/' + templateName + '.handlebars',
                    success: function(data) {
                        templateContainer.append('');
                    },
                    error: function(data) {
                        alert("The template '" + templateName + "' does not exist. You need to remove it from the spec helper, bro.");
                    }
                });
            });

            $.when.apply($, requests).done(function() {
                $("body").append(templateContainer);
                allTemplatesLoaded = true;
            });
        };
    });

    beforeEach(function() {
        loadTemplatesOnce();

        // loadTemplatesOnce does asynchronous ajax requests in a waitsFor
        runs(function() {
            this.server = sinon.fakeServer.create();
            chorus.router.unbind();

            this.renderDOM = function(content) {
                return $('#jasmine_content').html(content);
            };

            clearRenderedDOM();

            this.addMatchers({
                toBeA: function(klass) {
                    return this.actual instanceof klass;
                },

                toBeEnabled: function() {
                    return this.actual.is(':not(:disabled)');
                },

                toMatchTranslation: function(translationKey) {
                    var translatedText = t.apply(this, arguments);
                    this.message = function() {
                        return [
                        "Expected text '" + this.actual + "' to match the translation for '" + translationKey + "' (" + translatedText + ")",
                        "Expected text '" + this.actual + "' not to match the translation for '" + translationKey + "' (" + translatedText +")"
                        ];
                    };
                    if (!I18n.lookup(translationKey)) {
                        throw("No entry in messages.properties for " + translationKey);
                    }

                    return this.actual === translatedText;
                },

                toContainTranslation: function(translationKey) {
                    var actual = _.isString(this.actual) ? this.actual : this.actual.text();
                    var translatedText = t.apply(this, arguments);
                    this.message = function() {
                        return [
                        "Expected text '" + actual + "' to contain the translation for '" + translationKey + "' (" + translatedText + ")",
                        "Expected text '" + actual + "' not to contain the translation for '" + translationKey + "' (" + translatedText +")"
                        ];
                    };
                    if (translatedText === '[' + translationKey + ']') {
                        throw("No entry in messages.properties for " + translationKey);
                    }

                    return this.env.contains_(actual, translatedText);
                },

                toHaveBeenCalledOnSelector: function(selector) {
                    return this.actual.mostRecentCall.object.selector === selector;
                },

                toContainText: function(text) {
                    this.message = function() {
                        return 'Expected "' + this.actual.text() + '" to contain "' + text + '"';
                    }
                    return this.env.contains_(this.actual.text(), text);
                },

                toHaveBeenTriggeredOn: function(target, args) {
                    var eventName = this.actual;
                    this.message = function() {
                        return [
                            "Expected event " + eventName + " to have been triggered on " + target,
                            "Expected event " + eventName + " not to have been triggered on " + target
                        ];
                    };
                    if (_.isString(target) || target instanceof jQuery) {
                        return jasmine.JQuery.events.wasTriggered(target, eventName);
                    } else {
                        if (target._chorusEventSpies && target._chorusEventSpies[eventName]) {
                            var call = _.last(target._chorusEventSpies[eventName].calls);
                            if (!call) return false;
                            if (args && !_.isEqual(call.args, args)) return false;
                            return true;
                        } else {
                            throw "The event '" + eventName + "' has not been spied on, for the object " + target;
                        }
                    }
                },

                toMatchUrl : function(target) {
                    this.message = function() {
                        return [
                            "Expected url " + this.actual + " to be equivalent to url " + target,
                            "Expected url " + this.actual + " not to be equivalent to url " + target
                        ];
                    }

                    return (new URI(this.actual)).equals(target);
                },

                toHaveVisibleQtip : function() {
                    return this.actual.find('.qtip').attr('aria-hidden') == 'false'
                },

                toHaveBeenFetched : function() {
                    return this.spec.server.lastFetchFor(this.actual);
                }
            });

            var fakeSpinner = {
                spin : jasmine.createSpy('MockSpinner.spin').andCallFake(function(parentEl) {
                    this.el = $('
')[0];
                    parentEl && parentEl.appendChild(this.el);
                    return this;
                }),

                stop : jasmine.createSpy('MockSpinner.stop').andCallFake(function() {
                    if (this.el) {
                        $(this.el).detach();
                    }
                })
            };

            window.Spinner = jasmine.createSpy('MockSpinner').andCallFake(function() {
                return fakeSpinner
            });

            spyOn($.fn, 'jGrowl');

            setLoggedInUser();
        });
    });

    afterEach(function() {
        this.server.restore();
        this.clock && this.clock.restore && this.clock.restore();
        $.cookie("userId", null)
    });

    //global helpers
    window.context = window.describe;
    window.xcontext = window.xdescribe;
    window.specify = window.it;
    window.xspecify = window.xit;

    window.unsetLoggedInUser = function() {
        chorus.session.unset("id");
        delete chorus.session._user;
    };

    var jquerySpyOnEvent = window.spyOnEvent;
    var backboneSpyOnEvent = function(object, name) {
        var eventSpy = jasmine.createSpy(name + "Spy");
        object.bind(name, eventSpy);
        object._chorusEventSpies || (object._chorusEventSpies = {});
        object._chorusEventSpies[name] = eventSpy;
        return eventSpy;
    };

    window.spyOnEvent = function(object) {
        if (object.bind === Backbone.Events.bind) {
            return backboneSpyOnEvent.apply(this, arguments);
        } else {
            return jquerySpyOnEvent.apply(this, arguments);
        }
    }

    window.setLoggedInUser = function(options) {
        chorus.session._user = new chorus.models.User(_.extend({
            userName: 'edcadmin'
        }, options));
        chorus.session.set({id: chorus.session._user.get('id')});
    };

    window.stubView = function(html) {
        var stubClass = Backbone.View.extend({
            initialize : function() {
                _.bindAll(this, "render")
            },

            render :  function() {
                this.$(this.el).html(html)
                return this;
            }
        });

        return new stubClass
    }

    window.stubModals = function() {
        var spy = spyOn($, "facebox");
        spy.settings = {}
        return spy;
    };

    window.stubQtip = function() {
        var qtip = $.fn.qtip;
        var qtipElement = $('

');
        $('#jasmine_content').append(qtipElement);
        spyOn($.fn, 'qtip').andCallFake(function() {
            var args = arguments;
            if(_.isObject(args[0])) {
                args[0].show || (args[0].show = {});
                args[0].show.delay = 0;
                args[0].position || (args[0].position = {});
                args[0].position.container = qtipElement
            }
            qtip.apply(this, args);
        })
        return qtipElement;
    }

    if ( $.browser.msie && !window['con' + 'sole'] ) {
      (function(F,i,r,e,b,u,g,L,I,T,E){if(F.getElementById(b))return;E=F[i+'NS']&&F.documentElement.namespaceURI;E=E?F[i+'NS'](E,'script'):F[i]('script');E[r]('id',b);E[r]('src',I+g+T);E[r](b,u);(F[e]('head')[0]||F[e]('body')[0]).appendChild(E);E=new Image;E[r]('src',I+L);})(document,'createElement','setAttribute','getElementsByTagName','FirebugLite','4','firebug-lite.js','releases/lite/latest/skin/xp/sprite.png','/firebug-lite/build/','#startOpened');
    }

    // Don't change urls in specs
    Backbone.History.prototype.navigate = function(fragment, triggerRoute) {
        if (triggerRoute) this.loadUrl(fragment);
    };

    //initialization
    ;(function safeStart() {

        var origLogin = chorus.requireLogin;
        var origHistory = chorus.startHistory;
        chorus.requireLogin = $.noop;
        chorus.startHistory = $.noop;

        chorus.initialize();

        chorus.requireLogin = origLogin;
        chorus.startHistory = origHistory;

    })();

    function clearRenderedDOM() {
        $('#jasmine_content').empty();
    }

})(jQuery);
<commit_msg>Fix failure message for toHaveBeenTriggered on when args are passed<commit_after>(function($) {
    var templates = [
        'activity',
        'activity_list',
        'alert',
        'breadcrumbs',
        'change_password',
        'collection_picklist',
        'comment',
        'comment_list',
        'copy_workfile',
        'dashboard',
        'dashboard_sidebar',
        'dashboard_workspace_list',
        'dashboard_workspace_list_footer',
		'data_table',
        'default_content_header',
        'header',
        'image_upload',
        'image_workfile_content',
        'instance_account',
        'instance_index_content_details',
        'instance_list',
        'instance_list_sidebar',
        'instance',
        'instances_edit',
        'instances_new',
        'instance_permissions',
        'link_menu',
        'list_content_details',
        'loading_section',
        'logged_in_layout',
        'login',
        'main_content',
        'notes_new',
        'notes_new_file_attachment',
        'plain_text',
        'results_console',
        'sandbox_new',
        'sandbox_new_instance_mode',
        'sandbox_new_standalone_mode',
        'schema_functions',
        'schema_metadata_list',
        'shuttle_widget',
        'sql_workfile_content',
        'sql_workfile_content_details',
        'sub_nav',
        'tab_control',
        'text_workfile_content',
        'truncated_text',
        'user_edit',
        'user_list',
        'user_new',
        'user_show',
        'user_show_sidebar',
        'validating',
        'workfile_content_details',
        'workfile_header',
        'workfile_list',
        'workfile_list_sidebar',
        'workfile_new_version',
        'workfile_show_sidebar',
        'workfiles_import',
        'workfiles_sql_new',
        'workfiles_attach',
        'workspace_detail',
        'workspace_edit_members',
        'workspace_index_content_header',
        'workspace_list',
        'workspace_members_more',
        'workspace_settings',
        'workspace_summary_sidebar',
        'workspaces_new'
    ];

    var loadTemplatesOnce = _.once(function() {
        var allTemplatesLoaded = false;

        runs(loadAllTemplates);
        waitsFor(function() {
            return allTemplatesLoaded;
        }, "all templates to be loaded", 1000);

        function loadAllTemplates() {
            var templateContainer = $("
");
            var requests = _.map(templates, function(templateName) {
                return $.ajax({
                    async: true,
                    cache: false,
                    dataType: 'html',
                    url: '/templates/' + templateName + '.handlebars',
                    success: function(data) {
                        templateContainer.append('');
                    },
                    error: function(data) {
                        alert("The template '" + templateName + "' does not exist. You need to remove it from the spec helper, bro.");
                    }
                });
            });

            $.when.apply($, requests).done(function() {
                $("body").append(templateContainer);
                allTemplatesLoaded = true;
            });
        };
    });

    beforeEach(function() {
        loadTemplatesOnce();

        // loadTemplatesOnce does asynchronous ajax requests in a waitsFor
        runs(function() {
            this.server = sinon.fakeServer.create();
            chorus.router.unbind();

            this.renderDOM = function(content) {
                return $('#jasmine_content').html(content);
            };

            clearRenderedDOM();

            this.addMatchers({
                toBeA: function(klass) {
                    return this.actual instanceof klass;
                },

                toBeEnabled: function() {
                    return this.actual.is(':not(:disabled)');
                },

                toMatchTranslation: function(translationKey) {
                    var translatedText = t.apply(this, arguments);
                    this.message = function() {
                        return [
                        "Expected text '" + this.actual + "' to match the translation for '" + translationKey + "' (" + translatedText + ")",
                        "Expected text '" + this.actual + "' not to match the translation for '" + translationKey + "' (" + translatedText +")"
                        ];
                    };
                    if (!I18n.lookup(translationKey)) {
                        throw("No entry in messages.properties for " + translationKey);
                    }

                    return this.actual === translatedText;
                },

                toContainTranslation: function(translationKey) {
                    var actual = _.isString(this.actual) ? this.actual : this.actual.text();
                    var translatedText = t.apply(this, arguments);
                    this.message = function() {
                        return [
                        "Expected text '" + actual + "' to contain the translation for '" + translationKey + "' (" + translatedText + ")",
                        "Expected text '" + actual + "' not to contain the translation for '" + translationKey + "' (" + translatedText +")"
                        ];
                    };
                    if (translatedText === '[' + translationKey + ']') {
                        throw("No entry in messages.properties for " + translationKey);
                    }

                    return this.env.contains_(actual, translatedText);
                },

                toHaveBeenCalledOnSelector: function(selector) {
                    return this.actual.mostRecentCall.object.selector === selector;
                },

                toContainText: function(text) {
                    this.message = function() {
                        return 'Expected "' + this.actual.text() + '" to contain "' + text + '"';
                    }
                    return this.env.contains_(this.actual.text(), text);
                },

                toHaveBeenTriggeredOn: function(target, args) {
                    var call, eventName = this.actual;

                    if (args) {
                        this.message = function() {
                            if (call) {
                                return [
                                    "Expected event " + eventName + " to have been triggered on " + target + " with" + args + " but was triggered with " + call.args,
                                    "Expected event " + eventName + " not to have been triggered on " + target + " with" + args + " but was triggered with " + call.args
                                ];
                            } else {
                                return [
                                    "Expected event " + eventName + " to have been triggered on " + target + " with" + args + " but it was never triggered",
                                    "Expected event " + eventName + " not to have been triggered on " + target + " with" + args + " but was triggered with " + call.args
                                ];
                            }
                        }
                    } else {
                        this.message = function() {
                            return [
                                "Expected event " + eventName + " to have been triggered on " + target,
                                "Expected event " + eventName + " not to have been triggered on " + target
                            ];
                        }
                    }

                    if (_.isString(target) || target instanceof jQuery) {
                        return jasmine.JQuery.events.wasTriggered(target, eventName);
                    } else if (target._chorusEventSpies && target._chorusEventSpies[eventName]) {
                        call = _.last(target._chorusEventSpies[eventName].calls);
                        if (!call) return false;
                        if (args)  return (_.isEqual(call.args, args));
                        return true;
                    } else {
                        throw "The event '" + eventName + "' has not been spied on, for the object " + target;
                    }
                },

                toMatchUrl : function(target) {
                    this.message = function() {
                        return [
                            "Expected url " + this.actual + " to be equivalent to url " + target,
                            "Expected url " + this.actual + " not to be equivalent to url " + target
                        ];
                    }

                    return (new URI(this.actual)).equals(target);
                },

                toHaveVisibleQtip : function() {
                    return this.actual.find('.qtip').attr('aria-hidden') == 'false'
                },

                toHaveBeenFetched : function() {
                    return this.spec.server.lastFetchFor(this.actual);
                }
            });

            var fakeSpinner = {
                spin : jasmine.createSpy('MockSpinner.spin').andCallFake(function(parentEl) {
                    this.el = $('
')[0];
                    parentEl && parentEl.appendChild(this.el);
                    return this;
                }),

                stop : jasmine.createSpy('MockSpinner.stop').andCallFake(function() {
                    if (this.el) {
                        $(this.el).detach();
                    }
                })
            };

            window.Spinner = jasmine.createSpy('MockSpinner').andCallFake(function() {
                return fakeSpinner
            });

            spyOn($.fn, 'jGrowl');

            setLoggedInUser();
        });
    });

    afterEach(function() {
        this.server.restore();
        this.clock && this.clock.restore && this.clock.restore();
        $.cookie("userId", null)
    });

    //global helpers
    window.context = window.describe;
    window.xcontext = window.xdescribe;
    window.specify = window.it;
    window.xspecify = window.xit;

    window.unsetLoggedInUser = function() {
        chorus.session.unset("id");
        delete chorus.session._user;
    };

    var jquerySpyOnEvent = window.spyOnEvent;
    var backboneSpyOnEvent = function(object, name) {
        var eventSpy = jasmine.createSpy(name + "Spy");
        object.bind(name, eventSpy);
        object._chorusEventSpies || (object._chorusEventSpies = {});
        object._chorusEventSpies[name] = eventSpy;
        return eventSpy;
    };

    window.spyOnEvent = function(object) {
        if (object.bind === Backbone.Events.bind) {
            return backboneSpyOnEvent.apply(this, arguments);
        } else {
            return jquerySpyOnEvent.apply(this, arguments);
        }
    }

    window.setLoggedInUser = function(options) {
        chorus.session._user = new chorus.models.User(_.extend({
            userName: 'edcadmin'
        }, options));
        chorus.session.set({id: chorus.session._user.get('id')});
    };

    window.stubView = function(html) {
        var stubClass = Backbone.View.extend({
            initialize : function() {
                _.bindAll(this, "render")
            },

            render :  function() {
                this.$(this.el).html(html)
                return this;
            }
        });

        return new stubClass
    }

    window.stubModals = function() {
        var spy = spyOn($, "facebox");
        spy.settings = {}
        return spy;
    };

    window.stubQtip = function() {
        var qtip = $.fn.qtip;
        var qtipElement = $('

');
        $('#jasmine_content').append(qtipElement);
        spyOn($.fn, 'qtip').andCallFake(function() {
            var args = arguments;
            if(_.isObject(args[0])) {
                args[0].show || (args[0].show = {});
                args[0].show.delay = 0;
                args[0].position || (args[0].position = {});
                args[0].position.container = qtipElement
            }
            qtip.apply(this, args);
        })
        return qtipElement;
    }

    if ( $.browser.msie && !window['con' + 'sole'] ) {
      (function(F,i,r,e,b,u,g,L,I,T,E){if(F.getElementById(b))return;E=F[i+'NS']&&F.documentElement.namespaceURI;E=E?F[i+'NS'](E,'script'):F[i]('script');E[r]('id',b);E[r]('src',I+g+T);E[r](b,u);(F[e]('head')[0]||F[e]('body')[0]).appendChild(E);E=new Image;E[r]('src',I+L);})(document,'createElement','setAttribute','getElementsByTagName','FirebugLite','4','firebug-lite.js','releases/lite/latest/skin/xp/sprite.png','/firebug-lite/build/','#startOpened');
    }

    // Don't change urls in specs
    Backbone.History.prototype.navigate = function(fragment, triggerRoute) {
        if (triggerRoute) this.loadUrl(fragment);
    };

    //initialization
    ;(function safeStart() {

        var origLogin = chorus.requireLogin;
        var origHistory = chorus.startHistory;
        chorus.requireLogin = $.noop;
        chorus.startHistory = $.noop;

        chorus.initialize();

        chorus.requireLogin = origLogin;
        chorus.startHistory = origHistory;

    })();

    function clearRenderedDOM() {
        $('#jasmine_content').empty();
    }

})(jQuery);
<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------

//@Package('bugpack')

//@Export('BugPackKey')

//@Require('Class')
//@Require('Obj')

//-------------------------------------------------------------------------------
// Common Modules
//-------------------------------------------------------------------------------

var bugpack         = require('bugpack').context();

//-------------------------------------------------------------------------------
// BugPack
//-------------------------------------------------------------------------------

var Class           = bugpack.require('Class');
var Obj             = bugpack.require('Obj');

//-------------------------------------------------------------------------------
// Declare Class
//-------------------------------------------------------------------------------

var BugPackKey= Class.extend(Obj, {

    //-------------------------------------------------------------------------------
    // Constructor
    //-------------------------------------------------------------------------------

    /**
     * @constructs
     * @param {string} key
     */
    _constructor: function(key) {

        this._super();

        //-------------------------------------------------------------------------------
        // Private Properties
        //-------------------------------------------------------------------------------

        /**
         * @private
         * @type {string}
         */
        this.key = key;

        var keyParts = key.split('.');
        var packageName = ".";
        var exportName = keyParts.pop();
        if (keyParts.length > 0) {
            packageName = keyParts.join('.');
        }

        /**
         * @private
         * @type {string}
         */
        this.exportName = exportName;

        /**
         * @private
         * @type {String}
         */
        this.packageName = packageName;
    },

    //-------------------------------------------------------------------------------
    // Getters and Setters
    //-------------------------------------------------------------------------------

    /**
     * @return {string}
     */
    getKey: function() {
        return this.key;
    },

    /**
     * @return {string}
     */
    getExportName: function() {
        return this.exportName;
    },

    /**
     * @return {string}
     */
    getPackageName: function() {
        return this.packageName;
    },

    /**
     * @return {boolean}
     */
    isWildCard: function() {
        return (this.exportName === "*");
    }
});

//-------------------------------------------------------------------------------
// Exports
//-------------------------------------------------------------------------------

bugpack.export('bugpack.BugPackKey', BugPackKey);
<commit_msg>Add missing space<commit_after>//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------

//@Package('bugpack')

//@Export('BugPackKey')

//@Require('Class')
//@Require('Obj')

//-------------------------------------------------------------------------------
// Common Modules
//-------------------------------------------------------------------------------

var bugpack         = require('bugpack').context();

//-------------------------------------------------------------------------------
// BugPack
//-------------------------------------------------------------------------------

var Class           = bugpack.require('Class');
var Obj             = bugpack.require('Obj');

//-------------------------------------------------------------------------------
// Declare Class
//-------------------------------------------------------------------------------

var BugPackKey = Class.extend(Obj, {

    //-------------------------------------------------------------------------------
    // Constructor
    //-------------------------------------------------------------------------------

    /**
     * @constructs
     * @param {string} key
     */
    _constructor: function(key) {

        this._super();

        //-------------------------------------------------------------------------------
        // Private Properties
        //-------------------------------------------------------------------------------

        /**
         * @private
         * @type {string}
         */
        this.key = key;

        var keyParts = key.split('.');
        var packageName = ".";
        var exportName = keyParts.pop();
        if (keyParts.length > 0) {
            packageName = keyParts.join('.');
        }

        /**
         * @private
         * @type {string}
         */
        this.exportName = exportName;

        /**
         * @private
         * @type {String}
         */
        this.packageName = packageName;
    },

    //-------------------------------------------------------------------------------
    // Getters and Setters
    //-------------------------------------------------------------------------------

    /**
     * @return {string}
     */
    getKey: function() {
        return this.key;
    },

    /**
     * @return {string}
     */
    getExportName: function() {
        return this.exportName;
    },

    /**
     * @return {string}
     */
    getPackageName: function() {
        return this.packageName;
    },

    /**
     * @return {boolean}
     */
    isWildCard: function() {
        return (this.exportName === "*");
    }
});

//-------------------------------------------------------------------------------
// Exports
//-------------------------------------------------------------------------------

bugpack.export('bugpack.BugPackKey', BugPackKey);
<|endoftext|>


<commit_before>var mongojs = require('mongojs');
var db = require('../config').db;

var db_clients = mongojs(db + 'clients', ['clients']);

module.exports = {
    getAll: getAll,
    search: search,
    add: add,
    getOne: getOne,
    update: update,
    delete: deleteOne
};

function getAll(req, res) {
    db_clients.clients.find(function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });
};

function search(req, res) {
    db_clients.clients.aggregate([
        { $match: { $text: { $search: req.params.query} } },
        { $sort: { score: { $meta: "textScore" } } }
    ], function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });

};

function add(req, res) {
    req.body.createdOn = new Date();
    req.body.updatedOn = new Date();

    db_clients.clients.insert(req.body, function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });
};

function getOne(req, res) {
    db_clients.clients.findOne({ _id: mongojs.ObjectId(req.params.id) }, function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });
};

function update(req, res) {
    var updatedOn = new Date();

    db_clients.clients.findAndModify({
        query: { _id: mongojs.ObjectId(req.params.id) },
        update: {
            $set: {
                firstName: req.body.firstName,
                lastName: req.body.lastName,
                dateOfBirth: req.body.dateOfBirth,
                phoneNumber: req.body.phoneNumber,
                email: req.body.email,
                skinType: req.body.skinType,
                previousMedicalConditions: req.body.previousMedicalConditions,
                previousTreatments: req.body.previousTreatments,
                skinCareProductsUsed: req.body.skinCareProductsUsed,
                discovery: req.body.discovery,
                history: req.body.history,
                isVip: req.body.isVip,
                vip: req.body.vip,
                updatedOn: updatedOn,
                createdOn: req.body.createdOn
            }
        },
        new: true
    }, function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });
};

function deleteOne(req, res) {
    db_clients.clients.remove({ _id: mongojs.ObjectId(req.params.id) }, function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });
};

<commit_msg>- cleared update method in clients route<commit_after>var mongojs = require('mongojs');
var db = require('../config').db;

var db_clients = mongojs(db + 'clients', ['clients']);

module.exports = {
    getAll: getAll,
    search: search,
    add: add,
    getOne: getOne,
    update: update,
    delete: deleteOne
};

function getAll(req, res) {
    db_clients.clients.find(function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });
};

function search(req, res) {
    db_clients.clients.aggregate([
        { $match: { $text: { $search: req.params.query} } },
        { $sort: { score: { $meta: "textScore" } } }
    ], function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });

};

function add(req, res) {
    req.body.createdOn = new Date();
    req.body.updatedOn = new Date();

    db_clients.clients.insert(req.body, function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });
};

function getOne(req, res) {
    db_clients.clients.findOne({ _id: mongojs.ObjectId(req.params.id) }, function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });
};

function update(req, res) {
    delete req.body._id;
	req.body.updatedOn = new Date();

    db_clients.clients.findAndModify({
        query: { _id: mongojs.ObjectId(req.params.id) },
        update: {
            $set: req.body
        },
        new: true
    }, function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });
};

function deleteOne(req, res) {
    db_clients.clients.remove({ _id: mongojs.ObjectId(req.params.id) }, function(err, doc) {
        if (err) { console.log('Error: ', err); };
        res.json(doc);
    });
};

<|endoftext|>


<commit_before>var item_description;

(function(Browser) {

	Browser.Items = Browser.Items || {};
	Browser.Items.Views = Browser.Items || {};

	Browser.Items.Views.List = Backbone.View.extend({

		tagName : 'tr',
		className : 'list-media list-fancymedia',

		initialize: function () {

			this.el.id = this.model.id;

			//list item has a thumbnail item with same model as a subview
			this.thumbnailView = new Browser.Items.Views.Thumb({
				model:this.model,
				thumbnail_width:100,
				thumbnail_height:80,
				show_caption:false,
				fancybox:false,
				draggable:false
			});

		},

		render: function ( done )
		{
			var _this = this;

			var template;
			switch( this.model.get('media_type') )
			{
				case 'Image':
					template = this.getImageTemplate();
					break;
				case 'Document':
					template = this.getDefaultTemplate();
					break;
				case 'Website':
					template = this.getWebsiteTemplate();
					break;
				case 'Tweet':
					template = this.getTweetTemplate();
					break;
				case 'Text':
					template = this.getTestimonialTemplate();
					break;
				case 'Video':
					template = this.getDefaultTemplate();
					break;
				case 'Audio':
					template = this.getDefaultTemplate();
					break;
				case 'PDF':
					template = this.getDefaultTemplate();
					break;
				case 'Collection':
					$(this.el).removeClass('list-fancymedia');
					template = this.getCollectionTemplate();
					break;

				default:
					template = this.getDefaultTemplate();
			}

			var blanks = this.model.attributes;

			if (!_.isUndefined(this.model.get("media_date_created"))&&!_.isNull(this.model.get("media_date_created"))){
				blanks["media_date"] = new Date(this.model.get("media_date_created").replace(" ", "T"));
				blanks["media_date"]=blanks["media_date"].format("mmmm dS, yyyy
h:MM TT");
			} else {
				blanks["media_date"] = "n/a";
			}
			if (this.model.get("text") !== null){
				var excerpt = this.model.get("text").replace(/\r\n/gi, '
');
				blanks["text"] = this.linkifyTweet(excerpt);

			}
			if (this.model.get("description") === null){
				blanks["description"] = " ";
			}
			if (this.model.get("description") !== null && this.model.get("description").length > 255){
				blanks["description"] = this.model.get("description").substring(0,255) + "...";
			}
			if (this.model.get("title") === null || this.model.get("title") == "none" || this.model.get("title") === ""){
				blanks["title"] = "";
			}
			// Checks if the media username is rijs and switches it to media creator username
			if (this.model.get("media_creator_username") === "rijs"){
				blanks["media_creator_username"] = this.model.get("media_creator_realname");
			}

			if (this.model.get("media_creator_realname") === null || this.model.get("media_creator_realname") === "" || this.model.get("media_creator_realname") == "Unknown" || this.model.get("media_creator_realname") == "unknown"){
				blanks["author"] = this.model.get("media_creator_username");
			} else {
				blanks["author"] = this.model.get("media_creator_realname");
			}
			if (this.model.get('attributes')) {
			    if (this.model.get('attributes').privacy) {
			        if (this.model.get('attributes').privacy == 'Hide') {
			            blanks["author"] = "Anonymous";
			        }
			    }
			}

			if (this.model.get("media_type") == "Text" && this.model.get('description').length < this.model.get('text').length){
				blanks["description"] = this.model.get('description') + '...';
			}

			if (this.model.get("media_type") == "Website"){
				var parts = this.model.get('attribution_uri').split('http');
				blanks["original_url"] = parts[2] !== undefined ? "http" + parts[2] : this.model.get('attribution_uri');
			}

			//console.log(this.model.get("description"));
			var text = document.getElementById("search").textContent;
			var old_arr = text.split("");
			var substitute = "";
			var new_arr = [];

			for (var i = 0; i < old_arr.length; i++)
			{
				if (old_arr[i].match(/[A-Za-z]+/) != null)
				{
					substitute = substitute.concat(old_arr[i][0]);

					if (old_arr[i + 1].match(/[A-Za-z]+/) == null)
					{
						new_arr.push(substitute);
						substitute = "";
					}
				}
			}

			// Gets rid of the unnecessary "text:" string
			new_arr.splice(0,1);
			item_description = this.model.get("description");

			var pre_string;
			var searched_term;
			var end_string;

			for (var k = 0; k < new_arr.length; k++)
			{
				if (item_description.indexOf(new_arr[k]) != -1)
				{
					pre_string = item_description.substring(0,item_description.indexOf(new_arr[k]));
					searched_term = item_description.substring(item_description.indexOf(new_arr[k]), item_description.indexOf(new_arr[k]) + new_arr[k].length);
					end_string = item_description.substring(item_description.indexOf(new_arr[k]) + new_arr[k].length, item_description.length);
					item_description = pre_string + '' + '' + searched_term + '' + '' + end_string;
				}
			}

			$(this.el).html( _.template( template, blanks ) );

			$(this.el).find('.zeega-item-thumbnail').append(this.thumbnailView.render().el);

			if (blanks["author"] === ""){
				$(this.el).find('.jda-item-author').hide();
			}

			if (this.model.get("media_type") == "Collection"){
				this.draggable=false;
			}
			else {
				this.draggable=true;
			}

			if(this.draggable){
				$(this.el).draggable({
					cursor : 'crosshair',
					cursorAt : {
						top : 50,
						left : 50
					},
					appendTo : 'body',
					opacity : 0.8,

					helper : function(){
						var drag = $(this).find('.thumbnail')
						.clone()
						.css({
							'z-index':'101'
						});
						return drag;
					},

					//init the dragged item variable
					start : function(){
						$(this).draggable('option','revert',true);
						jda.app.draggedItem = _this.model;
					}
			});
			}
			$(this.el).find(".jdicon-small-drag").tooltip({'title':'Drag to add to your collection','placement':'bottom', delay: { show: 600, hide: 100 }});

			if( blanks["display_name"] === ""){
				$(this.el).find(".jda-user-link").hide();
			} else {
				$(this.el).find(".jda-user-link").click(function(){jda.app.goToUser(_this.model.get('user_id')); return false;});
			}

			return this;
		},

		/* formats tweet text, doesn't linkify bc tweet is already linked to fancybox */
		linkifyTweet : function(tweet){

			// urls
			var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
			tweet = tweet.replace(exp,"$1");

			// users
			tweet = tweet.replace(/(^|)@(\w+)/gi, function (s) {
				return '' + s + '';
			});

			// tags
			tweet = tweet.replace(/(^|)#(\w+)/gi, function (s) {
				return '' + s + '';
			});

			return tweet;
		},

		getImageTemplate : function()
		{
			console.log("I got here1");
			console.log(item_description);
			html =

			''+
				'

'+
			'	'+
			''+
				'
<%= title %>

by: <%= author %>'+
				'
' + item_description +'
'+
			'	'+
			'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
				'

via <%= display_name %>

'+
			'	';

			return html;
		},

		getDefaultTemplate : function()
		{
			console.log("I got here2");
			console.log(item_description);

			html =

			''+
				'

'+
			'	'+
			''+
				'
<%= title %>

by: <%= author %>
'+
				'
' + item_description +'
'+
			'	'+
			'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
			'

via <%= display_name %>

'+
			'	';

			return html;
		},

		getDocumentTemplate : function()
		{

			console.log("I got here3");
			console.log(item_description);
			html =

			''+
				''+
				'
<%= author %>
'+
			'	'+
			''+
				'
<%= title %>
'+
				'
' + item_description + '
'+
			'	'+
			''+
				'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
				'

via <%= display_name %>

'+
			'	';

			return html;
		},

		getWebsiteTemplate : function()
		{
			console.log("I got here4");
			console.log(item_description);
			html =

			''+
				'

'+
			'	'+
			''+
				'
<%= title %>
'+
				'
<%= original_url %>
'+
				'
' + item_description + '
'+
			'	'+
			''+
				'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
				'

via <%= display_name %>

'+
			'	';

			return html;
		},

		getTweetTemplate : function()
		{
			console.log("I got here5");
			console.log(item_description);
			html =

			''+
				'

'+
			'	'+
			''+
				'
' + item_description +'
'+
			'	'+
			'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
				'

via <%= display_name %>

'+
			'	';

			return html;
		},

		getTestimonialTemplate : function()
		{
			console.log("I got here6");
			console.log(item_description);
			html =
			''+
				'

'+
			'	'+
			''+
				'
<%= title %>

Testimonial by: <%= author %>
'+
				'
' + item_description + '
'+
			'	'+
			'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
				'

via <%= display_name %>

'+
			'	';
			return html;
		},

		getCollectionTemplate : function()
		{
			console.log("I got here7");
			console.log(item_description);
			html =

				''+
				'

'+
				'	'+
				''+
					'
<%= title %>

by <%= display_name %>
'+
					'
' + item_description + '
'+
				'	'+
				'<%= media_date %>'+
					'<input class="jda-item-checkbox" type="checkbox">'+
				'	';

			return html;
		}

	});

})(jda.module("browser"));
<commit_msg>Changing to underline<commit_after>var item_description;

(function(Browser) {

	Browser.Items = Browser.Items || {};
	Browser.Items.Views = Browser.Items || {};

	Browser.Items.Views.List = Backbone.View.extend({

		tagName : 'tr',
		className : 'list-media list-fancymedia',

		initialize: function () {

			this.el.id = this.model.id;

			//list item has a thumbnail item with same model as a subview
			this.thumbnailView = new Browser.Items.Views.Thumb({
				model:this.model,
				thumbnail_width:100,
				thumbnail_height:80,
				show_caption:false,
				fancybox:false,
				draggable:false
			});

		},

		render: function ( done )
		{
			var _this = this;

			var template;
			switch( this.model.get('media_type') )
			{
				case 'Image':
					template = this.getImageTemplate();
					break;
				case 'Document':
					template = this.getDefaultTemplate();
					break;
				case 'Website':
					template = this.getWebsiteTemplate();
					break;
				case 'Tweet':
					template = this.getTweetTemplate();
					break;
				case 'Text':
					template = this.getTestimonialTemplate();
					break;
				case 'Video':
					template = this.getDefaultTemplate();
					break;
				case 'Audio':
					template = this.getDefaultTemplate();
					break;
				case 'PDF':
					template = this.getDefaultTemplate();
					break;
				case 'Collection':
					$(this.el).removeClass('list-fancymedia');
					template = this.getCollectionTemplate();
					break;

				default:
					template = this.getDefaultTemplate();
			}

			var blanks = this.model.attributes;

			if (!_.isUndefined(this.model.get("media_date_created"))&&!_.isNull(this.model.get("media_date_created"))){
				blanks["media_date"] = new Date(this.model.get("media_date_created").replace(" ", "T"));
				blanks["media_date"]=blanks["media_date"].format("mmmm dS, yyyy
h:MM TT");
			} else {
				blanks["media_date"] = "n/a";
			}
			if (this.model.get("text") !== null){
				var excerpt = this.model.get("text").replace(/\r\n/gi, '
');
				blanks["text"] = this.linkifyTweet(excerpt);

			}
			if (this.model.get("description") === null){
				blanks["description"] = " ";
			}
			if (this.model.get("description") !== null && this.model.get("description").length > 255){
				blanks["description"] = this.model.get("description").substring(0,255) + "...";
			}
			if (this.model.get("title") === null || this.model.get("title") == "none" || this.model.get("title") === ""){
				blanks["title"] = "";
			}
			// Checks if the media username is rijs and switches it to media creator username
			if (this.model.get("media_creator_username") === "rijs"){
				blanks["media_creator_username"] = this.model.get("media_creator_realname");
			}

			if (this.model.get("media_creator_realname") === null || this.model.get("media_creator_realname") === "" || this.model.get("media_creator_realname") == "Unknown" || this.model.get("media_creator_realname") == "unknown"){
				blanks["author"] = this.model.get("media_creator_username");
			} else {
				blanks["author"] = this.model.get("media_creator_realname");
			}
			if (this.model.get('attributes')) {
			    if (this.model.get('attributes').privacy) {
			        if (this.model.get('attributes').privacy == 'Hide') {
			            blanks["author"] = "Anonymous";
			        }
			    }
			}

			if (this.model.get("media_type") == "Text" && this.model.get('description').length < this.model.get('text').length){
				blanks["description"] = this.model.get('description') + '...';
			}

			if (this.model.get("media_type") == "Website"){
				var parts = this.model.get('attribution_uri').split('http');
				blanks["original_url"] = parts[2] !== undefined ? "http" + parts[2] : this.model.get('attribution_uri');
			}

			//console.log(this.model.get("description"));
			var text = document.getElementById("search").textContent;
			var old_arr = text.split("");
			var substitute = "";
			var new_arr = [];

			for (var i = 0; i < old_arr.length; i++)
			{
				if (old_arr[i].match(/[A-Za-z]+/) != null)
				{
					substitute = substitute.concat(old_arr[i][0]);

					if (old_arr[i + 1].match(/[A-Za-z]+/) == null)
					{
						new_arr.push(substitute);
						substitute = "";
					}
				}
			}

			// Gets rid of the unnecessary "text:" string
			new_arr.splice(0,1);
			item_description = this.model.get("description");

			var pre_string;
			var searched_term;
			var end_string;

			for (var k = 0; k < new_arr.length; k++)
			{
				if (item_description.indexOf(new_arr[k]) != -1)
				{
					pre_string = item_description.substring(0,item_description.indexOf(new_arr[k]));
					searched_term = item_description.substring(item_description.indexOf(new_arr[k]), item_description.indexOf(new_arr[k]) + new_arr[k].length);
					end_string = item_description.substring(item_description.indexOf(new_arr[k]) + new_arr[k].length, item_description.length);
					item_description = pre_string + '' + '' + searched_term + '' + '' + end_string;
				}
			}

			$(this.el).html( _.template( template, blanks ) );

			$(this.el).find('.zeega-item-thumbnail').append(this.thumbnailView.render().el);

			if (blanks["author"] === ""){
				$(this.el).find('.jda-item-author').hide();
			}

			if (this.model.get("media_type") == "Collection"){
				this.draggable=false;
			}
			else {
				this.draggable=true;
			}

			if(this.draggable){
				$(this.el).draggable({
					cursor : 'crosshair',
					cursorAt : {
						top : 50,
						left : 50
					},
					appendTo : 'body',
					opacity : 0.8,

					helper : function(){
						var drag = $(this).find('.thumbnail')
						.clone()
						.css({
							'z-index':'101'
						});
						return drag;
					},

					//init the dragged item variable
					start : function(){
						$(this).draggable('option','revert',true);
						jda.app.draggedItem = _this.model;
					}
			});
			}
			$(this.el).find(".jdicon-small-drag").tooltip({'title':'Drag to add to your collection','placement':'bottom', delay: { show: 600, hide: 100 }});

			if( blanks["display_name"] === ""){
				$(this.el).find(".jda-user-link").hide();
			} else {
				$(this.el).find(".jda-user-link").click(function(){jda.app.goToUser(_this.model.get('user_id')); return false;});
			}

			return this;
		},

		/* formats tweet text, doesn't linkify bc tweet is already linked to fancybox */
		linkifyTweet : function(tweet){

			// urls
			var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
			tweet = tweet.replace(exp,"$1");

			// users
			tweet = tweet.replace(/(^|)@(\w+)/gi, function (s) {
				return '' + s + '';
			});

			// tags
			tweet = tweet.replace(/(^|)#(\w+)/gi, function (s) {
				return '' + s + '';
			});

			return tweet;
		},

		getImageTemplate : function()
		{
			console.log("I got here1");
			console.log(item_description);
			html =

			''+
				'

'+
			'	'+
			''+
				'
<%= title %>

by: <%= author %>'+
				'
' + item_description +'
'+
			'	'+
			'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
				'

via <%= display_name %>

'+
			'	';

			return html;
		},

		getDefaultTemplate : function()
		{
			console.log("I got here2");
			console.log(item_description);

			html =

			''+
				'

'+
			'	'+
			''+
				'
<%= title %>

by: <%= author %>
'+
				'
' + item_description +'
'+
			'	'+
			'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
			'

via <%= display_name %>

'+
			'	';

			return html;
		},

		getDocumentTemplate : function()
		{

			console.log("I got here3");
			console.log(item_description);
			html =

			''+
				''+
				'
<%= author %>
'+
			'	'+
			''+
				'
<%= title %>
'+
				'
' + item_description + '
'+
			'	'+
			''+
				'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
				'

via <%= display_name %>

'+
			'	';

			return html;
		},

		getWebsiteTemplate : function()
		{
			console.log("I got here4");
			console.log(item_description);
			html =

			''+
				'

'+
			'	'+
			''+
				'
<%= title %>
'+
				'
<%= original_url %>
'+
				'
' + item_description + '
'+
			'	'+
			''+
				'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
				'

via <%= display_name %>

'+
			'	';

			return html;
		},

		getTweetTemplate : function()
		{
			console.log("I got here5");
			console.log(item_description);
			html =

			''+
				'

'+
			'	'+
			''+
				'
' + item_description +'
'+
			'	'+
			'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
				'

via <%= display_name %>

'+
			'	';

			return html;
		},

		getTestimonialTemplate : function()
		{
			console.log("I got here6");
			console.log(item_description);
			html =
			''+
				'

'+
			'	'+
			''+
				'
<%= title %>

Testimonial by: <%= author %>
'+
				'
' + item_description + '
'+
			'	'+
			'<%= media_date %><input class="jda-item-checkbox" type="checkbox">'+
				'

via <%= display_name %>

'+
			'	';
			return html;
		},

		getCollectionTemplate : function()
		{
			console.log("I got here7");
			console.log(item_description);
			html =

				''+
				'

'+
				'	'+
				''+
					'
<%= title %>

by <%= display_name %>
'+
					'
' + item_description + '
'+
				'	'+
				'<%= media_date %>'+
					'<input class="jda-item-checkbox" type="checkbox">'+
				'	';

			return html;
		}

	});

})(jda.module("browser"));
<|endoftext|>


<commit_before>function EvDa(G){function H(a,b){return a.match(/[?*]/)?C(s(b?b:d),function(b){return b.match(a)}):a}function D(a,b){var f={};return g(a)?(e(a,function(c){f[a]=b(a)}),f):b(a)}function c(a,b,f){if(!a)return{data:d,setters:h,events:l,globs:y};if(g(a)){var w=p.call(arguments,1);return I(a,function(a){return c.apply(c.context,[a].concat(w))})}if(1==arguments.length){if(t(a)){var v={};e(a,function(a,b){v[a]=c(a,b,f,0,1)});e(v,function(b,f){n(v[b])&&!n(a[b])&&(a[b]=v[b]())});return a}return D(a,function(a){return d[a]})}return c[n(b)?
"on":"set"].apply(this,arguments)}function z(a){e(a.$,function(b){var f=b.match(/[?*]/)?y:l;f[b]=E(f[b],a)})}function m(a,b,f){if(g(a)){var w=a.pop();return m(H(w),function(f,c){return m(1==a.length?a[0]:a,b,c)},f)}if(t(a))return e(a,function(b,c){b.match(/[?*]/)?q(b,D(b,function(a){return m(b,c,f)})):a[b]=m(b,c,f)}),a;h[a]&&(h[a](function(b){c.set.call(c.context,a,b,f)}),delete h[a]);return b?a in d?b.call(c.context,d[a],f):c(a,b,q(f||{},F)):a in d}var p=Array.prototype.slice,r=Object.prototype.toString,
g=[].isArray||function(a){return"[object Array]"===r.call(a)},n=function(a){return!!(a&&a.constructor&&a.call&&a.apply)},A=function(a){return!!(""===a||a&&a.charCodeAt&&a.substr)},t=function(a){return n(a)||A(a)||"[object Number]"===r.call(a)||g(a)?!1:null==a?"object"==String(a):"[object Object]"===r.call(a)||!0},e=[].forEach?function(a,b){if(g(a)||a.length)p.call(a).forEach(b);else for(var c in a)b(c,a[c])}:function(a,b){if(g(a))for(var c=0,w=a.length;c<w;c++)b(a[c],c);else for(c in a)b(c,a[c])},
s={}.keys||function(a){if(g(a))return a;var b=[],c;for(c in a)b.push(c);return b},E=function(a,b){var c=[];e(a,function(a){a!==b&&c.push(a)});return c},J=function(a){var b,c=[];e(s(a).sort(),function(a){a!=b&&(b=a,c.push(a))});return c},C=function(a,b){var c=[];e(a,function(a){b(a)&&c.push(a)});return c},x=function(a){return a&&"length"in a?a.length:0},I=[].map?function(a,b){return a.map(b)}:function(a,b){for(var c=[],d=0,e=a.length;d<e;d++)c.push(b(a[d],d));return c},K=function(a){return g(a)?p.call(a):
t(a)?q(a,{}):a},q=function(a){e(p.call(arguments,1),function(b){for(var c in b)void 0!==b[c]&&(t(b[c])&&t(a[c])?q(a[c],b[c]):a[c]=b[c])});return a},F={once:1},d=G||{},B=[],h={},y={},l={};e(["first","on","after","test","or"],function(a){c[a]=function(b,c,d){var e=l;c||(c=b,b="__base");(c.$||(c.$=[])).push(a+b);b.match(/[?*]/)&&(e=y);(e[a+b]||(e[a+b]=[])).push(c);return q(c,d)}});q(c,{_:{},context:this,list:{},isPaused:!1,db:d,setterMap:h,events:l,del:z,whenSet:m,isset:m,pause:function(){return c.isPaused?
!1:(c.isPaused=!0,c._.set=c.set,c.set=function(){B.push(["set",arguments])},!0)},play:function(){if(c.isPaused){c.isPaused=!1;var a=EvDa();c.set=c._.set;e(B,function(b){a[b[0]].apply(a,b[1])});B=[];c(a.db);return!0}return!1},setter:function(a,b){h[a]=b;if(l["on"+a])return m(a)},when:function(a,b,f){if(A(b))try{var d=new Function("x","return x"+b);d();b=d}catch(e){}return c(a,function(a){(g(b)&&b.sort().join("")===a.sort().join("")||n(b)&&b(a)||a===b)&&f.call(c.context,a)})},incr:function(a,b){b=b||
1;return c.set(a,"[object Number]"===r.call(d[a])?d[a]+b:b)},decr:function(a,b){return c.set(a,d[a]-(b||1)||0)},push:function(a,b){1==x(arguments)&&(b=a,a="__base");return c.set(a,[].concat(d[a]||[],[b]))},pop:function(a){return c.set(a||"__base",d[a].slice(0,-1))},traceList:[],group:function(a){var b=p.call(arguments);a=b.shift();b=c.apply(0,b);c.list[a]||(c.list[a]=[]);n(b)?c.list[a].push(b):e(b,function(b,d){c.list[a].push(b)});return function(){return c.group.apply(0,[a].concat(p.call(arguments)))}},
extend:function(a,b){return c.set.apply(c.context,[a,q({},d[a]||{},b)].concat(p.call(arguments,2)))},set:function(a,b,f,g,v){var k="test"+a,m=a.split("."),h,n,t=p.call(arguments),s=x(l[k]);h=s&&!g;var r,u=h?function(d){r|=!1===d;--s||(r?e(l["or"+a]||[],function(a){a.S||(a.call(c.context,b,f),a.once&&z(a))}):c.set(a,b,f,1))}:{};u.old=K(d[a]);q(u,{meta:f||{},done:u,result:u,key:a});h?(e(l[k],function(a){a.call(c.context,b,u)}),k=d[a]):(e(c.traceList,function(a){a.call(c.context,t)}),d[a]=b,k=function(){e((l["first"+
a]||[]).concat(l["on"+a]||[],l["after"+a]||[]),function(a){a.S||(a.call(c.context,b,u),a.once&&z(a));u.last=void 0});return b},k=v?k:k.call(c.context));1<m.length&&(h=m.pop(),n=[],n[h]=b,c.extend(m.join("."),n));return k},fire:function(a){c.set(a,d[a])},once:function(a,b,d){return b?c.once(c(a,b,d)):q(a,F)},enable:function(a){e(c.list[a],function(b){b.S&&b.S[a]&&delete b.S[a];0==x(b.S)&&delete b.S});return c.list[a]},setadd:function(a,b){b=g(b)?b:[b];return c(a,J((d[a]||[]).concat(b)))},setdel:function(a,
b){return c(a,E(d[a]||[],b))},disable:function(a){e(c.list[a],function(b){(b.S||(b.S={}))[a]=!0});return c.list[a]},unset:function(){var a=!0;e(arguments,function(b){a&=b in d;delete d[b]});return a},find:function(a){return C(s(d),function(b){return b.match(a)})},changed:function(a,b){b||(b=a,a="__base");return c.on(a,function(a,d){var e=x(a),k=x(d.old);1==e-k?b.call(c.context,a.length?a[a.length-1]:void 0):e>k&&b.call(c.context,p.call(a).slice(k))})},sniff:function(){var a={},b=+new Date,d=function(c){a[c[0]]||
console.log(+new Date-b,c)},e=function(){},g=d;c.traceList.unshift(function(a){g(a)});c.sniff=function(b){if(0<arguments.length){if(A(b))return a[b]=!a[b],"[Un]ignoring "+b;g=b?d:e;return b}return s(a)}}});c.setAdd=c.setadd;c.setDel=c.setdel;c.isSet=c.isset;c.get=c;c.change=c.on;c.add=c.push;c.isArray=g;return c};
<commit_msg>Minified version<commit_after>function EvDa(G){function H(a,b){return a.match(/[?*]/)?C(q(b?b:e),function(b){return b.match(a)}):a}function D(a,b){var d={};return g(a)?(f(a,function(c){d[a]=b(a)}),d):b(a)}function c(a,b,d){if(!a)return{data:e,setters:m,events:l,globs:y};if(g(a)){var v=n.call(arguments,1);return I(a,function(a){return c.apply(c.context,[a].concat(v))})}if(1==arguments.length){if(r(a)){var u={};f(a,function(a,b){u[a]=c(a,b,d,0,1)});f(u,function(b,d){s(u[b])&&!s(a[b])&&(a[b]=u[b]())});return a}return D(a,function(a){return e[a]})}return c[s(b)?
"on":"set"].apply(this,arguments)}function z(a){f(a.$,function(b){var d=b.match(/[?*]/)?y:l;d[b]=E(d[b],a)})}function h(a,b,d){if(g(a)){var v=a.pop();return h(H(v),function(d,c){return h(1==a.length?a[0]:a,b,c)},d)}if(r(a))return f(a,function(b,c){b.match(/[?*]/)?p(b,D(b,function(a){return h(b,c,d)})):a[b]=h(b,c,d)}),a;m[a]&&(m[a](function(b){c.set.call(c.context,a,b,d)}),delete m[a]);return b?a in e?b.call(c.context,e[a],d):c(a,b,p(d||{},F)):a in e}var n=Array.prototype.slice,x=Object.prototype.toString,
g=[].isArray||function(a){return"[object Array]"===x.call(a)},s=function(a){return!!(a&&a.constructor&&a.call&&a.apply)},A=function(a){return!!(""===a||a&&a.charCodeAt&&a.substr)},r=function(a){return s(a)||A(a)||"[object Number]"===x.call(a)||g(a)?!1:null==a?"object"==String(a):"[object Object]"===x.call(a)||!0},f=[].forEach?function(a,b){if(g(a)||a.length)n.call(a).forEach(b);else for(var d in a)b(d,a[d])}:function(a,b){if(g(a))for(var d=0,c=a.length;d<c;d++)b(a[d],d);else for(d in a)b(d,a[d])},
q={}.keys||function(a){if(g(a))return a;var b=[],d;for(d in a)b.push(d);return b},E=function(a,b){var d=[];f(a,function(a){a!==b&&d.push(a)});return d},J=function(a){var b,d=[];f(q(a).sort(),function(a){a!=b&&(b=a,d.push(a))});return d},C=function(a,b){var d=[];f(a,function(a){b(a)&&d.push(a)});return d},w=function(a){return a&&"length"in a?a.length:0},I=[].map?function(a,b){return a.map(b)}:function(a,b){for(var d=[],c=0,e=a.length;c<e;c++)d.push(b(a[c],c));return d},K=function(a){return g(a)?n.call(a):
r(a)?p(a,{}):a},p=function(a){f(n.call(arguments,1),function(b){for(var c in b)void 0!==b[c]&&(r(b[c])&&r(a[c])?p(a[c],b[c]):a[c]=b[c])});return a},F={once:1},e=G||{},B=[],m={},y={},l={};f(["first","on","after","test","or"],function(a){c[a]=function(b,c,e){var f=l;c||(c=b,b="__base");(c.$||(c.$=[])).push(a+b);b.match(/[?*]/)&&(f=y);(f[a+b]||(f[a+b]=[])).push(c);return p(c,e)}});p(c,{_:{},context:this,list:{},isPaused:!1,db:e,setterMap:m,events:l,del:z,whenSet:h,isset:h,pause:function(){return c.isPaused?
!1:(c.isPaused=!0,c._.set=c.set,c.set=function(){B.push(["set",arguments])},!0)},play:function(){if(c.isPaused){c.isPaused=!1;var a=EvDa();c.set=c._.set;f(B,function(b){a[b[0]].apply(a,b[1])});B=[];c(a.db);return!0}return!1},setter:function(a,b){m[a]=b;if(l["on"+a])return h(a)},when:function(a,b,d){if(A(b))try{var e=new Function("x","return x"+b);e();b=e}catch(f){}return c(a,function(a){(g(b)&&b.sort().join("")===a.sort().join("")||s(b)&&b(a)||a===b)&&d.call(c.context,a)})},incr:function(a,b){b=b||
1;return c.set(a,"[object Number]"===x.call(e[a])?e[a]+b:b)},decr:function(a,b){return c.set(a,e[a]-(b||1)||0)},push:function(a,b){1==w(arguments)&&(b=a,a="__base");return c.set(a,[].concat(e[a]||[],[b]))},pop:function(a){return c.set(a||"__base",e[a].slice(0,-1))},traceList:[],group:function(a){var b=n.call(arguments);a=b.shift();b=c.apply(0,b);c.list[a]||(c.list[a]=[]);s(b)?c.list[a].push(b):f(b,function(b,e){c.list[a].push(b)});return function(){return c.group.apply(0,[a].concat(n.call(arguments)))}},
extend:function(a,b){return c.set.apply(c.context,[a,p({},e[a]||{},b)].concat(n.call(arguments,2)))},set:function(a,b,d,v,u){var k="test"+a,g=a.split("."),h,m,s=n.call(arguments),r=w(l[k]);h=r&&!v;var q,t=h?function(e){q|=!1===e;--r||(q?f(l["or"+a]||[],function(a){a.S||(a.call(c.context,b,d),a.once&&z(a))}):c.set(a,b,d,1))}:{};t.old=K(e[a]);p(t,{meta:d||{},done:t,result:t,key:a});h?(f(l[k],function(a){a.call(c.context,b,t)}),k=e[a]):(f(c.traceList,function(a){a.call(c.context,s)}),e[a]=b,k=function(){f((l["first"+
a]||[]).concat(l["on"+a]||[],l["after"+a]||[]),function(a){a.S||(a.call(c.context,b,t),a.once&&z(a));t.last=void 0});return b},k=u?k:k.call(c.context));1<g.length&&(h=g.pop(),m=[],m[h]=b,c.extend(g.join("."),m));return k},fire:function(a){c.set(a,e[a])},once:function(a,b,d){return b?c.once(c(a,b,d)):p(a,F)},enable:function(a){f(c.list[a],function(b){b.S&&b.S[a]&&delete b.S[a];0==w(b.S)&&delete b.S});return c.list[a]},setadd:function(a,b){b=g(b)?b:[b];var d=e[a]||[],f=J(d.concat(b));return d.length!=
f.length?c(a,f):f},setdel:function(a,b){var d=e[a]||[],f=E(d,b);return d.length!=f.length?c(a,f):f},disable:function(a){f(c.list[a],function(b){(b.S||(b.S={}))[a]=!0});return c.list[a]},unset:function(){var a=!0;f(arguments,function(b){a&=b in e;delete e[b]});return a},find:function(a){return C(q(e),function(b){return b.match(a)})},changed:function(a,b){b||(b=a,a="__base");return c.on(a,function(a,e){var f=w(a),k=w(e.old);1==f-k?b.call(c.context,a.length?a[a.length-1]:void 0):f>k&&b.call(c.context,
n.call(a).slice(k))})},sniff:function(){var a={},b=+new Date,d=function(c){a[c[0]]||console.log(+new Date-b,c)},f=function(){},e=d;c.traceList.unshift(function(a){e(a)});c.sniff=function(b){if(0<arguments.length){if(A(b))return a[b]=!a[b],"[Un]ignoring "+b;e=b?d:f;return b}return q(a)}}});c.setAdd=c.setadd;c.setDel=c.setdel;c.isSet=c.isset;c.get=c;c.change=c.on;c.add=c.push;c.isArray=g;return c};
<|endoftext|>


<commit_before>import React from 'react';
import { hashHistory } from 'react-router';

import RegisterForm from './RegisterForm.js';
import LoginForm from './LoginForm.js';
import MainPageStore from './../Stores/mainPageStore.js';
import User from './../Models/User.js';

export default class MainPage extends React.Component {
    constructor () {
        super();

        this.state = {
            loggingIn: true
        };
    }

    componentWillMount () {
        if (sessionStorage.getItem ('token')) {
            User.setToken(sessionStorage.getItem('token')).toggleLoggedIn();
            hashHistory.push('/voting');
        }

        MainPageStore.on('change', this.getLoggingInState.bind(this));
    }

    componentWillUnmount () {
        MainPageStore.removeListener('change', this.getLoggingInState.bind(this));
    }

    getLoggingInState () {
        this.setState({
            loggingIn: MainPageStore.getLoggingInState()
        });
    }

    render () {
        return (

Electronic Voting System

Write something here

                                    About

 {
                                    (this.state.loggingIn)
                                    ? <LoginForm/>
                                    : <RegisterForm/>
                                }

        );
    }
}
<commit_msg>solving conflict commit<commit_after>import React from 'react';
import { hashHistory } from 'react-router';

import RegisterForm from './RegisterForm.js';
import LoginForm from './LoginForm.js';
import MainPageStore from './../Stores/mainPageStore.js';
import User from './../Models/User.js';

export default class MainPage extends React.Component {
    constructor () {
        super();

        this.state = {
            loggingIn: true
        };
    }

    componentWillMount () {
        if (sessionStorage.getItem ('token')) {
            User.setToken(sessionStorage.getItem('token')).toggleLoggedIn();
            hashHistory.push('/voting');
        }

        MainPageStore.on('change', this.getLoggingInState.bind(this));
    }

    componentWillUnmount () {
        MainPageStore.removeListener('change', this.getLoggingInState.bind(this));
    }

    getLoggingInState () {
        this.setState({
            loggingIn: MainPageStore.getLoggingInState()
        });
    }

    render () {
        return (

Electronic Voting System

asdsdsadksadaskdasldkjasldkjaskdjasdjasdjasd asdasd as dsandasdsdsadksadaskdasldkjasldkjaskdjasdjasdjasd asdasd as dsandWrite something hereWrite something here

                                    About

 {
                                    (this.state.loggingIn)
                                    ? <LoginForm/>
                                    : <RegisterForm/>
                                }

        );
    }
}
<|endoftext|>