<commit_before>/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */
YUI.add('mojito-resource-store-adapter-tests', function(Y, NAME) {

    var suite = new YUITest.TestSuite(NAME),
        path = require('path'),
        fixtures = path.join(__dirname, '../../../fixtures/store'),
        dummyLog = {log: function() {}},
        A = YUITest.Assert;

    suite.add(new YUITest.TestCase({

        name: 'Resource Store Adapter Tests',

        'pre load': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            A.isTrue(store.getAppPath() === fixtures);
        },

        'server app config value': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var config = store.getAppConfig(null, 'application');
            A.isTrue(config.testKey1 === 'testVal1');
        },

        'server mojit config value': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {base:'test1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.id === 'test1');
                A.isTrue(instance.type === 'test_mojit_1');
                A.isTrue(instance.config.testKey4 === 'testVal4');
            });
        },

        'server mojit config value via type': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'test_mojit_1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.type === 'test_mojit_1');
                A.isTrue(instance.config.testKey4 === 'testVal4');
                A.isTrue(instance.config.testKey6.testKey7 === 'testVal7');
            });
        },

        'server mojit config value via type & overrride': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {
                type:'test_mojit_1',
                config:{testKey4: 'other'}
            };
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.type === 'test_mojit_1');
                A.isTrue(instance.config.testKey4 === 'other');
                A.isTrue(instance.config.testKey5 === 'testVal5');
            });
        },

        'server mojit config assets': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'test_mojit_1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.assets['css/main.css'] !== undefined);
                A.isTrue(instance.assets['js/main.js'] !== undefined);
            });
        },

        'server mojit config views': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'test_mojit_1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.views['test_1'] !== undefined);
                A.isTrue(instance.views['test_2'] !== undefined);
            });
        },

        'server mojit config models': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'test_mojit_1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.models['test_1'] !== undefined);
                A.isTrue(instance.models['test_2'] !== undefined);
            });
        },

        'server mojit config actions': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'test_mojit_1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.actions.length === 2);
            });
        },

        'server mojit config appConfig': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var command = {
                type:'test_mojit_1',
                appConfig:{
                    testKey3: 'other'
                }
            };
            store.expandInstance(command, {}, function(err, instance){
                A.isTrue(instance.appConfig.testKey2 === 'testVal2');
                A.isTrue(instance.appConfig.testKey3 === 'other');
            });
        },

        'TODO: server mojit config definition override': function() {
            A.skip(); return;

            var store = new Y.mojito.ResourceStore({ root: fixtures });
            store.preload();

            var command = {type:'test_mojit_1'};
            store.expandInstance(command, {}, function(err, instance){
                A.isTrue(instance.models['other_1'] === '/path/to/other_1');
            });
        },

        'server mojit instance definition override': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var command = {
                type:'test_mojit_1',
                models: {
                    'other_2': '/path/to/other_2'
                }
            };
            store.expandInstance(command, {}, function(err, instance){
                A.isTrue(instance.models['other_2'] === '/path/to/other_2');
            });
        },

        'server mojit type name can come from package.json': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit2'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isNotUndefined(instance.controller);
                A.areSame('/static/TestMojit2/assets', instance.assetsRoot);
                A.isNotUndefined(instance.yui.config.modules.test_mojit_2);
            });
        },

        'server mojit is NOT loaded becuase of pacakge mojito version miss-match': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            A.isTrue(typeof store._staticURLs['/static/test_mojit_4/package.json'] === 'undefined');
            A.isTrue(typeof store._staticURLs['/static/TestMojit4/package.json'] === 'undefined');
        },

        'server mojit is loaded becuase of pacakge mojito version match': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit2'};
            store.expandInstance(instance, {}, function(err, instance){
                A.areSame('/static/TestMojit2/assets', instance.assetsRoot);
            });
        },

        'server a mojits package.json file is NOT publicly accessible': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            A.isTrue(typeof store._staticURLs['/static/TestMojit2/package.json'] === 'undefined');
        },

        'server a mojits package.json file is publicly accessible': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            A.isTrue(typeof store._staticURLs['/static/TestMojit3/package.json'] === 'string');
        },

        'server a mojit is NOT loaded because it has a package.json file with no mojito config': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            A.isTrue(typeof store._staticURLs['/static/TestMojit5/package.json'] === 'undefined');
        },

        'server mojit view index.mu.html is loaded correctly': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit3'};
            store.expandInstance(instance, {}, function(err, instance){
                A.areSame('index.mu.html', instance.views.index['content-path'].split('/').pop());
            });
        },

        'server mojit view index.iphone.mu.html is loaded correctly': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit3'};
            store.expandInstance(instance, {device:'iphone'}, function(err, instance){
                A.areSame('index.iphone.mu.html', instance.views.index['content-path'].split('/').pop());
            });
        },

        'server mojit view index1.mu.html is loaded correctly': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit3', action: 'index1'};
            store.expandInstance(instance, {device:'forotheriphone'}, function(err, instance){
                A.areSame('index1.forotheriphone.mu.html', instance.views.index1['content-path'].split('/').pop());
            });
        },

        'server mojit view index1.iphone.mu.html is loaded correctly': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit3', action: 'index1'};
            store.expandInstance(instance, {device:'otheriphone'}, function(err, instance){
                A.areSame('index1.otheriphone.mu.html', instance.views.index1['content-path'].split('/').pop());
            });
        },

        'test getSpec() from specs dir': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            store.getSpec('server', 'TestMojit2', {}, function(err, instance){
                A.isTrue(instance.type === 'TestMojit2');
                A.isTrue(instance.config.testKey1 === 'testVal1');
            });
        },

        'test getType()': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            store.getType('server', 'test_mojit_1', {}, function(err, instance){
                A.isTrue(instance.type === 'test_mojit_1');
                A.isTrue(instance.config.testKey4 === 'testVal4');
                A.isTrue(instance.config.testKey6.testKey7 === 'testVal7');
            });
        }

    }));

    YUITest.TestRunner.add(suite);

}, '0.0.1', {requires: [
    'mojito-resource-store',
    'mojito-resource-store-adapter'
]});
<commit_msg>fixed up call to store.getAppConfig()<commit_after>/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */
YUI.add('mojito-resource-store-adapter-tests', function(Y, NAME) {

    var suite = new YUITest.TestSuite(NAME),
        path = require('path'),
        fixtures = path.join(__dirname, '../../../fixtures/store'),
        dummyLog = {log: function() {}},
        A = YUITest.Assert;

    suite.add(new YUITest.TestCase({

        name: 'Resource Store Adapter Tests',

        'pre load': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            A.isTrue(store.getAppPath() === fixtures);
        },

        'server app config value': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var config = store.getAppConfig(null);
            A.isTrue(config.testKey1 === 'testVal1');
        },

        'server mojit config value': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {base:'test1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.id === 'test1');
                A.isTrue(instance.type === 'test_mojit_1');
                A.isTrue(instance.config.testKey4 === 'testVal4');
            });
        },

        'server mojit config value via type': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'test_mojit_1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.type === 'test_mojit_1');
                A.isTrue(instance.config.testKey4 === 'testVal4');
                A.isTrue(instance.config.testKey6.testKey7 === 'testVal7');
            });
        },

        'server mojit config value via type & overrride': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {
                type:'test_mojit_1',
                config:{testKey4: 'other'}
            };
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.type === 'test_mojit_1');
                A.isTrue(instance.config.testKey4 === 'other');
                A.isTrue(instance.config.testKey5 === 'testVal5');
            });
        },

        'server mojit config assets': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'test_mojit_1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.assets['css/main.css'] !== undefined);
                A.isTrue(instance.assets['js/main.js'] !== undefined);
            });
        },

        'server mojit config views': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'test_mojit_1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.views['test_1'] !== undefined);
                A.isTrue(instance.views['test_2'] !== undefined);
            });
        },

        'server mojit config models': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'test_mojit_1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.models['test_1'] !== undefined);
                A.isTrue(instance.models['test_2'] !== undefined);
            });
        },

        'server mojit config actions': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'test_mojit_1'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isTrue(instance.actions.length === 2);
            });
        },

        'server mojit config appConfig': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var command = {
                type:'test_mojit_1',
                appConfig:{
                    testKey3: 'other'
                }
            };
            store.expandInstance(command, {}, function(err, instance){
                A.isTrue(instance.appConfig.testKey2 === 'testVal2');
                A.isTrue(instance.appConfig.testKey3 === 'other');
            });
        },

        'TODO: server mojit config definition override': function() {
            A.skip(); return;

            var store = new Y.mojito.ResourceStore({ root: fixtures });
            store.preload();

            var command = {type:'test_mojit_1'};
            store.expandInstance(command, {}, function(err, instance){
                A.isTrue(instance.models['other_1'] === '/path/to/other_1');
            });
        },

        'server mojit instance definition override': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var command = {
                type:'test_mojit_1',
                models: {
                    'other_2': '/path/to/other_2'
                }
            };
            store.expandInstance(command, {}, function(err, instance){
                A.isTrue(instance.models['other_2'] === '/path/to/other_2');
            });
        },

        'server mojit type name can come from package.json': function() {
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit2'};
            store.expandInstance(instance, {}, function(err, instance){
                A.isNotUndefined(instance.controller);
                A.areSame('/static/TestMojit2/assets', instance.assetsRoot);
                A.isNotUndefined(instance.yui.config.modules.test_mojit_2);
            });
        },

        'server mojit is NOT loaded becuase of pacakge mojito version miss-match': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            A.isTrue(typeof store._staticURLs['/static/test_mojit_4/package.json'] === 'undefined');
            A.isTrue(typeof store._staticURLs['/static/TestMojit4/package.json'] === 'undefined');
        },

        'server mojit is loaded becuase of pacakge mojito version match': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit2'};
            store.expandInstance(instance, {}, function(err, instance){
                A.areSame('/static/TestMojit2/assets', instance.assetsRoot);
            });
        },

        'server a mojits package.json file is NOT publicly accessible': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            A.isTrue(typeof store._staticURLs['/static/TestMojit2/package.json'] === 'undefined');
        },

        'server a mojits package.json file is publicly accessible': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            A.isTrue(typeof store._staticURLs['/static/TestMojit3/package.json'] === 'string');
        },

        'server a mojit is NOT loaded because it has a package.json file with no mojito config': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            A.isTrue(typeof store._staticURLs['/static/TestMojit5/package.json'] === 'undefined');
        },

        'server mojit view index.mu.html is loaded correctly': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit3'};
            store.expandInstance(instance, {}, function(err, instance){
                A.areSame('index.mu.html', instance.views.index['content-path'].split('/').pop());
            });
        },

        'server mojit view index.iphone.mu.html is loaded correctly': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit3'};
            store.expandInstance(instance, {device:'iphone'}, function(err, instance){
                A.areSame('index.iphone.mu.html', instance.views.index['content-path'].split('/').pop());
            });
        },

        'server mojit view index1.mu.html is loaded correctly': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit3', action: 'index1'};
            store.expandInstance(instance, {device:'forotheriphone'}, function(err, instance){
                A.areSame('index1.forotheriphone.mu.html', instance.views.index1['content-path'].split('/').pop());
            });
        },

        'server mojit view index1.iphone.mu.html is loaded correctly': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            var instance = {type:'TestMojit3', action: 'index1'};
            store.expandInstance(instance, {device:'otheriphone'}, function(err, instance){
                A.areSame('index1.otheriphone.mu.html', instance.views.index1['content-path'].split('/').pop());
            });
        },

        'test getSpec() from specs dir': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            store.getSpec('server', 'TestMojit2', {}, function(err, instance){
                A.isTrue(instance.type === 'TestMojit2');
                A.isTrue(instance.config.testKey1 === 'testVal1');
            });
        },

        'test getType()': function(){
            var resourceStore,
                store;

            resourceStore = new Y.mojito.ResourceStore({ root: fixtures });
            resourceStore.preload();

            store = Y.mojito.ResourceStoreAdapter.init('server', resourceStore, dummyLog);
            store.getType('server', 'test_mojit_1', {}, function(err, instance){
                A.isTrue(instance.type === 'test_mojit_1');
                A.isTrue(instance.config.testKey4 === 'testVal4');
                A.isTrue(instance.config.testKey6.testKey7 === 'testVal7');
            });
        }

    }));

    YUITest.TestRunner.add(suite);

}, '0.0.1', {requires: [
    'mojito-resource-store',
    'mojito-resource-store-adapter'
]});
<|endoftext|>


<commit_before>$(function(){
  $(document).delegate('.add_child','click', function() {
    var association = $(this).attr('data-association');
    var template = $(this).attr('data-association-template');
    var child_templates = $(this).attr('data-child-template').split(' ');
    var target = $(this).attr('target');
    var regexp = new RegExp('new_' + association, 'g');
    var regexp2 = new RegExp('\\[tempid\\]', 'g');
    var regexp_child_template = new RegExp('_tempid_', 'g');
    var regexp_parent_new_field = new RegExp('new_' + association, 'g');
    var new_id = new Date().getTime();
    var Dest = (target == '') ? $(this).parent() : $('#'+target);
    Dest.append(window[ template ].replace(regexp, new_id).replace(regexp2, new_id));
    for(var index in child_templates)
    {
      child_template = child_templates[index];
      if(child_template != "")
      {
        body = window[child_template];
        child_script_tag = "<script> var " + child_template + " = '" + body + "'  </script>";
        child_script_tag = child_script_tag.replace(regexp_child_template, "_" + new_id + "_")
                            .replace(regexp_parent_new_field, new_id);
        Dest.append(child_script_tag.replace(regexp_child_template, "_" + new_id + "_"));
      }
    }
    $(document).trigger('coolNestedForms.childAdded');
    return false;
  });

  $(document).delegate('.remove_child','click', function() {
    $(this).parent().children('.removable')[0].value = 1;
    $(this).parent().hide();
    $(document).trigger('coolNestedForms.childRemoved');
    return false;
  });
});
<commit_msg>Added new event listener for cnf-add-entry. using JS style for var names. standardizing var names to match new attribute names.<commit_after>$(function(){
  $(document).delegate('.cnf-add-entry','click', function() {
    // initialize options
    var association = $(this).attr('data-association');
    var jsTemplateName = $(this).attr('data-js-template-name');
    var childTemplates = $(this).attr('data-child-js-template-names').split(' ');
    var target = $(this).attr('data-target');

    // initialize regular expressions
    var associationNewRegEx = new RegExp('new_' + association, 'g');
    var tempIdRegEx = new RegExp('\\[tempid\\]', 'g');
    var childTempIdRegEx = new RegExp('_tempid_', 'g');
    // var regexp_parent_new_field = new RegExp('new_' + association, 'g');

    var newId = new Date().getTime();

    var Dest = (target == '') ? $(this).parent() : $('#'+target);

    Dest.append(window[ jsTemplateName ].replace(associationNewRegEx, newId).replace(tempIdRegEx, newId));
    for(var index in childTemplates)
    {
      childTemplate = childTemplates[index];
      if(childTemplate != "")
      {
        body = window[childTemplate];
        child_script_tag = "<script> var " + childTemplate + " = '" + body + "'  </script>";
        child_script_tag = child_script_tag.replace(childTempIdRegEx, "_" + newId + "_")
                            .replace(associationNewRegEx, newId);
        Dest.append(child_script_tag.replace(childTempIdRegEx, "_" + newId + "_"));
      }
    }
    $(document).trigger('coolNestedForms.entryAdded');
    return false;
  });

});

$(function(){
  $(document).delegate('.add_child','click', function() {
    var association = $(this).attr('data-association');
    var template = $(this).attr('data-association-template');
    var child_templates = $(this).attr('data-child-template').split(' ');
    var target = $(this).attr('target');
    var regexp = new RegExp('new_' + association, 'g');
    var regexp2 = new RegExp('\\[tempid\\]', 'g');
    var regexp_child_template = new RegExp('_tempid_', 'g');
    var regexp_parent_new_field = new RegExp('new_' + association, 'g');
    var new_id = new Date().getTime();
    var Dest = (target == '') ? $(this).parent() : $('#'+target);
    Dest.append(window[ template ].replace(regexp, new_id).replace(regexp2, new_id));
    for(var index in child_templates)
    {
      child_template = child_templates[index];
      if(child_template != "")
      {
        body = window[child_template];
        child_script_tag = "<script> var " + child_template + " = '" + body + "'  </script>";
        child_script_tag = child_script_tag.replace(regexp_child_template, "_" + new_id + "_")
                            .replace(regexp_parent_new_field, new_id);
        Dest.append(child_script_tag.replace(regexp_child_template, "_" + new_id + "_"));
      }
    }
    $(document).trigger('coolNestedForms.childAdded');
    return false;
  });

  $(document).delegate('.remove_child','click', function() {
    $(this).parent().children('.removable')[0].value = 1;
    $(this).parent().hide();
    $(document).trigger('coolNestedForms.childRemoved');
    return false;
  });
});
<|endoftext|>


<commit_before>// @flow
import React, { Component, Fragment } from 'react';
import { observer, inject } from 'mobx-react';
import StepWalletTypeContainer from './wallet-restore/StepWalletTypeContainer';
import StepMnemonicsContainer from './wallet-restore/StepMnemonicsContainer';
import StepConfigurationContainer from './wallet-restore/StepConfigurationContainer';
import StepSuccessContainer from './wallet-restore/StepSuccessContainer';
import type { InjectedProps } from '../../../types/injectedPropsType';
import { RESTORE_WALLET_STEPS } from '../../../config/walletRestoreConfig';

type Props = InjectedProps;

// TODO restore component;
const RestoreWalletAbortConfirmation = () =>
Are you sure
;

@inject('stores', 'actions')
@observer
export default class WalletRestoreContainer extends Component<Props> {
  static defaultProps = { actions: null, stores: null };

  get containers() {
    return {
      type: StepWalletTypeContainer,
      mnemonics: StepMnemonicsContainer,
      configuration: StepConfigurationContainer,
      success: StepSuccessContainer,
    };
  }

  get shouldDisplayAbortAlert() {
    return (
      this.currentStep < 0 && this.currentStep > RESTORE_WALLET_STEPS.length
    );
  }

  get currentStep() {
    return this.props.stores.wallets.restoreWalletStep;
  }

  onContinue = () => {
    const {
      restoreWalletChangeStep,
    } = this.props.actions.wallets;
    if (this.currentStep < RESTORE_WALLET_STEPS.length - 1) {
      restoreWalletChangeStep.trigger();
    }
  };

  onBack = () => {
    this.props.actions.wallets.restoreWalletChangeStep.trigger(true);
  };

  onClose = () => {
    const {
      restoreWalletAbort,
      restoreWalletClose,
      restoreWalletEnd,
    } = this.props.actions.wallets;
    if (this.props.stores.wallets.restoredWalletId) {
      restoreWalletEnd.trigger(this.props.stores.wallets.restoredWalletId);
    } else if (this.shouldDisplayAbortAlert) {
      restoreWalletAbort.trigger();
    } else {
      restoreWalletClose.trigger();
    }
  };

  onAbort = () => this.props.actions.wallets.restoreWalletAbort.trigger();

  render() {
    const {
      restoreWalletStep,
      restoreWalletShowAbortConfirmation,
    } = this.props.stores.wallets;
    const stepId = RESTORE_WALLET_STEPS[restoreWalletStep];
    const CurrentContainer = this.containers[stepId];
    return (
      <Fragment>
        {restoreWalletShowAbortConfirmation && (
          <RestoreWalletAbortConfirmation onAbort={this.onAbort} />
        )}
        <CurrentContainer
          onContinue={this.onContinue}
          onBack={this.onBack}
          onClose={this.onClose}
        />
      </Fragment>
    );
  }
}
<commit_msg>[DDW-1156] - Implement hardware wallets restoration - fixes<commit_after>// @flow
import React, { Component, Fragment } from 'react';
import { observer, inject } from 'mobx-react';
import StepWalletTypeContainer from './wallet-restore/StepWalletTypeContainer';
import StepMnemonicsContainer from './wallet-restore/StepMnemonicsContainer';
import StepConfigurationContainer from './wallet-restore/StepConfigurationContainer';
import StepSuccessContainer from './wallet-restore/StepSuccessContainer';
import type { InjectedProps } from '../../../types/injectedPropsType';
import { RESTORE_WALLET_STEPS } from '../../../config/walletRestoreConfig';

type Props = InjectedProps;

// TODO restore component;
const RestoreWalletAbortConfirmation = () =>
Are you sure
;

@inject('stores', 'actions')
@observer
export default class WalletRestoreContainer extends Component<Props> {
  static defaultProps = { actions: null, stores: null };

  get containers() {
    return {
      type: StepWalletTypeContainer,
      mnemonics: StepMnemonicsContainer,
      configuration: StepConfigurationContainer,
      success: StepSuccessContainer,
    };
  }

  get shouldDisplayAbortAlert() {
    return (
      this.currentStep < 0 && this.currentStep > RESTORE_WALLET_STEPS.length
    );
  }

  get currentStep() {
    return this.props.stores.wallets.restoreWalletStep;
  }

  onContinue = () => {
    const { restoreWalletChangeStep } = this.props.actions.wallets;
    if (this.currentStep < RESTORE_WALLET_STEPS.length - 1) {
      restoreWalletChangeStep.trigger();
    }
  };

  onBack = () => {
    this.props.actions.wallets.restoreWalletChangeStep.trigger(true);
  };

  onClose = () => {
    const {
      restoreWalletAbort,
      restoreWalletClose,
      restoreWalletEnd,
    } = this.props.actions.wallets;
    if (this.props.stores.wallets.restoredWalletId) {
      restoreWalletEnd.trigger(this.props.stores.wallets.restoredWalletId);
    } else if (this.shouldDisplayAbortAlert) {
      restoreWalletAbort.trigger();
    } else {
      restoreWalletClose.trigger();
    }
  };

  onAbort = () => this.props.actions.wallets.restoreWalletAbort.trigger();

  render() {
    const {
      restoreWalletStep,
      restoreWalletShowAbortConfirmation,
    } = this.props.stores.wallets;
    const stepId = RESTORE_WALLET_STEPS[restoreWalletStep];
    const CurrentContainer = this.containers[stepId];
    return (
      <Fragment>
        {restoreWalletShowAbortConfirmation && (
          <RestoreWalletAbortConfirmation onAbort={this.onAbort} />
        )}
        <CurrentContainer
          onContinue={this.onContinue}
          onBack={this.onBack}
          onClose={this.onClose}
        />
      </Fragment>
    );
  }
}
<|endoftext|>


<commit_before>(function($) {
	"use strict";

	function property(properties, name, value) {
		if (value === undefined) {
			return properties[name];
		} else {
			properties[name] = value;
			return self;
		}
	}

	function normalizeOption(op) {
		if (typeof(op) == "object") {
			if (!op.text) {
				op.text = op.value;
			}
			return op;
		} else {
			op = "" + op;
			var idx = op.indexOf(":"),
				text = null,
				value = null;
			if (idx == -1) {
				value = op;
				text = op;
			} else {
				value = op.substring(0, idx);
				text = op.substring(idx+1);
			}
			return {
				"value": value,
				"text": text
			};
		}
	}
	function normalizeOptions(options) {
		var ret = [];
		for (var i=0; i<options.length; i++) {
			var op = normalizeOption(options[i]);
			ret.push(op);
		}
		return ret;
	}

	var defaultProperties = {
		"size" : 0,
		"placeHolder" : null,
		"helpText" : null,
		"follow" : false,
		"labelSize" : 0
	};
	function BasicInput(name, type, label, options) {
		var self = this;
		function initProperties(hash) {
			self.properties = $.extend(true, {}, defaultProperties, self.properties, hash);
console.log(self.properties);
		}
		function doProperties(name, v) {
			return property(self.properties, name, v);
		}
		if (!options) {
			options = {};
		}
		options.name = name;
		options.type = type;
		options.label = label;
		initProperties(options);

		$.extend(this, {
			"name" : function(v) { return doProperties("name", v);},
			"type" : function(v) { return doProperties("type", v);},
			"label" : function(v) { return doProperties("label", v);},
			"size" : function(v) { return doProperties("size", v);},
			"placeHolder" : function(v) { return doProperties("placeHolder", v);},
			"helpText" : function(v) { return doProperties("helpText", v);},
			"follow" : function(v) { return doProperties("follow", v);},
			"labelSize" : function(v) { return doProperties("labelSize", v);},
			"initProperties" : initProperties,
			"doProperties" : doProperties
		});
	}
	function Select(name, label, values, options) {
		function build($select) {
			var $group = null;
			for (var i=0; i<values.length; i++) {
				var op = values[i],
					$op = $("<option/>");
				$op.attr("value", op.value);
				$op.text(op.text);
				if (op.selected) {
					$op.attr("selected", "selected");
				}
				if (op.disabled) {
					$op.attr("disabled", "disabled");
				}
				if (op.group) {
					if ($group == null || $group.attr("label") != op.group) {
						$group = $("<optGroup/>");
						$group.attr("label", op.group);
						$select.append($group);
					}
				}
				if ($group) {
					$group.append($op);
				} else {
					$select.append($op);
				}
			}
		}
		function addOption(value, text) {
			if (typeof(value) === "string" && text) {
				value = value + ":" + text;
			}
			values.push(normalizeOption(value));
		}
		if (values && !$.isArray(values)) {
			options = values;
			values = [];
		}
		this.initProperties(options);
		this.name(name);
		this.label(label);
		if (!values) {
			values = [];
		}
		values = normalizeOptions(values);
		$.extend(this, {
			"build" : build,
			"addOption" : addOption
		});
	}
	Select.prototype = new BasicInput(null, "select", null);

	function Textarea(name, label, rows, options) {
		var self = this;
		if (typeof(rows) === "object") {
			options = rows;
			rows = null;
		}
		if (!options) {
			options = {};
		}
		if (!options.rows) {
			options.rows = rows || 3;
		}
		this.initProperties(options);
		this.name(name);
		this.label(label);
		$.extend(this, {
			"rows" : function(v) { return self.doProperties("rows", v);}
		});
	}
	Textarea.prototype = new BasicInput(null, "textarea", null);

	function Checkbox(name, label, values, options) {
		var self = this;

		function build($div) {
			for (var i=0; i<values.length; i++) {
				var op = values[i],
					$label = $("<label/>"),
					$input = $("<input/>");
				if (self.inline()) {
					$label.addClass(self.type() + "-inline");
				}
				$input.attr({
					"name" : self.name(),
					"type" : self.type(),
					"value" : op.value
				});
				$label.append($input).append(op.text);
				$div.append($label);
			}
		}
		function addValue(value, text) {
			if (typeof(value) === "string" && text) {
				value = value + ":" + text;
			}
			values.push(normalizeOption(value));
		}
		if (values && !$.isArray(values)) {
			options = values;
			values = [];
		}
		if (!values) {
			values = [];
		}
		values = normalizeOptions(values);
		if (!options) {
			options = {};
		}
		if (typeof(options.inline) === "undefined") {
			options.inline = true;
		}
		this.initProperties(options);
		this.name(name);
		this.label(label);
		$.extend(this, {
			"build" : build,
			"inline" : function(v) { return self.doProperties("inline", v);},
			"addValue" : addValue
		});
	}
	Checkbox.prototype = new BasicInput(null, "checkbox", null);

	function Bootstrap3Form($form, options) {
		var self = this,
			generated = false,
			properties = {
				"horizontal" : false,
				"idPrefix" : "",
				"labelSize" : 3,
				"gridSize" : "sm"
			};
		$form = $(form);

		if (options) {
			$.extend(properties, options);
		}

		var controls = [];

		function col(n) {
			return "col-" + properties.gridSize + "-" + n;
		}
		function offset(n) {
			return "col-" + properties.gridSize + "-offset-" + n;
		}

		function addInput(name, type, label, options) {
			var obj = new BasicInput(name, type, label, options);
			controls.push(obj);
			return obj;
		}
		function addSelect(name, label, values, options) {
			var obj = new Select(name, label, values, options);
			controls.push(obj);
			return obj;
		}
		function addTextarea(name, label, rows, options) {
			var obj = new Textarea(name, label, rows, options);
			controls.push(obj);
			return obj;
		}
		function addCheckbox(name, label, values, options) {
			var obj = new Checkbox(name, label, values, options);
			controls.push(obj);
			return obj;
		}
		function addRadio(name, type, label) {
			var obj = {
				"name" : name,
				"type" : type,
				"label" : label
			};
			controls.push(obj);
			generate();
		}
		function isFollowGroup(index) {
			if (!self.horizontal()) {
				return false;
			}
			var obj = controls[index];
			if (obj.follow()) {
				return true;
			}
			if (controls.length > index + 1 && controls[index+1].follow()) {
				return true;
			}
			return false;
		}
		function generate() {
			$form.empty();
			$form.addClass("form-horizontal");
			$.each(controls, function(index, obj) {
				var $div = $("<div/>"),
					$label = $("<label/>"),
					id = self.idPrefix() + obj.name(),
					labelSize = obj.labelSize() || self.labelSize(),
					$input = null;

				$label.html(obj.label());
				if (self.horizontal()) {
					$label.addClass(col(labelSize));
					$label.addClass("control-label");
				} else {
					$label.addClass(col(12));
				}
				if (self.horizontal() && obj.follow()) {
					$div = $form.find(".form-group:last");
				} else {
					$div.addClass("form-group");
					$form.append($div);
				}
				$div.append($label);

				if (obj.type() == "checkbox" || obj.type() == "radio") {
					var $childDiv = $("<div/>");
					if (!obj.inline()) {
						$childDiv.addClass(obj.type());
					}
					$childDiv.addClass(col(self.horizontal() ? 12 - labelSize : 12));
					$div.append($childDiv);
					obj.build($childDiv);
				} else {
					if (obj.type() == "textarea") {
						$input = $("<textarea/>");
						$input.attr("rows", obj.rows() || 3);
					} else if (obj.type() == "select") {
						$input = $("<select/>");
						obj.build($input);
					} else {
						$input = $("<input/>");
					}
					$input.attr({
						"type" : obj.type(),
						"id" : id,
						"name" : obj.name()
					});
					$input.addClass("form-control");
					if (obj.placeHolder()) {
						$input.attr("placeholder", obj.placeHolder());
					}
					$label.attr("for", id);

					var $inputDiv = $("<div/>");
					$inputDiv.addClass(col(obj.size() || (self.horizontal() ? 12 - labelSize : 12)));
					$inputDiv.append($input);
					$div.append($inputDiv);

					if (obj.helpText()) {
						var helpBlock = $("<span/>");
						helpBlock.addClass("help-block");
						helpBlock.html(obj.helpText());
						if (self.horizontal()) {
							if (isFollowGroup(index)) {
								$inputDiv.append(helpBlock);
							} else {
								helpBlock.addClass(col(12 - labelSize));
								helpBlock.addClass(offset(labelSize));
								$div.append(helpBlock);
							}
						} else {
							if (obj.size()) {
								var dummy = $("<div/>");
								dummy.addClass(col(12 - obj.size()));
								dummy.addClass("dummy");
								dummy.height($inputDiv.outerHeight());
								$div.append(dummy);
							}
							helpBlock.addClass(col(12));
							$div.append(helpBlock);
						}
					}
				}
			});
			generated = true;
		}
		$.extend(this, {
			"addInput" : addInput,
			"addSelect" : addSelect,
			"addCheckbox" : addCheckbox,
			"addRadio" : addRadio,
			"addTextarea" : addTextarea,
			"generate" : generate,
			"horizontal" : function(v) { return property(properties, "horizontal", v);},
			"idPrefix" : function(v) { return property(properties, "idPrefix", v);},
			"labelSize" : function(v) { return property(properties, "labelSize", v);}
		});
	}
	$.fn.bootstrap3form = function(options) {
		return new Bootstrap3Form($(this), options);
	}

})(jQuery);
<commit_msg>bugfix<commit_after>(function($) {
	"use strict";

	function property(properties, name, value) {
		if (value === undefined) {
			return properties[name];
		} else {
			properties[name] = value;
			return self;
		}
	}

	function normalizeOption(op) {
		if (typeof(op) == "object") {
			if (!op.text) {
				op.text = op.value;
			}
			return op;
		} else {
			op = "" + op;
			var idx = op.indexOf(":"),
				text = null,
				value = null;
			if (idx == -1) {
				value = op;
				text = op;
			} else {
				value = op.substring(0, idx);
				text = op.substring(idx+1);
			}
			return {
				"value": value,
				"text": text
			};
		}
	}
	function normalizeOptions(options) {
		var ret = [];
		for (var i=0; i<options.length; i++) {
			var op = normalizeOption(options[i]);
			ret.push(op);
		}
		return ret;
	}

	var defaultProperties = {
		"size" : 0,
		"placeHolder" : null,
		"helpText" : null,
		"follow" : false,
		"labelSize" : 0
	};
	function BasicInput(name, type, label, options) {
		var self = this;
		function initProperties(hash) {
			self.properties = $.extend(true, {}, defaultProperties, self.properties, hash);
		}
		function doProperties(name, v) {
			return property(self.properties, name, v);
		}
		if (!options) {
			options = {};
		}
		options.name = name;
		options.type = type;
		options.label = label;
		initProperties(options);

		$.extend(this, {
			"name" : function(v) { return doProperties("name", v);},
			"type" : function(v) { return doProperties("type", v);},
			"label" : function(v) { return doProperties("label", v);},
			"size" : function(v) { return doProperties("size", v);},
			"placeHolder" : function(v) { return doProperties("placeHolder", v);},
			"helpText" : function(v) { return doProperties("helpText", v);},
			"follow" : function(v) { return doProperties("follow", v);},
			"labelSize" : function(v) { return doProperties("labelSize", v);},
			"initProperties" : initProperties,
			"doProperties" : doProperties
		});
	}
	function Select(name, label, values, options) {
		function build($select) {
			var $group = null;
			for (var i=0; i<values.length; i++) {
				var op = values[i],
					$op = $("<option/>");
				$op.attr("value", op.value);
				$op.text(op.text);
				if (op.selected) {
					$op.attr("selected", "selected");
				}
				if (op.disabled) {
					$op.attr("disabled", "disabled");
				}
				if (op.group) {
					if ($group == null || $group.attr("label") != op.group) {
						$group = $("<optGroup/>");
						$group.attr("label", op.group);
						$select.append($group);
					}
				}
				if ($group) {
					$group.append($op);
				} else {
					$select.append($op);
				}
			}
		}
		function addOption(value, text) {
			if (typeof(value) === "string" && text) {
				value = value + ":" + text;
			}
			values.push(normalizeOption(value));
		}
		if (values && !$.isArray(values)) {
			options = values;
			values = [];
		}
		this.__proto__ = new BasicInput(name, "select", label, options);
		if (!values) {
			values = [];
		}
		values = normalizeOptions(values);
		$.extend(this, {
			"build" : build,
			"addOption" : addOption
		});
	}

	function Textarea(name, label, rows, options) {
		var self = this;
		if (typeof(rows) === "object") {
			options = rows;
			rows = null;
		}
		if (!options) {
			options = {};
		}
		if (!options.rows) {
			options.rows = rows || 3;
		}
		this.__proto__ = new BasicInput(name, "textarea", label, options);
		$.extend(this, {
			"rows" : function(v) { return self.doProperties("rows", v);}
		});
	}

	function Checkbox(name, label, values, options) {
		var self = this;

		function build($div) {
			for (var i=0; i<values.length; i++) {
				var op = values[i],
					$label = $("<label/>"),
					$input = $("<input/>");
				if (self.inline()) {
					$label.addClass(self.type() + "-inline");
				}
				$input.attr({
					"name" : self.name(),
					"type" : self.type(),
					"value" : op.value
				});
				$label.append($input).append(op.text);
				if (self.inline()) {
					$div.append($label);
				} else {
					var $childDiv = $("<div/>");
					$childDiv.addClass(self.type());
					$childDiv.append($label);
					$div.append($childDiv);
				}
			}
		}
		function addValue(value, text) {
			if (typeof(value) === "string" && text) {
				value = value + ":" + text;
			}
			values.push(normalizeOption(value));
		}
		if (values && !$.isArray(values)) {
			options = values;
			values = [];
		}
		if (!values) {
			values = [];
		}
		values = normalizeOptions(values);
		if (!options) {
			options = {};
		}
		if (typeof(options.inline) === "undefined") {
			options.inline = true;
		}
		this.__proto__ = new BasicInput(name, "checkbox", label, options);
		$.extend(this, {
			"build" : build,
			"inline" : function(v) { return self.doProperties("inline", v);},
			"addValue" : addValue
		});
	}

	function Bootstrap3Form($form, options) {
		var self = this,
			generated = false,
			properties = {
				"horizontal" : false,
				"idPrefix" : "",
				"labelSize" : 3,
				"gridSize" : "sm"
			};
		$form = $(form);

		if (options) {
			$.extend(properties, options);
		}

		var controls = [];

		function col(n) {
			return "col-" + properties.gridSize + "-" + n;
		}
		function offset(n) {
			return "col-" + properties.gridSize + "-offset-" + n;
		}

		function addInput(name, type, label, options) {
			var obj = new BasicInput(name, type, label, options);
			controls.push(obj);
			return obj;
		}
		function addSelect(name, label, values, options) {
			var obj = new Select(name, label, values, options);
			controls.push(obj);
			return obj;
		}
		function addTextarea(name, label, rows, options) {
			var obj = new Textarea(name, label, rows, options);
			controls.push(obj);
			return obj;
		}
		function addCheckbox(name, label, values, options) {
			var obj = new Checkbox(name, label, values, options);
			controls.push(obj);
			return obj;
		}
		function addRadio(name, type, label) {
			var obj = {
				"name" : name,
				"type" : type,
				"label" : label
			};
			controls.push(obj);
			generate();
		}
		function isFollowGroup(index) {
			if (!self.horizontal()) {
				return false;
			}
			var obj = controls[index];
			if (obj.follow()) {
				return true;
			}
			if (controls.length > index + 1 && controls[index+1].follow()) {
				return true;
			}
			return false;
		}
		function generate() {
			$form.empty();
			$form.addClass("form-horizontal");
			$.each(controls, function(index, obj) {
				var $div = $("<div/>"),
					$label = $("<label/>"),
					id = self.idPrefix() + obj.name(),
					labelSize = obj.labelSize() || self.labelSize(),
					$input = null;

				$label.html(obj.label());
				if (self.horizontal()) {
					$label.addClass(col(labelSize));
					$label.addClass("control-label");
				} else {
					$label.addClass(col(12));
				}
				if (self.horizontal() && obj.follow()) {
					$div = $form.find(".form-group:last");
				} else {
					$div.addClass("form-group");
					$form.append($div);
				}
				$div.append($label);

				if (obj.type() == "checkbox" || obj.type() == "radio") {
					var $childDiv = $("<div/>");
					$childDiv.addClass(col(self.horizontal() ? 12 - labelSize : 12));
					$div.append($childDiv);
					obj.build($childDiv);
				} else {
					if (obj.type() == "textarea") {
						$input = $("<textarea/>");
						$input.attr("rows", obj.rows() || 3);
					} else if (obj.type() == "select") {
						$input = $("<select/>");
						obj.build($input);
					} else {
						$input = $("<input/>");
					}
					$input.attr({
						"type" : obj.type(),
						"id" : id,
						"name" : obj.name()
					});
					$input.addClass("form-control");
					if (obj.placeHolder()) {
						$input.attr("placeholder", obj.placeHolder());
					}
					$label.attr("for", id);

					var $inputDiv = $("<div/>");
					$inputDiv.addClass(col(obj.size() || (self.horizontal() ? 12 - labelSize : 12)));
					$inputDiv.append($input);
					$div.append($inputDiv);

					if (obj.helpText()) {
						var helpBlock = $("<span/>");
						helpBlock.addClass("help-block");
						helpBlock.html(obj.helpText());
						if (self.horizontal()) {
							if (isFollowGroup(index)) {
								$inputDiv.append(helpBlock);
							} else {
								helpBlock.addClass(col(12 - labelSize));
								helpBlock.addClass(offset(labelSize));
								$div.append(helpBlock);
							}
						} else {
							if (obj.size()) {
								var dummy = $("<div/>");
								dummy.addClass(col(12 - obj.size()));
								dummy.addClass("dummy");
								dummy.height($inputDiv.outerHeight());
								$div.append(dummy);
							}
							helpBlock.addClass(col(12));
							$div.append(helpBlock);
						}
					}
				}
			});
			generated = true;
		}
		$.extend(this, {
			"addInput" : addInput,
			"addSelect" : addSelect,
			"addCheckbox" : addCheckbox,
			"addRadio" : addRadio,
			"addTextarea" : addTextarea,
			"generate" : generate,
			"horizontal" : function(v) { return property(properties, "horizontal", v);},
			"idPrefix" : function(v) { return property(properties, "idPrefix", v);},
			"labelSize" : function(v) { return property(properties, "labelSize", v);}
		});
	}
	$.fn.bootstrap3form = function(options) {
		return new Bootstrap3Form($(this), options);
	}

})(jQuery);
<|endoftext|>


<commit_before>var constructSimMatrix = function constructSimMatrix(worker) {
    /*************** Private variables ***************/
    /* UI variables */
    var margin = {top: 10, right: 200, bottom: 10, left: 0},
        matrix_padding = 0.03,
        width = 500,
        height = 500;

    /* variable to contain our d3 selectors */
    var svg;

    /* Scales */
    var x = d3.scale.ordinal().rangeBands([0, width], matrix_padding),
        z = d3.scale.linear().domain([0, 1]).clamp(true);

    /* Constructor fields */
    var names = [],
        order = [],
        treeOrder = [],
        matrix = [],
        clustered = false,
        updated = false,
        newick,
        worker = worker;

    var tabSelector = $('a[href="#sim_matrix_wrapper"]');

    var that = {};

    /*************** Private methods ***************/

    /* generate a row */
    function rowF(row) {
        var cell = d3.select(this).selectAll(".cell")
            //.data(row.filter(function(d) { return d.z; }))
            .data(row)
            .attr("x", function(d, i) { return x(i); })
            .attr("width", x.rangeBand())
            .attr("height", x.rangeBand())
            .style("fill-opacity", function(d) { return z(d * d); })
            .style("fill", function(d) { return (d != -1) ? "steelblue" : "white" })
          .enter().append("rect")
            .attr("class", "cell")
            .attr("x", function(d, i) { return x(i); })
            .attr("width", x.rangeBand())
            .attr("height", x.rangeBand())
            .style("fill-opacity", function(d) { return z(d * d); })
            .style("fill", function(d) { return (d != -1) ? "steelblue" : "white" });
    }

    /* add popover to all cells */
    function popOverF(row, j) {
        d3.select(this).selectAll(".cell")
            .each(function(d, i) {
                $(this).popover('destroy');
                content = d >= 0 ? d3.format(".2%")(d) + " peptidome similarity" : "Not calculated";
                $(this).popover({title: names[order[i]].name + "
" + names[order[j]].name, content: content, trigger: 'hover', placement: 'top', container: 'body', html: true});
            });
    }
    /* TODO: can this be abstracted? */
    function sendToWorker(type, message) {
        worker.postMessage({'cmd': type, 'msg': message});
    }

    function setupWorker() {
        /* setup worker */
        worker.addEventListener('message', function (e) {
            var data = e.data;
            switch (data.type) {
            case 'newOrder':
                that.reOrder(data.msg);
                break;
            case 'matrixData':
                receiveMatrix(data.msg);
                break;
            case 'newick':
                that.drawTree(data.msg);
                break;
            case 'log':
                console.log(data.msg);
                break;
            }
        });
    }

    /* receive the new matrix from the worker */
    function receiveMatrix(m) {
        matrix = m;
        updated = true;
        that.reDraw();
    }

    /**
     *
     * initializes the Matrix
     *
     */
    function init() {
        setupWorker();
        tabSelector.on('shown.bs.tab', function () {
            that.reDraw();
        });
        $("#sim_matrix_buttons").prepend("<button id='calculate-matrix-btn' class='btn btn-default'> Calculate Similarity Matrix</button>");
        $("#calculate-matrix-btn").click(function () {
            that.calculateSimilarity();
        });
        $("#sim_matrix_buttons").prepend("<button id='cluster-matrix-btn' class='btn btn-default'> Cluster Similarity Matrix</button>");
        $("#cluster-matrix-btn").click(function () {
            that.clusterMatrix();
        });
    }

    /*************** Public methods ***************/

    /* reOrder the matrix based on the new order */
    that.reOrder = function (newOrder) {
        treeOrder = newOrder;
        x.domain(newOrder);
        var t = svg.transition().duration(2500);

        t.selectAll(".row")
            .delay(function(d, i) { return x(i) * 4; })
            .attr("transform", function(d, i) { return "translate(0," + x(i) + ")"; })
            .selectAll(".cell")
            .delay(function(d, i) { return x(i) * 4; })
            .attr("x", function(d, i) { return x(i); });

        t.selectAll(".column")
            .delay(function(d, i) { return x(i) * 4; })
            .attr("transform", function(d, i) { return "translate(" + x(i) + ")rotate(-90)"; });
        clustered = true;
        updated = true;
    }

    that.reDraw = function () {
        // Check if we are currently active pane
        if (! that.activeTab() || ! updated ) {
            return;
        }

        updated = false;

        /* TODO: instead of appending, this needs more selectAll I think */
        if (! svg) {
            svg = d3.select("#sim_matrix").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

            svg.append("rect")
                .attr("class", "background")
                .attr("width", width)
                .attr("height", height)
                .attr("fill", "#eeeeee");
        }

        if (!clustered) {
            // The default sort order.
            x.domain(d3.range(order.length));
        }

        var row = svg.selectAll(".row")
            .data(matrix)

        row.attr("transform", function(d, i) { return "translate(0," + x(i) + ")"; })
            .each(rowF);

        row.selectAll("text").attr('y', x.rangeBand() / 2);

        row_enter = row.enter().append("g")
            .attr("class", "row")
            .attr("transform", function(d, i) { return "translate(0," + x(i) + ")"; })
            .each(rowF);

        row_enter.append("line")
            .attr("x2", width)
            .attr("stroke", "#ffffff");

        row_enter.append("text")
            .attr("x", width + 6)
            .attr("y", x.rangeBand() / 2)
            .attr("dy", ".32em")
            .attr("text-anchor", "start")
            .text(function(d, i) { return names[order[i]].name; });

        var column = svg.selectAll(".column")
            .data(matrix)
            .attr("transform", function(d, i) { return "translate(" + x(i) + ")rotate(-90)"; })
            .attr("y", x.rangeBand() / 2);

        column_enter = column.enter().append("g")
            .attr("class", "column")
            .attr("transform", function(d, i) { return "translate(" + x(i) + ")rotate(-90)"; });

        column_enter.append("line")
            .attr("x1", -width)
            .attr("stroke", "#ffffff");

        row.each(popOverF);

    }

    that.drawTree = function (n) {
        newick = n;
        var parsed = Newick.parse(n);
        $("#sim_graph").html("");
        d3.phylogram.build('#sim_graph', parsed, {width: 100, height: 500}, treeOrder);
    }

    /* calculate similarity */
    that.calculateSimilarity = function () {
        sendToWorker('calculateSimilarity');
    }

    that.clusterMatrix = function () {
        sendToWorker('clusterMatrix');
    }

    /* add data to the matrix */
    that.addGenome = function(id, name) {
        names[id] = {'name': name};
        order.push(id);
        var length = matrix.length;
        for (var x = 0; x < length; x ++) {
            // add -1 to the end
            matrix[x].push(-1);
        }

        var new_row = []
        for (var x = 0; x < order.length; x ++) {
            new_row.push(-1);
        }
        matrix.push(new_row);

        clustered = false;
        updated = true;
        if( that.activeTab() ) {
            that.calculateSimilarity();
        }

        that.reDraw();
    }

    /* remove data from the matrix */
    that.removeGenome = function(id) {
        delete names[id];
        var index = order.indexOf(id);
        order.splice(index, 1);

        matrix.splice(index, 1);
        for (var x = 0; x < matrix.length; x ++) {
            // add -1 to the end
            matrix[x].splice(index, 1);
        }
        clustered = false;
        updated = true;
        that.reDraw();
    }

    that.activeTab = function () {
        return tabSelector.parent().hasClass("active");
    }

    // initialize the object
    init();

    return that;
};
<commit_msg>keep popovers on click, with some ugly variables<commit_after>var constructSimMatrix = function constructSimMatrix(worker) {
    /*************** Private variables ***************/
    /* UI variables */
    var margin = {top: 10, right: 200, bottom: 10, left: 0},
        matrix_padding = 0.03,
        width = 500,
        height = 500;

    /* variable to contain our d3 selectors */
    var svg;

    /* Scales */
    var x = d3.scale.ordinal().rangeBands([0, width], matrix_padding),
        z = d3.scale.linear().domain([0, 1]).clamp(true);

    /* Constructor fields */
    var names = [],
        order = [],
        treeOrder = [],
        matrix = [],
        clustered = false,
        updated = false,
        newick,
        worker = worker;

    var tabSelector = $('a[href="#sim_matrix_wrapper"]');

    var that = {};

    /*************** Private methods ***************/

    /* generate a row */
    function rowF(row) {
        var cell = d3.select(this).selectAll(".cell")
            //.data(row.filter(function(d) { return d.z; }))
            .data(row)
            .attr("x", function(d, i) { return x(i); })
            .attr("width", x.rangeBand())
            .attr("height", x.rangeBand())
            .style("fill-opacity", function(d) { return z(d * d); })
            .style("fill", function(d) { return (d != -1) ? "steelblue" : "white" })
          .enter().append("rect")
            .attr("class", "cell")
            .attr("x", function(d, i) { return x(i); })
            .attr("width", x.rangeBand())
            .attr("height", x.rangeBand())
            .style("fill-opacity", function(d) { return z(d * d); })
            .style("fill", function(d) { return (d != -1) ? "steelblue" : "white" });
    }

    /* add popover to all cells */
    function popOverF(row, j) {
        d3.select(this).selectAll(".cell")
            .each(function(d, i) {
                var content = d >= 0 ? d3.format(".2%")(d) + " peptidome similarity" : "Not calculated";
                var clicked = false;
                $(this).popover('destroy');
                $(this).popover({title: names[order[i]].name + "
" + names[order[j]].name, content: content, trigger: 'manual', placement: 'top', container: 'body', html: true});
                $(this).hover(function() {
                    if(!clicked) {
                        $(this).popover('show');
                    }
                }, function () {
                    if(!clicked) {
                        $(this).popover('hide');
                    }
                });

                $(this).click(function() {
                    if(clicked) {
                        $(this).popover('hide');
                    }
                    clicked = !clicked;
                });
            });
    }
    /* TODO: can this be abstracted? */
    function sendToWorker(type, message) {
        worker.postMessage({'cmd': type, 'msg': message});
    }

    function setupWorker() {
        /* setup worker */
        worker.addEventListener('message', function (e) {
            var data = e.data;
            switch (data.type) {
            case 'newOrder':
                that.reOrder(data.msg);
                break;
            case 'matrixData':
                receiveMatrix(data.msg);
                break;
            case 'newick':
                that.drawTree(data.msg);
                break;
            case 'log':
                console.log(data.msg);
                break;
            }
        });
    }

    /* receive the new matrix from the worker */
    function receiveMatrix(m) {
        matrix = m;
        updated = true;
        that.reDraw();
    }

    /**
     *
     * initializes the Matrix
     *
     */
    function init() {
        setupWorker();
        tabSelector.on('shown.bs.tab', function () {
            that.reDraw();
        });
        $("#sim_matrix_buttons").prepend("<button id='calculate-matrix-btn' class='btn btn-default'> Calculate Similarity Matrix</button>");
        $("#calculate-matrix-btn").click(function () {
            that.calculateSimilarity();
        });
        $("#sim_matrix_buttons").prepend("<button id='cluster-matrix-btn' class='btn btn-default'> Cluster Similarity Matrix</button>");
        $("#cluster-matrix-btn").click(function () {
            that.clusterMatrix();
        });
    }

    /*************** Public methods ***************/

    /* reOrder the matrix based on the new order */
    that.reOrder = function (newOrder) {
        treeOrder = newOrder;
        x.domain(newOrder);
        var t = svg.transition().duration(2500);

        t.selectAll(".row")
            .delay(function(d, i) { return x(i) * 4; })
            .attr("transform", function(d, i) { return "translate(0," + x(i) + ")"; })
            .selectAll(".cell")
            .delay(function(d, i) { return x(i) * 4; })
            .attr("x", function(d, i) { return x(i); });

        t.selectAll(".column")
            .delay(function(d, i) { return x(i) * 4; })
            .attr("transform", function(d, i) { return "translate(" + x(i) + ")rotate(-90)"; });
        clustered = true;
        updated = true;
    }

    that.reDraw = function () {
        // Check if we are currently active pane
        if (! that.activeTab() || ! updated ) {
            return;
        }

        updated = false;

        /* TODO: instead of appending, this needs more selectAll I think */
        if (! svg) {
            svg = d3.select("#sim_matrix").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

            svg.append("rect")
                .attr("class", "background")
                .attr("width", width)
                .attr("height", height)
                .attr("fill", "#eeeeee");
        }

        if (!clustered) {
            // The default sort order.
            x.domain(d3.range(order.length));
        }

        var row = svg.selectAll(".row")
            .data(matrix)

        row.attr("transform", function(d, i) { return "translate(0," + x(i) + ")"; })
            .each(rowF);

        row.selectAll("text").attr('y', x.rangeBand() / 2);

        row_enter = row.enter().append("g")
            .attr("class", "row")
            .attr("transform", function(d, i) { return "translate(0," + x(i) + ")"; })
            .each(rowF);

        row_enter.append("line")
            .attr("x2", width)
            .attr("stroke", "#ffffff");

        row_enter.append("text")
            .attr("x", width + 6)
            .attr("y", x.rangeBand() / 2)
            .attr("dy", ".32em")
            .attr("text-anchor", "start")
            .text(function(d, i) { return names[order[i]].name; });

        var column = svg.selectAll(".column")
            .data(matrix)
            .attr("transform", function(d, i) { return "translate(" + x(i) + ")rotate(-90)"; })
            .attr("y", x.rangeBand() / 2);

        column_enter = column.enter().append("g")
            .attr("class", "column")
            .attr("transform", function(d, i) { return "translate(" + x(i) + ")rotate(-90)"; });

        column_enter.append("line")
            .attr("x1", -width)
            .attr("stroke", "#ffffff");

        row.each(popOverF);

    }

    that.drawTree = function (n) {
        newick = n;
        var parsed = Newick.parse(n);
        $("#sim_graph").html("");
        d3.phylogram.build('#sim_graph', parsed, {width: 100, height: 500}, treeOrder);
    }

    /* calculate similarity */
    that.calculateSimilarity = function () {
        sendToWorker('calculateSimilarity');
    }

    that.clusterMatrix = function () {
        sendToWorker('clusterMatrix');
    }

    /* add data to the matrix */
    that.addGenome = function(id, name) {
        names[id] = {'name': name};
        order.push(id);
        var length = matrix.length;
        for (var x = 0; x < length; x ++) {
            // add -1 to the end
            matrix[x].push(-1);
        }

        var new_row = []
        for (var x = 0; x < order.length; x ++) {
            new_row.push(-1);
        }
        matrix.push(new_row);

        clustered = false;
        updated = true;
        if( that.activeTab() ) {
            that.calculateSimilarity();
        }

        that.reDraw();
    }

    /* remove data from the matrix */
    that.removeGenome = function(id) {
        delete names[id];
        var index = order.indexOf(id);
        order.splice(index, 1);

        matrix.splice(index, 1);
        for (var x = 0; x < matrix.length; x ++) {
            // add -1 to the end
            matrix[x].splice(index, 1);
        }
        clustered = false;
        updated = true;
        that.reDraw();
    }

    that.activeTab = function () {
        return tabSelector.parent().hasClass("active");
    }

    // initialize the object
    init();

    return that;
};
<|endoftext|>


<commit_before>import { sortByKey } from '../utils/model_utils';
import { RECEIVE_ARTICLES, SORT_ARTICLES } from '../constants';

const initialState = {
  articles: [],
  limit: 500,
  limitReached: false,
  sortKey: 'character_sum'
};

const SORT_DESCENDING = {
  rating_num: true,
  title: true,
  character_sum: true,
  view_count: true
};

const isLimitReached = (revs, limit) => {
  return (revs.length < limit);
};

export default function articles(state = initialState, action) {
  switch (action.type) {
    case RECEIVE_ARTICLES:
      return {
        articles: action.data.course.articles,
        limit: action.limit,
        limitReached: isLimitReached(action.data.course.articles, action.limit)
      };
    case SORT_ARTICLES: {
      const newState = { ...state };
      const sorted = sortByKey(newState.articles, action.key, state.sortKey, SORT_DESCENDING[action.key]);
      newState.users = sorted.newModels;
      newState.sortKey = sorted.newKey;
      return newState;
    }
    default:
      return state;
  }
}
<commit_msg>Align with current sort behavior<commit_after>import { sortByKey } from '../utils/model_utils';
import { RECEIVE_ARTICLES, SORT_ARTICLES } from '../constants';

const initialState = {
  articles: [],
  limit: 500,
  limitReached: false,
  sortKey: 'character_sum'
};

const SORT_DESCENDING = {
  character_sum: true,
  view_count: true
};

const isLimitReached = (revs, limit) => {
  return (revs.length < limit);
};

export default function articles(state = initialState, action) {
  switch (action.type) {
    case RECEIVE_ARTICLES:
      return {
        articles: action.data.course.articles,
        limit: action.limit,
        limitReached: isLimitReached(action.data.course.articles, action.limit)
      };
    case SORT_ARTICLES: {
      const newState = { ...state };
      const sorted = sortByKey(newState.articles, action.key, state.sortKey, SORT_DESCENDING[action.key]);
      newState.users = sorted.newModels;
      newState.sortKey = sorted.newKey;
      return newState;
    }
    default:
      return state;
  }
}
<|endoftext|>


<commit_before>/**
 * An Object Oriented page handler for the curate process.
 */

// Declare a ss (street seen) name space if it doesn't exist
var ss = ss || {};
ss.handler = ss.handler || {};

ss.handler.Curate = function(regionId) {

  this.regionId = regionId;

  // These instance variables can easily be overridden by setting
  // the appropriate property.
  this.panoramaMapId = 'panorama-map';
  this.panoramaId = 'panorama';
  this.editModalId = 'edit-location-modal';
  this.deleteModalId = 'delete-location-modal';
  this.deleteRegionModalId = 'delete-region-modal';
  this.locationIdPrefix = 'location-';
  this.countId = 'location-count'
  this.quantityId = 'quantity';
  this.proximityId = 'proximity';

  this.locked = false;

}

ss.handler.Curate.prototype.initialize = function (mapId, center, zoom, path) {

  polygon = new ss.Polygon(path);
  this.polygonMap = new ss.PolygonMap(polygon, mapId, center, zoom, false);

  var $this = this;

  if (!this.locked) {
    this.polygonMap.markerClickCb = function() {
      // Fire the click handler of the curate link
      // $('#' + $this.locationIdPrefix + this.getZIndex()).click();
      $this.editLocation(this.data.id, this.data.latitude , this.data.longitude, this.data.heading, this.data.pitch);
    }
  }

  this.polygonMap.markerPersistCb = function(position) {
    ss.Location.create($this.regionId, position.lat(), position.lng(), function(location, status, xhr) {

      // Promote our point from a pending point to a full marker
      point = new google.maps.LatLng(location.latitude, location.longitude);
      $this.polygonMap.promotePendingToMarker(location.id, point);

      // Update our counter
      $('#' + $this.countId).html($this.polygonMap.markers.length);

      // We should append a linked image below
      $(
        '',
        {
          id: $this.locationIdPrefix + location.id,
          class: 'thumbnail cursor new',
          'data-toggle': 'modal',
          onclick: 'curate.editLocation(' + location.id + ', ' + location.latitude + ', ' + location.longitude + ', ' +location.heading + ', ' + location.pitch + ');'
        }
      ).html('').prependTo('#images');

    });
  }
}

ss.handler.Curate.prototype.addPoints = function() {
  this.polygonMap.addPoints(
    document.getElementById(this.quantityId).value,
    document.getElementById(this.proximityId).value);
}

ss.handler.Curate.prototype.editLocation = function(id, latitude, longitude, heading, pitch) {
  if (this.locked) {
    alert('After launching a study, images can no longer be curated.');
  }
  else {
    // Enable modal
    editModal = $('#' + this.editModalId);
    editModal.modal();

    var $this = this;

    // Add some handlers for position and pov
    editModal.on('shown', function () {

      // Set the working location to be this location.
      $this.workingLocation = new ss.Location(id, latitude, longitude, heading, pitch);

      // Create a panorama and google map (required for panorama?)
      var position = new google.maps.LatLng(latitude,longitude);

      // Create panorama options
      var panoramaOptions = {
        position: position,
        pov: {
          heading: heading,
          pitch: pitch,
        },

        addressControl: false,
        linksControl: false,
        disableDoubleClickZoom: true,
        zoomControl: false,
        navigationControl: false,
        enableCloseButton: false,
        disableDefaultUI: true,
        scrollwheel: false,
        scaleControl: false,
        draggable: false,
        mapTypeControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

    // Create a map
    var mapOptions = {
      center: position,
      zoom: 12,
      disableDefaultUI: true,
      disableDoubleClickZoom: true,
      draggable: false,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById($this.panoramaMapId), mapOptions);

    // Associate the panorama
    var panorama = new google.maps.StreetViewPanorama(document.getElementById($this.panoramaId), panoramaOptions);
    map.setStreetView(panorama);

    marker = new google.maps.Marker({
      position: position,
      map: map,
      title: 'Location Id:\n  '+ id + '\n\nCoordinates:\n  ' + position.lat() + ', ' + position.lng(),

      });

      var $that = $this;

      google.maps.event.trigger(panorama, 'resize');
      google.maps.event.addListener(panorama, 'pov_changed', function() {
        $that.workingLocation.heading = panorama.getPov().heading;
        $that.workingLocation.pitch = panorama.getPov().pitch;
      });
    });
  }
}

/**
 * Shows the confirm delete dialog.
 */
ss.handler.Curate.prototype.deleteLocation = function() {
  $('#' + this.editModalId).modal('toggle');
  $('#' + this.deleteModalId).modal('toggle');
}

/**
 * Actually deletes the location.
 */
ss.handler.Curate.prototype.deleteLocationConfirm = function() {
  $('#' + this.deleteModalId).modal('toggle');
  $this = this;
  this.workingLocation.delete(function (location, status, xhr) {
    // delete the image
    $('#' + $this.locationIdPrefix + location.id).remove();

    $this.polygonMap.removeMarker(location.id);
  });
}

/**
 * Actually deletes the location.
 */
ss.handler.Curate.prototype.deleteRegion = function(id) {
  $('#' + this.deleteRegionModalId).modal('toggle');
  $this = this;
  region = new ss.Region(id);
  region.delete(function (region, status, xhr) {
    location = 'vote'
  });
}

/**
 * Cancels deletion and returns to the edit modal.
 */
ss.handler.Curate.prototype.deleteLocationCancel = function() {
  $('#' + this.deleteModalId).modal('toggle');
  $('#' + this.editModalId).modal('toggle');
}

ss.handler.Curate.prototype.updateLocation = function() {
  var $this = this;

  this.workingLocation.update(function(location, status, xhr) {
    if (status == "success") {
      // update the onclick
      $('#' + $this.locationIdPrefix + location.id).click(function(){
        $this.editLocation(location.id, location.latitude, location.longitude, location.heading, location.pitch);
      });
      // update the image
      $('#' + $this.locationIdPrefix + location.id).html(
        ''
        );
      $('#' + $this.editModalId).modal('toggle');
    }
  });

}

<commit_msg>remove picture before showing modal<commit_after>/**
 * An Object Oriented page handler for the curate process.
 */

// Declare a ss (street seen) name space if it doesn't exist
var ss = ss || {};
ss.handler = ss.handler || {};

ss.handler.Curate = function(regionId) {

  this.regionId = regionId;

  // These instance variables can easily be overridden by setting
  // the appropriate property.
  this.panoramaMapId = 'panorama-map';
  this.panoramaId = 'panorama';
  this.editModalId = 'edit-location-modal';
  this.deleteModalId = 'delete-location-modal';
  this.deleteRegionModalId = 'delete-region-modal';
  this.locationIdPrefix = 'location-';
  this.countId = 'location-count'
  this.quantityId = 'quantity';
  this.proximityId = 'proximity';

  this.locked = false;

}

ss.handler.Curate.prototype.initialize = function (mapId, center, zoom, path) {

  polygon = new ss.Polygon(path);
  this.polygonMap = new ss.PolygonMap(polygon, mapId, center, zoom, false);

  var $this = this;

  if (!this.locked) {
    this.polygonMap.markerClickCb = function() {
      // Fire the click handler of the curate link
      // $('#' + $this.locationIdPrefix + this.getZIndex()).click();
      $this.editLocation(this.data.id, this.data.latitude , this.data.longitude, this.data.heading, this.data.pitch);
    }
  }

  this.polygonMap.markerPersistCb = function(position) {
    ss.Location.create($this.regionId, position.lat(), position.lng(), function(location, status, xhr) {

      // Promote our point from a pending point to a full marker
      point = new google.maps.LatLng(location.latitude, location.longitude);
      $this.polygonMap.promotePendingToMarker(location.id, point);

      // Update our counter
      $('#' + $this.countId).html($this.polygonMap.markers.length);

      // We should append a linked image below
      $(
        '',
        {
          id: $this.locationIdPrefix + location.id,
          class: 'thumbnail cursor new',
          'data-toggle': 'modal',
          onclick: 'curate.editLocation(' + location.id + ', ' + location.latitude + ', ' + location.longitude + ', ' +location.heading + ', ' + location.pitch + ');'
        }
      ).html('').prependTo('#images');

    });
  }
}

ss.handler.Curate.prototype.addPoints = function() {
  this.polygonMap.addPoints(
    document.getElementById(this.quantityId).value,
    document.getElementById(this.proximityId).value);
}

ss.handler.Curate.prototype.editLocation = function(id, latitude, longitude, heading, pitch) {
  if (this.locked) {
    alert('After launching a study, images can no longer be curated.');
  }
  else {
    // Clean up any old maps in modal before enabling
    $('#' + this.panoramaId).html('');
    $('#' + this.panoramaMapId).html('');

    // Enable modal
    editModal = $('#' + this.editModalId);
    editModal.modal();

    var $this = this;

    // Add some handlers for position and pov
    editModal.on('shown', function () {

      // Set the working location to be this location.
      $this.workingLocation = new ss.Location(id, latitude, longitude, heading, pitch);

      // Create a panorama and google map (required for panorama?)
      var position = new google.maps.LatLng(latitude,longitude);

      // Create panorama options
      var panoramaOptions = {
        position: position,
        pov: {
          heading: heading,
          pitch: pitch,
        },

        addressControl: false,
        linksControl: false,
        disableDoubleClickZoom: true,
        zoomControl: false,
        navigationControl: false,
        enableCloseButton: false,
        disableDefaultUI: true,
        scrollwheel: false,
        scaleControl: false,
        draggable: false,
        mapTypeControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

    // Create a map
    var mapOptions = {
      center: position,
      zoom: 12,
      disableDefaultUI: true,
      disableDoubleClickZoom: true,
      draggable: false,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById($this.panoramaMapId), mapOptions);

    // Associate the panorama
    var panorama = new google.maps.StreetViewPanorama(document.getElementById($this.panoramaId), panoramaOptions);
    map.setStreetView(panorama);

    marker = new google.maps.Marker({
      position: position,
      map: map,
      title: 'Location Id:\n  '+ id + '\n\nCoordinates:\n  ' + position.lat() + ', ' + position.lng(),

      });

      var $that = $this;

      google.maps.event.trigger(panorama, 'resize');
      google.maps.event.addListener(panorama, 'pov_changed', function() {
        $that.workingLocation.heading = panorama.getPov().heading;
        $that.workingLocation.pitch = panorama.getPov().pitch;
      });
    });
  }
}

/**
 * Shows the confirm delete dialog.
 */
ss.handler.Curate.prototype.deleteLocation = function() {
  $('#' + this.editModalId).modal('toggle');
  $('#' + this.deleteModalId).modal('toggle');
}

/**
 * Actually deletes the location.
 */
ss.handler.Curate.prototype.deleteLocationConfirm = function() {
  $('#' + this.deleteModalId).modal('toggle');
  $this = this;
  this.workingLocation.delete(function (location, status, xhr) {
    // delete the image
    $('#' + $this.locationIdPrefix + location.id).remove();

    $this.polygonMap.removeMarker(location.id);
  });
}

/**
 * Actually deletes the location.
 */
ss.handler.Curate.prototype.deleteRegion = function(id) {
  $('#' + this.deleteRegionModalId).modal('toggle');
  $this = this;
  region = new ss.Region(id);
  region.delete(function (region, status, xhr) {
    location = 'vote'
  });
}

/**
 * Cancels deletion and returns to the edit modal.
 */
ss.handler.Curate.prototype.deleteLocationCancel = function() {
  $('#' + this.deleteModalId).modal('toggle');
  $('#' + this.editModalId).modal('toggle');
}

ss.handler.Curate.prototype.updateLocation = function() {
  var $this = this;

  this.workingLocation.update(function(location, status, xhr) {
    if (status == "success") {
      // update the onclick
      $('#' + $this.locationIdPrefix + location.id).click(function(){
        $this.editLocation(location.id, location.latitude, location.longitude, location.heading, location.pitch);
      });
      // update the image
      $('#' + $this.locationIdPrefix + location.id).html(
        ''
        );
      $('#' + $this.editModalId).modal('toggle');
    }
  });

}

<|endoftext|>