<commit_before>FBL.ns(function () {
  /**
   *
   * ### Security
   *
   * It is _believed_ that the following usage of `ko.contextFor` via `window.wrappedJSObject` is secure, but I'm not
   * going to stake anything too valuable on it. Potentially useful additional references:
   *
   * 1.  https://developer.mozilla.org/en-US/docs/en/XPCNativeWrapper
   * 2.  https://getfirebug.com/wiki/index.php/Using_win.wrappedJSObject
   *
   * @private
   *
   * @param firebugContext
   * @param object
   * @returns {?Knockout.Context}
   */
  function getKnockoutContext(firebugContext, object) {
    var rep;
    var realObject;
    var window;
    var knockout;
    var knockoutContextForFunction;

    // Much of this was adapted from UseInCommandLine from the base Firebug source.

    if (!object || typeof object === "boolean") {
      return null;
    }

    rep = Firebug.getRep(object, firebugContext);
    if (!rep || !rep.inspectable) {
      return null;
    }

    realObject = rep.getRealObject(object, firebugContext);
    if (!FBL.isElement(realObject)) {
      return null;
    }

    // Checking that `realObject` is an instance of `window.Element` is fairly defensive; not sure whether it has any
    // utility. This is simply an attempt to ensure that we don't pass anything exploitable into the `contextFor`
    // function.
    window = firebugContext.window;
    if (!window || !window.Element || !(realObject instanceof window.Element)) {
      return null;
    }

    knockoutContextForFunction = (knockout = window.wrappedJSObject.ko) && knockout.contextFor;
    if (knockoutContextForFunction && FBL.isFunction(knockoutContextForFunction)) {
      return knockoutContextForFunction(realObject);
    } else {
      return null;
    }
  }

  // Adapted from UseInCommandLine from the base Firebug source.
  var InspectKnockoutContext = FBL.extend(Firebug.Module, {
    dispatchName: "InspectKnockoutContext",

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Extends Module

    initialize: function () {
      Firebug.Module.initialize.apply(this, arguments);

      Firebug.registerUIListener(this);
    },

    shutdown: function () {
      Module.shutdown.apply(this, arguments);

      Firebug.unregisterUIListener(this);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // UI Listener

    onContextMenu: function (items, object, target, firebugContext, panel, popup) {
      var knockoutContext;
      var knockoutContextRep;
      var knockoutContextRealObject;

      knockoutContext = getKnockoutContext(firebugContext, object);
      if (!knockoutContext) {
        return;
      }

      // REVIEW: Not sure if going through `getRep` and `getRealObject` serve any purpose what so ever.

      knockoutContextRep = Firebug.getRep(knockoutContext, firebugContext);
      if (!knockoutContextRep || !knockoutContextRep.inspectable) {
        return;
      }

      knockoutContextRealObject = knockoutContextRep.getRealObject(knockoutContext, firebugContext);
      if (!knockoutContextRealObject) {
        return;
      }

      FBL.createMenuSeparator(popup);

      FBL.createMenuItem(popup, {
        label: "Inspect Knockout context",
        tooltiptext: "Open the Knockout context for the current element in the DOM panel",
        command: this.inspectKnockoutContext.bind(this, knockoutContextRealObject)
      });
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Context Menu Actions

    inspectKnockoutContext: function (knockoutContext) {
      Firebug.chrome.select(knockoutContext, "dom");
    }
  });

  Firebug.registerModule(InspectKnockoutContext);
});
<commit_msg>Add JSHint declarations.<commit_after>/* global FBL, Firebug, Module */

FBL.ns(function () {
  /**
   *
   * ### Security
   *
   * It is _believed_ that the following usage of `ko.contextFor` via `window.wrappedJSObject` is secure, but I'm not
   * going to stake anything too valuable on it. Potentially useful additional references:
   *
   * 1.  https://developer.mozilla.org/en-US/docs/en/XPCNativeWrapper
   * 2.  https://getfirebug.com/wiki/index.php/Using_win.wrappedJSObject
   *
   * @private
   *
   * @param firebugContext
   * @param object
   * @returns {?Knockout.Context}
   */
  function getKnockoutContext(firebugContext, object) {
    var rep;
    var realObject;
    var window;
    var knockout;
    var knockoutContextForFunction;

    // Much of this was adapted from UseInCommandLine from the base Firebug source.

    if (!object || typeof object === "boolean") {
      return null;
    }

    rep = Firebug.getRep(object, firebugContext);
    if (!rep || !rep.inspectable) {
      return null;
    }

    realObject = rep.getRealObject(object, firebugContext);
    if (!FBL.isElement(realObject)) {
      return null;
    }

    // Checking that `realObject` is an instance of `window.Element` is fairly defensive; not sure whether it has any
    // utility. This is simply an attempt to ensure that we don't pass anything exploitable into the `contextFor`
    // function.
    window = firebugContext.window;
    if (!window || !window.Element || !(realObject instanceof window.Element)) {
      return null;
    }

    knockoutContextForFunction = (knockout = window.wrappedJSObject.ko) && knockout.contextFor;
    if (knockoutContextForFunction && FBL.isFunction(knockoutContextForFunction)) {
      return knockoutContextForFunction(realObject);
    } else {
      return null;
    }
  }

  // Adapted from UseInCommandLine from the base Firebug source.
  var InspectKnockoutContext = FBL.extend(Firebug.Module, {
    dispatchName: "InspectKnockoutContext",

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Extends Module

    initialize: function () {
      Firebug.Module.initialize.apply(this, arguments);

      Firebug.registerUIListener(this);
    },

    shutdown: function () {
      Module.shutdown.apply(this, arguments);

      Firebug.unregisterUIListener(this);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // UI Listener

    onContextMenu: function (items, object, target, firebugContext, panel, popup) {
      var knockoutContext;
      var knockoutContextRep;
      var knockoutContextRealObject;

      knockoutContext = getKnockoutContext(firebugContext, object);
      if (!knockoutContext) {
        return;
      }

      // REVIEW: Not sure if going through `getRep` and `getRealObject` serve any purpose what so ever.

      knockoutContextRep = Firebug.getRep(knockoutContext, firebugContext);
      if (!knockoutContextRep || !knockoutContextRep.inspectable) {
        return;
      }

      knockoutContextRealObject = knockoutContextRep.getRealObject(knockoutContext, firebugContext);
      if (!knockoutContextRealObject) {
        return;
      }

      FBL.createMenuSeparator(popup);

      FBL.createMenuItem(popup, {
        label: "Inspect Knockout context",
        tooltiptext: "Open the Knockout context for the current element in the DOM panel",
        command: this.inspectKnockoutContext.bind(this, knockoutContextRealObject)
      });
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Context Menu Actions

    inspectKnockoutContext: function (knockoutContext) {
      Firebug.chrome.select(knockoutContext, "dom");
    }
  });

  Firebug.registerModule(InspectKnockoutContext);
});
<|endoftext|>


<commit_before>'use strict';

var ddsApp = angular.module('acceptanceTests', ['ui.router', 'ngAnimate', 'ui.bootstrap', 'ngStorage', 'ngSanitize', 'ddsCommon']);

ddsApp.config(function($locationProvider, $stateProvider, $urlRouterProvider) {
    moment.lang('fr');

    $locationProvider.html5Mode(true);
    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('index', {
            url: '/?testId',
            templateUrl: '/acceptance-tests/partials/index.html',
            controller: 'IndexCtrl',
            resolve: {
                acceptanceTests: ['$http', function($http) {
                    return $http.get('/api/acceptance-tests').then(function(result) {
                        return result.data;
                    });
                }]
            }
        })
        .state('login', {
            url: '/login',
            templateUrl: '/acceptance-tests/partials/login.html',
            controller: 'LoginCtrl',
            anonymous: true,
            onEnter: ['$state', 'UserService', function($state, UserService) {
                if (UserService.user()) {
                    $state.go('index');
                }
            }]
        })
        .state('new', {
            url: '/new/:situationId',
            templateUrl: '/acceptance-tests/partials/form.html',
            controller: 'FormCtrl',
            resolve: {
                droitsObtenus: ['$http', '$stateParams', function($http, $stateParams) {
                    return $http.get('/api/situations/' + $stateParams.situationId + '/simulation').then(function(result) {
                        return result.data;
                    });
                }],
                test: function() {
                    return null;
                }
            }
        })
        .state('edit', {
            url: '/:testId/edit',
            templateUrl: '/acceptance-tests/partials/form.html',
            controller: 'FormCtrl',
            resolve: {
                droitsObtenus: function() {
                    return null;
                },
                test: ['$http', '$stateParams', function($http, $stateParams) {
                    return $http.get('/api/acceptance-tests/' + $stateParams.testId).then(function(result) {
                        return result.data;
                    });
                }]
            }
        });
});

ddsApp.run(function($rootScope, $state, $stateParams, UserService) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

    $rootScope.$on('$stateChangeStart', function(e, state) {
        if (!UserService.user() && !state.anonymous) {
            e.preventDefault();
            $state.go('login');
        }
    });

    UserService.retrieveUserAsync()
        .finally(function() {
            $rootScope.appReady = true;
        });
});
<commit_msg>fix secutire acceptance tests<commit_after>'use strict';

var ddsApp = angular.module('acceptanceTests', ['ui.router', 'ngAnimate', 'ui.bootstrap', 'ngStorage', 'ngSanitize', 'ddsCommon']);

ddsApp.config(function($locationProvider, $stateProvider, $urlRouterProvider) {
    moment.lang('fr');

    $locationProvider.html5Mode(true);
    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('index', {
            url: '/?testId',
            templateUrl: '/acceptance-tests/partials/index.html',
            controller: 'IndexCtrl',
            resolve: {
                acceptanceTests: ['$http', function($http) {
                    return $http.get('/api/acceptance-tests').then(function(result) {
                        return result.data;
                    });
                }]
            }
        })
        .state('login', {
            url: '/login',
            templateUrl: '/acceptance-tests/partials/login.html',
            controller: 'LoginCtrl',
            anonymous: true,
            onEnter: ['$state', 'UserService', function($state, UserService) {
                if (UserService.user()) {
                    $state.go('index');
                }
            }]
        })
        .state('new', {
            url: '/new/:situationId',
            templateUrl: '/acceptance-tests/partials/form.html',
            controller: 'FormCtrl',
            resolve: {
                droitsObtenus: ['$http', '$stateParams', function($http, $stateParams) {
                    return $http.get('/api/situations/' + $stateParams.situationId + '/simulation').then(function(result) {
                        return result.data;
                    });
                }],
                test: function() {
                    return null;
                }
            }
        })
        .state('edit', {
            url: '/:testId/edit',
            templateUrl: '/acceptance-tests/partials/form.html',
            controller: 'FormCtrl',
            resolve: {
                droitsObtenus: function() {
                    return null;
                },
                test: ['$http', '$stateParams', function($http, $stateParams) {
                    return $http.get('/api/acceptance-tests/' + $stateParams.testId).then(function(result) {
                        return result.data;
                    });
                }]
            }
        });
});

ddsApp.run(function($rootScope, $state, $stateParams, UserService) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

    UserService.retrieveUserAsync()
        .catch(function() {
            $state.go('login');
        })
        .finally(function() {
            $rootScope.$on('$stateChangeStart', function(e, state) {
                if (!UserService.user() && !state.anonymous) {
                    e.preventDefault();
                    $state.go('login');
                }
            });
            $rootScope.appReady = true;
        });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var exec = require('child_process').exec;

var dbPath = './db.json';
var pidPath = './vibes.pid';

// if pid exists then delete
if (fs.existsSync(pidPath)) {
  fs.unlinkSync(pidPath);
}

var Player = function() {

  var self = this;

  /**
   * Play
   * Create database list and play song from file
   */
  self.play = function() {
    if (fs.existsSync(pidPath)) {
      console.log('Ignore request');
    }
    else {
      var list = fs.readdirSync(process.env.LOCAL_DIRECTORY);

      var db = JSON.parse(fs.readFileSync(dbPath));

      // create database if empty
      if (db.length === 0) {
        if (list.length > 0) {
          var store = [];
          list.forEach(function(file) {
            store.push(file);
          });

          fs.writeFileSync(dbPath, JSON.stringify(store), 'utf8');
        }
        // reload database
        db = JSON.parse(fs.readFileSync(dbPath));
      }

      var selectedFile = db[Math.floor(Math.random()*db.length)];

      var index = db.indexOf(selectedFile);
      db.splice(index, 1);
      fs.writeFileSync(dbPath, JSON.stringify(db), 'utf8');

      var play = 'omxplayer ' + process.env.LOCAL_DIRECTORY + selectedFile;

      var child = exec(play, function(err, stdout, stderr) {
          if (err) throw err;
          console.log('Play: ' + selectedFile);
      });

      // save pid file
      fs.writeFileSync(pidPath, child.pid, 'utf8');

      // listener close
      child.on('close', function(code) {
          // remove pid file
          fs.unlinkSync(pidPath);

          // next file
          self.play();
      });
    }
  };

  /**
   * Stop
   * Stop player
   */
   self.stop = function() {
     if (fs.existsSync(pidPath)) {
       var command = 'ps -ef | grep omxplayer | grep -v grep | awk \'{print $2}\' | xargs kill -9';
       var child = exec(command, function(err, stdout, stderr) {
         if (err) throw err;
         console.log('Stopping...');
       });

       child.on('close', function(code) {
         console.log('Stoped ✓');
         fs.unlinkSync(pidPath);
       });
     }
     else {
       console.log(pidPath + 'don\'t exists.')
     }
   }

   /**
    * Next
    * Next file
    */
    self.next = function() {
      self.stop();
      self.play();
    }
};

module.exports = new Player();
<commit_msg>fix next<commit_after>var fs = require('fs');
var exec = require('child_process').exec;

var dbPath = './db.json';
var pidPath = './vibes.pid';

// if pid exists then delete
if (fs.existsSync(pidPath)) {
  fs.unlinkSync(pidPath);
}

var Player = function() {

  var self = this;

  /**
   * Play
   * Create database list and play song from file
   */
  self.play = function() {
    if (fs.existsSync(pidPath)) {
      console.log('Ignore request');
    }
    else {
      var list = fs.readdirSync(process.env.LOCAL_DIRECTORY);

      var db = JSON.parse(fs.readFileSync(dbPath));

      // create database if empty
      if (db.length === 0) {
        if (list.length > 0) {
          var store = [];
          list.forEach(function(file) {
            store.push(file);
          });

          fs.writeFileSync(dbPath, JSON.stringify(store), 'utf8');
        }
        // reload database
        db = JSON.parse(fs.readFileSync(dbPath));
      }

      var selectedFile = db[Math.floor(Math.random()*db.length)];

      var index = db.indexOf(selectedFile);
      db.splice(index, 1);
      fs.writeFileSync(dbPath, JSON.stringify(db), 'utf8');

      var play = 'omxplayer ' + process.env.LOCAL_DIRECTORY + selectedFile;

      var child = exec(play, function(err, stdout, stderr) {
          if (err) throw err;
          console.log('Play: ' + selectedFile);
      });

      // save pid file
      fs.writeFileSync(pidPath, child.pid, 'utf8');

      // listener close
      child.on('close', function(code) {
          // remove pid file
          fs.unlinkSync(pidPath);

          // next file
          self.play();
      });
    }
  };

  /**
   * Stop
   * Stop player
   */
   self.stop = function() {
     if (fs.existsSync(pidPath)) {
       var command = 'ps -ef | grep omxplayer | grep -v grep | awk \'{print $2}\' | xargs kill -9';
       var child = exec(command, function(err, stdout, stderr) {
         if (err) throw err;
         console.log('Stopping...');
       });

       child.on('close', function(code) {
         console.log('Stoped ✓');
         fs.unlinkSync(pidPath);

         if(arguments[0] === 'next') {
           self.play();
         }
       });
     }
     else {
       console.log(pidPath + 'don\'t exists.')
     }
   }

   /**
    * Next
    * Next file
    */
    self.next = function() {
      self.stop('next');
    }
};

module.exports = new Player();
<|endoftext|>


<commit_before>// Download the Node helper library from www.twilio.com/docs/libraries/node#installation
// These identifiers are your accountSid and authToken from
// https://www.twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

const bindingOpts = {
  endpoint: '00000001:sms',
  identity: '00000001', // We recommend using a GUID or other anonymized identifier for Identity.
  bindingType: 'sms',
  address: '+1651000000000',
};

client.notify
  .services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
  .bindings.create(bindingOpts)
  .then(binding => console.log(binding.sid))
  .catch(error => console.log(error))
  .done()
<commit_msg>CMS update of notifications/sms-quickstart/create-binding by kking@twilio.com<commit_after><|endoftext|>


<commit_before>window.onload = function () {

  // Create layer selector
  function createSelector(layer) {
    var condition = ""; // SQL or CartoCSS string
    var $options = $(".layer_selector").find("li");
    $options.click(function(e) {
      var $li = $(e.target);
      var selected = $li.attr('data');
      var type = $li.data('type'); // 'sql' or 'cartocss'

      if (type === "cartocss") { // if a CartoCSS selector is chosen, set the style
        $options.removeClass('cartocss_selected');
        if (selected !== "simple") {
          $li.addClass('cartocss_selected');
        }

        condition = $('#'+selected).text();
        layer.setCartoCSS(condition);
      } else { // if a SQL selector is chosen, re-query the data
        $options.removeClass('sql_selected');
        if (selected !== "") {
          $li.addClass('sql_selected');
        }

        layer.setSQL("SELECT * FROM " + tableName + selected);
      }
    });
  }

  // this is the table where the data lives
  var tableName = "powerplants_us_201603";

  // it is a public layer in mishmashmaps' account
  var layerSource = {
    user_name: 'mishmashmaps',
    type: 'cartodb',
    sublayers: [{
      sql: "SELECT * FROM " + tableName, // All power plants in dataset
      cartocss: $("#simple").text() // Simple visualization
    }]
  }

  // For storing the sublayer
  var sublayer;

  // Instantiate new map object, place it in 'map' element
  var map_object = new L.Map('map', {
    center: [42.6526,-73.7562], // Albany
    // center: [37.0902,-84.4437914], // U.S.
    zoom: 7
    // zoom: 5
  });

  // Set basemap as Dark Matter Lite
  L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/{dark_nolabels}/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
  }).addTo(map_object);

  // Add data layer to your map
  cartodb.createLayer(map_object,layerSource)
    .addTo(map_object)
    .done(function(layer) {
      sublayer = layer.getSubLayer(0);
      createSelector(sublayer);
    })
    .error(function(err) {
      console.log("error: " + err);
    });
}
<commit_msg>updated HTTPS dark matter no labels<commit_after>window.onload = function () {

  // Create layer selector
  function createSelector(layer) {
    var condition = ""; // SQL or CartoCSS string
    var $options = $(".layer_selector").find("li");
    $options.click(function(e) {
      var $li = $(e.target);
      var selected = $li.attr('data');
      var type = $li.data('type'); // 'sql' or 'cartocss'

      if (type === "cartocss") { // if a CartoCSS selector is chosen, set the style
        $options.removeClass('cartocss_selected');
        if (selected !== "simple") {
          $li.addClass('cartocss_selected');
        }

        condition = $('#'+selected).text();
        layer.setCartoCSS(condition);
      } else { // if a SQL selector is chosen, re-query the data
        $options.removeClass('sql_selected');
        if (selected !== "") {
          $li.addClass('sql_selected');
        }

        layer.setSQL("SELECT * FROM " + tableName + selected);
      }
    });
  }

  // this is the table where the data lives
  var tableName = "powerplants_us_201603";

  // it is a public layer in mishmashmaps' account
  var layerSource = {
    user_name: 'mishmashmaps',
    type: 'cartodb',
    sublayers: [{
      sql: "SELECT * FROM " + tableName, // All power plants in dataset
      cartocss: $("#simple").text() // Simple visualization
    }]
  }

  // For storing the sublayer
  var sublayer;

  // Instantiate new map object, place it in 'map' element
  var map_object = new L.Map('map', {
    center: [42.6526,-73.7562], // Albany
    // center: [37.0902,-84.4437914], // U.S.
    zoom: 7
    // zoom: 5
  });

  // Set basemap as Dark Matter Lite
  L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_nolabels/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
  }).addTo(map_object);

  // Add data layer to your map
  cartodb.createLayer(map_object,layerSource)
    .addTo(map_object)
    .done(function(layer) {
      sublayer = layer.getSubLayer(0);
      createSelector(sublayer);
    })
    .error(function(err) {
      console.log("error: " + err);
    });
}
<|endoftext|>


<commit_before>$(window).on('entity:map', function (e, data) {

    var map = data.map;
    var loaded_site = false;
    // Show outdoor layers in application maps
    $.each(['site'], function (i, modelname) {
        var layer = new L.ObjectsLayer(null, {
            modelname: modelname,
            style: L.Util.extend(window.SETTINGS.map.styles[modelname] || {}, {clickable:false}),
        });
        if (data.modelname != modelname) {
            map.layerscontrol.addOverlay(layer, tr(modelname), tr('Outdoor'));
        };
        map.on('layeradd', function(e) {
            var options = e.layer.options || {'modelname': 'None'};
            if (! loaded_site) {
                if (options.modelname == 'site' && options.modelname != data.modelname) {
                    e.layer.load(window.SETTINGS.urls.site_layer);
                    loaded_site = true;
                }
            }
    	});
    });
});

$(window).on('entity:view:add entity:view:update', function (e, data) {
    if (data.modelname != 'site')
        return;

    // Refresh types by practice
    $('#id_practice').change(function() {
        update_site_types();
    });
    $('#id_practice').trigger('change');
});

function update_site_types() {
    var practices = JSON.parse($('#practices-types').text());
    var practice = $('#id_practice').val();
    var $select = $('#id_type');
    var selected = $select.val() || [];

    var types = practice ? practices[practice]['types'] : {};

    // Hide type field if no values for this practice
    $('#div_id_type').toggle(Object.keys(types).length > 0);

    // Refresh options list for types, depending on practice
    $select.empty();
    $('<option/>')
        .text('---------')
        .attr('value', '')
        .appendTo($select);
    for(var type_id in types) {
        var type_name = types[type_id];
        $('<option/>')
            .text(type_name)
            .attr('value', type_id)
            .prop('selected', selected.indexOf(type_id) >= 0)
            .appendTo($select);
    }
    $select.trigger('chosen:updated');
}
<commit_msg>Add course layer to layers control<commit_after>$(window).on('entity:map', function (e, data) {

    var map = data.map;
    var loaded_site = false;
    var loaded_course = false;
    // Show outdoor layers in application maps
    $.each(['site', 'course'], function (i, modelname) {
        var layer = new L.ObjectsLayer(null, {
            modelname: modelname,
            style: L.Util.extend(window.SETTINGS.map.styles[modelname] || {}, {clickable:false}),
        });
        if (data.modelname != modelname) {
            map.layerscontrol.addOverlay(layer, tr(modelname), tr('Outdoor'));
        };
        map.on('layeradd', function(e) {
            var options = e.layer.options || {'modelname': 'None'};
            if (! loaded_site) {
                if (options.modelname == 'site' && options.modelname != data.modelname) {
                    e.layer.load(window.SETTINGS.urls.site_layer);
                    loaded_site = true;
                }
            }
            if (! loaded_course) {
                if (options.modelname == 'course' && options.modelname != data.modelname) {
                    e.layer.load(window.SETTINGS.urls.course_layer);
                    loaded_course = true;
                }
            }
    	});
    });
});

$(window).on('entity:view:add entity:view:update', function (e, data) {
    if (data.modelname != 'site')
        return;

    // Refresh types by practice
    $('#id_practice').change(function() {
        update_site_types();
    });
    $('#id_practice').trigger('change');
});

function update_site_types() {
    var practices = JSON.parse($('#practices-types').text());
    var practice = $('#id_practice').val();
    var $select = $('#id_type');
    var selected = $select.val() || [];

    var types = practice ? practices[practice]['types'] : {};

    // Hide type field if no values for this practice
    $('#div_id_type').toggle(Object.keys(types).length > 0);

    // Refresh options list for types, depending on practice
    $select.empty();
    $('<option/>')
        .text('---------')
        .attr('value', '')
        .appendTo($select);
    for(var type_id in types) {
        var type_name = types[type_id];
        $('<option/>')
            .text(type_name)
            .attr('value', type_id)
            .prop('selected', selected.indexOf(type_id) >= 0)
            .appendTo($select);
    }
    $select.trigger('chosen:updated');
}
<|endoftext|>


<commit_before>/* vim: set et sw=2 ts=2: */
/* jshint node: true */
"use strict";

var thresholds = {
  statements: 99,
    branches: 98,
   functions: 100,
       lines: 99
};

var jshint = require('gulp-jshint'),
     mocha = require('gulp-mocha'),
   ghPages = require('gulp-gh-pages'),
  mustache = require('gulp-mustache'),
preprocess = require('gulp-preprocess'),
sourcemaps = require('gulp-sourcemaps'),
  markdown = require('gulp-markdown'),
  istanbul = require('gulp-istanbul'),
  enforcer = require('gulp-istanbul-enforcer'),
   replace = require('gulp-replace'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
     docco = require('gulp-docco'),
      less = require('gulp-less'),
     chalk = require('chalk'),
      gzip = require('gulp-gzip'),
        fs = require('fs'),
    apidoc = require('./documentation.js'),
  filesize = require('filesize'),
      gulp = require('gulp');

var lessOptions = {
  plugins: [
//    require('less-plugin-autoprefix'),
//    require('less-plugin-clean-css')
  ]
};

var npmPackage = require('./package.json');

function errorHandler(err) {
  console.log(chalk.red(err.message));
  process.exit(1);
}

gulp.task('minify', [ 'lint' ], function (done) {
  gulp.src('nodash.js')
      .pipe(sourcemaps.init())
      .pipe(preprocess())
      .pipe(uglify({ compressor: { global_defs: { group: true } } }))
      .pipe(replace(",description(function(){})", ""))
      .pipe(replace(/(group\(('[^']*'|"[^"]*")(,function\(\)\{\})?\),?)/g, ""))
      .pipe(replace(/composed\(function\(\)\{return ([^}]+)\}\)/g, "$1"))
      .pipe(rename({ suffix: '.min' }))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('dist/'))
      .on('error', errorHandler)
      .on('finish', done);
});

gulp.task('gzip', [ 'minify' ], function (done) {
  gulp.src('dist/nodash.min.js')
      .pipe(gzip({ append: true, gzipOptions: { level: 9 } }))
      .pipe(gulp.dest('dist/'))
      .on('finish', done);
});

gulp.task('lint', function (done) {
  gulp.src([ 'nodash.js', 'test/*.js' ])
      .pipe(jshint())
      .pipe(jshint.reporter('default'))
      .pipe(jshint.reporter('fail'))
      .on('error', errorHandler)
      .on('finish', done);
});

gulp.task('coverage', [ 'lint' ], function (done) {
  gulp.src('nodash.js')
      .pipe(istanbul())
      .pipe(istanbul.hookRequire())
      .on('error', errorHandler)
      .on('finish', function () {
        gulp.src('test/*.js')
            .pipe(mocha())
            .pipe(istanbul.writeReports({ dir: 'dist/coverage/' }))
            .on('finish', done);
    });
});

// test library as is
gulp.task('test', [ 'coverage' ], function (done) {
  gulp.src('.')
      .pipe(enforcer({
        thresholds: thresholds,
        coverageDirectory: 'dist/coverage/',
        rootDirectory: ''
      }))
      .on('error', errorHandler)
      .on('finish', done);
});

// test minified library
gulp.task('testm', [ 'test', 'minify' ], function (done) {
  gulp.src('test/*.js')
      .pipe(replace('../nodash', '../dist/nodash.min'))
      .pipe(gulp.dest('testm/'))
      .on('finish', function () {
        gulp.src('testm/*.js')
            .pipe(mocha())
            .on('error', errorHandler)
            .once('end', done);
      });
});

gulp.task('docco', [ 'lint' ], function (done) {
  gulp.src('nodash.js')
      .pipe(docco())
      .pipe(gulp.dest('dist/docco/'))
      .on('finish', done);
});

gulp.task('styles', function (done) {
  gulp.src('site/*.less')
      .pipe(less(lessOptions))
      .pipe(gulp.dest('dist/'))
      .on('finish', done);
});

gulp.task('apidoc', [ 'styles', 'lint' ], function (done) {
  var library = require('./nodash.js');

  gulp.src('site/apidoc.mustache')
      .pipe(mustache(apidoc(library.metadata)))
      .pipe(rename({ extname: ".html" }))
      .pipe(gulp.dest('dist/'))
      .on('finish', done);
});

gulp.task('site', [ 'build', 'docco', 'apidoc' ], function (done) {
  gulp.src('README.md')
      .pipe(markdown({ }))
      .pipe(gulp.dest('dist/'))
      .on('finish', function () {
        var variables = {
          MINIFIED_SIZE: filesize(fs.statSync('dist/nodash.min.js').size),
          GZIPPED_SIZE: filesize(fs.statSync('dist/nodash.min.js.gz').size),
          VERSION: npmPackage.version,
          TODAY: new Date().toISOString().substring(0, 10)
        };

        gulp.src('site/index.html')
            .pipe(preprocess({ context: variables }))
            .pipe(gulp.dest('dist/'))
            .on('finish', done);
      });
});

gulp.task('deploy', [ 'site' ], function () {
  return gulp.src('./dist/**/*')
      .pipe(ghPages({ }));
});

gulp.task('build', [ 'minify', 'testm', 'gzip' ]);

gulp.task('default', [ 'site', ], function (done) {

  var minified = filesize(fs.statSync('dist/nodash.min.js').size);

  console.log(chalk.white((function(){/*
  CHECKMARK Your library has been built, Sir!

  You can find the minified version in the dist/ folder
  (there's also some documentation in that folder).
  It passed all test cases and achieved a good code coverage.
  In total it is a whopping MINIFIED minified. Note that the
  minified version has also been dragged through all the test
  cases and passed without a doubt.
  */}).toString()
      .slice(14, -3)
      .replace("CHECKMARK", chalk.green("✓"))
      .replace("MINIFIED", chalk.yellow(minified))
  ));

});

<commit_msg>Build several files for site target<commit_after>/* vim: set et sw=2 ts=2: */
/* jshint node: true */
"use strict";

var thresholds = {
  statements: 99,
    branches: 98,
   functions: 100,
       lines: 99
};

var jshint = require('gulp-jshint'),
     mocha = require('gulp-mocha'),
   ghPages = require('gulp-gh-pages'),
  mustache = require('gulp-mustache'),
preprocess = require('gulp-preprocess'),
sourcemaps = require('gulp-sourcemaps'),
  markdown = require('gulp-markdown'),
  istanbul = require('gulp-istanbul'),
  enforcer = require('gulp-istanbul-enforcer'),
   replace = require('gulp-replace'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
     docco = require('gulp-docco'),
      less = require('gulp-less'),
     chalk = require('chalk'),
      gzip = require('gulp-gzip'),
        fs = require('fs'),
    apidoc = require('./documentation.js'),
  filesize = require('filesize'),
      gulp = require('gulp');

var lessOptions = {
  plugins: [
//    require('less-plugin-autoprefix'),
//    require('less-plugin-clean-css')
  ]
};

var npmPackage = require('./package.json');

function errorHandler(err) {
  console.log(chalk.red(err.message));
  process.exit(1);
}

gulp.task('minify', [ 'lint' ], function (done) {
  gulp.src('nodash.js')
      .pipe(sourcemaps.init())
      .pipe(preprocess())
      .pipe(uglify({ compressor: { global_defs: { group: true } } }))
      .pipe(replace(",description(function(){})", ""))
      .pipe(replace(/(group\(('[^']*'|"[^"]*")(,function\(\)\{\})?\),?)/g, ""))
      .pipe(replace(/composed\(function\(\)\{return ([^}]+)\}\)/g, "$1"))
      .pipe(rename({ suffix: '.min' }))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('dist/'))
      .on('error', errorHandler)
      .on('finish', done);
});

gulp.task('gzip', [ 'minify' ], function (done) {
  gulp.src('dist/nodash.min.js')
      .pipe(gzip({ append: true, gzipOptions: { level: 9 } }))
      .pipe(gulp.dest('dist/'))
      .on('finish', done);
});

gulp.task('lint', function (done) {
  gulp.src([ 'nodash.js', 'test/*.js' ])
      .pipe(jshint())
      .pipe(jshint.reporter('default'))
      .pipe(jshint.reporter('fail'))
      .on('error', errorHandler)
      .on('finish', done);
});

gulp.task('coverage', [ 'lint' ], function (done) {
  gulp.src('nodash.js')
      .pipe(istanbul())
      .pipe(istanbul.hookRequire())
      .on('error', errorHandler)
      .on('finish', function () {
        gulp.src('test/*.js')
            .pipe(mocha())
            .pipe(istanbul.writeReports({ dir: 'dist/coverage/' }))
            .on('finish', done);
    });
});

// test library as is
gulp.task('test', [ 'coverage' ], function (done) {
  gulp.src('.')
      .pipe(enforcer({
        thresholds: thresholds,
        coverageDirectory: 'dist/coverage/',
        rootDirectory: ''
      }))
      .on('error', errorHandler)
      .on('finish', done);
});

// test minified library
gulp.task('testm', [ 'test', 'minify' ], function (done) {
  gulp.src('test/*.js')
      .pipe(replace('../nodash', '../dist/nodash.min'))
      .pipe(gulp.dest('testm/'))
      .on('finish', function () {
        gulp.src('testm/*.js')
            .pipe(mocha())
            .on('error', errorHandler)
            .once('end', done);
      });
});

gulp.task('docco', [ 'lint' ], function (done) {
  gulp.src('nodash.js')
      .pipe(docco())
      .pipe(gulp.dest('dist/docco/'))
      .on('finish', done);
});

gulp.task('styles', function (done) {
  gulp.src('site/*.less')
      .pipe(less(lessOptions))
      .pipe(gulp.dest('dist/'))
      .on('finish', done);
});

gulp.task('apidoc', [ 'styles', 'lint' ], function (done) {
  var library = require('./nodash.js');

  gulp.src('site/apidoc.mustache')
      .pipe(mustache(apidoc(library.metadata)))
      .pipe(rename({ extname: ".html" }))
      .pipe(gulp.dest('dist/'))
      .on('finish', done);
});

gulp.task('site', [ 'build', 'docco', 'apidoc' ], function (done) {
  gulp.src('README.md')
      .pipe(markdown({ }))
      .pipe(gulp.dest('dist/'))
      .on('finish', function () {
        var variables = {
          MINIFIED_SIZE: filesize(fs.statSync('dist/nodash.min.js').size),
          GZIPPED_SIZE: filesize(fs.statSync('dist/nodash.min.js.gz').size),
          VERSION: npmPackage.version,
          TODAY: new Date().toISOString().substring(0, 10)
        };

        gulp.src('site/*.html')
            .pipe(preprocess({ context: variables }))
            .pipe(gulp.dest('dist/'))
            .on('finish', done);
      });
});

gulp.task('deploy', [ 'site' ], function () {
  return gulp.src('./dist/**/*')
      .pipe(ghPages({ }));
});

gulp.task('build', [ 'minify', 'testm', 'gzip' ]);

gulp.task('default', [ 'site', ], function (done) {

  var minified = filesize(fs.statSync('dist/nodash.min.js').size);

  console.log(chalk.white((function(){/*
  CHECKMARK Your library has been built, Sir!

  You can find the minified version in the dist/ folder
  (there's also some documentation in that folder).
  It passed all test cases and achieved a good code coverage.
  In total it is a whopping MINIFIED minified. Note that the
  minified version has also been dragged through all the test
  cases and passed without a doubt.
  */}).toString()
      .slice(14, -3)
      .replace("CHECKMARK", chalk.green("✓"))
      .replace("MINIFIED", chalk.yellow(minified))
  ));

});

<|endoftext|>


<commit_before>import Link from 'next/link';
import { Component } from 'react';
import PropTypes from 'prop-types';
import Router from 'next/router';
import pluralize from 'pluralize';

export default class Nav extends Component {
  static propTypes = {
    items: PropTypes.arrayOf(PropTypes.shape({
      name: PropTypes.any.isRequired,
      href: PropTypes.any.isRequired,
    })),
    model: PropTypes.string,
  }

  static defaultProps = {
    items: [],
  }

  constructor() {
    super();

    this.state = {
      pathname: '',
    };
  }

  componentDidMount() {
    const pathname = Router.pathname.toLowerCase();
    this.setState({ pathname });
  }

  render() {
    const { items } = this.props;

    return (

        <Link as="/" href="/Index">
          Home
        </Link>
        <Link as="/about" href="/About">
          About
        </Link>

          {items.map((item, key) => {
            return (
              <Link key= { key } as={`/${pluralize(item.name, 1)}`} href= {{ pathname: item.href, query: item.query}}>

                  {item.name}

              </Link> );
          })}

    );
  }

  linkClassNames(item) {
    const classes = ['nav-link'];
    const pathname = this.state.pathname;

    if (item.href === '/View' && item.query) {
      if (item.query.model === this.props.model) classes.push('active');
      return classes.join(' ');
    }

    if ( pathname.match(item.href) ) classes.push('active');
    return classes.join(' ');
  }
}
<commit_msg>minor fix after rebase<commit_after>import Link from 'next/link';
import { Component } from 'react';
import PropTypes from 'prop-types';
import Router from 'next/router';
import pluralize from 'pluralize';

export default class Nav extends Component {
  static propTypes = {
    items: PropTypes.arrayOf(PropTypes.shape({
      name: PropTypes.any.isRequired,
      href: PropTypes.any.isRequired,
    })),
    model: PropTypes.string,
  }

  static defaultProps = {
    items: [],
  }

  constructor() {
    super();

    this.state = {
      pathname: '',
    };
  }

  componentDidMount() {
    const pathname = Router.pathname.toLowerCase();
    this.setState({ pathname });
  }

  render() {
    const { items } = this.props;

    return (

        <Link as="/" href="/Index">
          Home
        </Link>
        <Link as="/about" href="/about">
          About
        </Link>

          {items.map((item, key) => {
            return (
              <Link key= { key } as={`/${pluralize(item.name, 1)}`} href= {{ pathname: item.href, query: item.query}}>

                  {item.name}

              </Link> );
          })}

    );
  }

  linkClassNames(item) {
    const classes = ['nav-link'];
    const pathname = this.state.pathname;

    if (item.href === '/View' && item.query) {
      if (item.query.model === this.props.model) classes.push('active');
      return classes.join(' ');
    }

    if ( pathname.match(item.href) ) classes.push('active');
    return classes.join(' ');
  }
}
<|endoftext|>


<commit_before>define(['app', 'providers/routes/extended-route-provider'], function(app) { 'use strict';

  app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

      $locationProvider.html5Mode(true);
      $locationProvider.hashPrefix('!');

      $routeProvider
        .when('/printsmart/printshop',       {templateUrl: '/app/views/print-smart/printshop.html',  resolveController: true })

        .when('/mop7/insession',  {
            templateUrl : '/app/views/meetings/documents/in-session.html',
            resolveController : true,
            progress  : { stop : false },
            title     : "BS COP-MOP 7 In-session Documents",
            intro     : "The documents below are in session documents made available for the convenience of the participants. They do not represent final decisions.",
            documents : {
                plenary       : { title : "Plenary",                           url : "/doc/no-cache/mop7/insession/plenary.json" },
                wg1           : { title : "Working Group I",                   url : "/doc/no-cache/mop7/insession/wg1.json" },
                wg2           : { title : "Working Group II",                  url : "/doc/no-cache/mop7/insession/wg2.json" },
                other         : { title : "Other",                             url : "/doc/no-cache/mop7/insession/other.json" },
                presentations : { title : "Special Session on Implementation", url : "/doc/no-cache/mop7/insession/presentations.json" }
            }
        }).when('/npmop1/insession',  {
            templateUrl : '/app/views/meetings/documents/in-session.html',
            resolveController : true,
            progress  : { stop : false },
            title     : "NP COP-MOP 1 In In-session Documents",
            intro     : "The documents below are in session documents made available for the convenience of the participants. They do not represent final decisions.",
            documents : {
                plenary       : { title : "Plenary",          url : "/doc/no-cache/mop7/npmop1/plenary.json" },
                wg1           : { title : "Working Group I",  url : "/doc/no-cache/mop7/npmop1/wg1.json" },
                wg2           : { title : "Working Group II", url : "/doc/no-cache/mop7/npmop1/wg2.json" },
                other         : { title : "Other",            url : "/doc/no-cache/mop7/npmop1/other.json" }
            }
        }).when('/cop12/insession',  {
            templateUrl : '/app/views/meetings/documents/in-session.html',
            resolveController : true,
            progress  : { stop : false },
            title     : "COP 12 In-Session Documents",
            intro     : "The documents below are in session documents made available for the convenience of the participants. They do not represent final decisions.",
            documents : {
                plenary       : { title : "Plenary",          url : "/doc/no-cache/cop12/insession/plenary.json" },
                wg1           : { title : "Working Group I",  url : "/doc/no-cache/cop12/insession/wg1.json" },
                wg2           : { title : "Working Group II", url : "/doc/no-cache/cop12/insession/wg2.json" },
                other         : { title : "Other",            url : "/doc/no-cache/cop12/insession/other.json" }
            }
        }).when('/cop12/hls/insession',  {
            templateUrl : '/app/views/meetings/documents/in-session.html',
            resolveController : true,
            progress  : { stop : false },
            title     : "High Level Segment of COP 12",
            intro     : "The CBD Secretariat is making the following documents available on behalf of the Government of the Republic of Korea.",
            documents : {
                plenary     : { title : "HLS Documents",                                                                          open : true, url : "/doc/no-cache/cop12/insession/hls/plenary.json" },
                initiatives : { title : "COP 12 Information documents on Initiatives of the Government of the Republic of Korea", open : true, url : "/doc/no-cache/cop12/insession/hls/initiatives.json" }
            }
        })

        .when('/404', {templateUrl: '/app/views/404.html', resolveUser: true })
        .otherwise({redirectTo: '/404'});
    }
  ]);
});
<commit_msg>Renamed route<commit_after>define(['app', 'providers/routes/extended-route-provider'], function(app) { 'use strict';

  app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

      $locationProvider.html5Mode(true);
      $locationProvider.hashPrefix('!');

      $routeProvider
        .when('/printsmart/printshop',       {templateUrl: '/app/views/print-smart/printshop.html',  resolveController: true })

        .when('/mop7/insession',  {
            templateUrl : '/app/views/meetings/documents/in-session.html',
            resolveController : true,
            progress  : { stop : false },
            title     : "BS COP-MOP 7 In-session Documents",
            intro     : "The documents below are in session documents made available for the convenience of the participants. They do not represent final decisions.",
            documents : {
                plenary       : { title : "Plenary",                           url : "/doc/no-cache/mop7/insession/plenary.json" },
                wg1           : { title : "Working Group I",                   url : "/doc/no-cache/mop7/insession/wg1.json" },
                wg2           : { title : "Working Group II",                  url : "/doc/no-cache/mop7/insession/wg2.json" },
                other         : { title : "Other",                             url : "/doc/no-cache/mop7/insession/other.json" },
                presentations : { title : "Special Session on Implementation", url : "/doc/no-cache/mop7/insession/presentations.json" }
            }
        }).when('/npmop1/insession',  {
            templateUrl : '/app/views/meetings/documents/in-session.html',
            resolveController : true,
            progress  : { stop : false },
            title     : "NP COP-MOP 1 In In-session Documents",
            intro     : "The documents below are in session documents made available for the convenience of the participants. They do not represent final decisions.",
            documents : {
                plenary       : { title : "Plenary",          url : "/doc/no-cache/mop7/npmop1/plenary.json" },
                wg1           : { title : "Working Group I",  url : "/doc/no-cache/mop7/npmop1/wg1.json" },
                wg2           : { title : "Working Group II", url : "/doc/no-cache/mop7/npmop1/wg2.json" },
                other         : { title : "Other",            url : "/doc/no-cache/mop7/npmop1/other.json" }
            }
        }).when('/cop12/insession',  {
            templateUrl : '/app/views/meetings/documents/in-session.html',
            resolveController : true,
            progress  : { stop : false },
            title     : "COP 12 In-Session Documents",
            intro     : "The documents below are in session documents made available for the convenience of the participants. They do not represent final decisions.",
            documents : {
                plenary       : { title : "Plenary",          url : "/doc/no-cache/cop12/insession/plenary.json" },
                wg1           : { title : "Working Group I",  url : "/doc/no-cache/cop12/insession/wg1.json" },
                wg2           : { title : "Working Group II", url : "/doc/no-cache/cop12/insession/wg2.json" },
                other         : { title : "Other",            url : "/doc/no-cache/cop12/insession/other.json" }
            }
        }).when('/cop12/insession/hls',  {
            templateUrl : '/app/views/meetings/documents/in-session.html',
            resolveController : true,
            progress  : { stop : false },
            title     : "High Level Segment of COP 12",
            intro     : "The CBD Secretariat is making the following documents available on behalf of the Government of the Republic of Korea.",
            documents : {
                plenary     : { title : "HLS Documents",                                                                          open : true, url : "/doc/no-cache/cop12/insession/hls/plenary.json" },
                initiatives : { title : "COP 12 Information documents on Initiatives of the Government of the Republic of Korea", open : true, url : "/doc/no-cache/cop12/insession/hls/initiatives.json" }
            }
        })

        .when('/404', {templateUrl: '/app/views/404.html', resolveUser: true })
        .otherwise({redirectTo: '/404'});
    }
  ]);
});
<|endoftext|>


<commit_before>var util = require('./util');
var merge = require('object').merge;

module.exports = marker;

function marker(options) {
  var _gm = util.gm(), self;

  function add(map) {
    self._g.setMap(map._g);
    return self;
  }

  function remove() {
    self._g.setMap(null);
    return self;
  }

  function on(event, fn) {
    _gm.event.addListener(self._g, event, fn);
    return self;
  }

  self = {
    add: add,
    remove: remove,
    on: on
  };

  options = merge({
    flat: true,
    icon: {
      path: _gm.SymbolPath.CIRCLE,
      fillColor: options.color,
      fillOpacity: 1,
      strokeColor:  '#555555',
      strokeWeight: 2,
      scale: 7
    }
  }, options);
  if (options.map) {
    options.map = options.map._g;
  }
  if (options.position) {
    options.position = util.ll2gll(options.position);
  }

  self._g = new _gm.Marker(options);

  return self;
}
<commit_msg>add marker.animation<commit_after>var util = require('./util');
var merge = require('object').merge;

module.exports = marker;

function marker(options) {
  var _gm = util.gm(), self;

  function add(map) {
    self._g.setMap(map._g);
    return self;
  }

  function remove() {
    self._g.setMap(null);
    return self;
  }

  function animation(type) {
    var gtype = type && _gm.Animation[type.toUpperCase()];
    self._g.setAnimation(gtype);
    return self;
  }

  function on(event, fn) {
    _gm.event.addListener(self._g, event, fn);
    return self;
  }

  self = {
    animation: animation,
    add: add,
    remove: remove,
    on: on
  };

  options = merge({
    flat: true,
    icon: {
      path: _gm.SymbolPath.CIRCLE,
      fillColor: options.color,
      fillOpacity: 1,
      strokeColor:  '#555555',
      strokeWeight: 2,
      scale: 7
    }
  }, options);
  if (options.map) {
    options.map = options.map._g;
  }
  if (options.position) {
    options.position = util.ll2gll(options.position);
  }

  self._g = new _gm.Marker(options);

  return self;
}
<|endoftext|>


<commit_before>'use strict';
// generated on 2014-10-21 using generator-gulp-webapp 0.1.0

var gulp = require('gulp'),
exec = require('child_process').exec,
fs = require('fs');

// load plugins
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {
	return gulp.src('app/styles/main.scss')
		.pipe($.rubySass({
			style: 'expanded',
			precision: 10
		}))
		.pipe($.autoprefixer('last 2 versions'))
		.pipe(gulp.dest('.tmp/styles'))
		.pipe($.size());
});

gulp.task('scripts', function () {
	return gulp.src('app/scripts/**/*.js')
		.pipe($.jshint())
		.pipe($.jshint.reporter(require('jshint-stylish')))
		.pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
	var jsFilter = $.filter('**/*.js');
	var cssFilter = $.filter('**/*.css');

	return gulp.src('app/*.html')
		.pipe($.useref.assets({searchPath: '{.tmp,app}'}))
		.pipe(jsFilter)
		.pipe($.uglify())
		.pipe(jsFilter.restore())
		.pipe(cssFilter)
		.pipe($.csso())
		.pipe(cssFilter.restore())
		.pipe($.useref.restore())
		.pipe($.useref())
		.pipe(gulp.dest('dist'))
		.pipe($.size());
});

gulp.task('images', function () {
	return gulp.src('app/images/**/*')
		// .pipe($.cache($.imagemin({
		// 	optimizationLevel: 3,
		// 	progressive: true,
		// 	interlaced: true
		// })))
		.pipe(gulp.dest('dist/images'))
		.pipe($.size());
});

gulp.task('data', function (cb) {
	// Yes, this is quick and dirty.
	exec('node make/data.js', function (err, stdout, stderr) {
		console.log(stderr);
		cb(err);
	});
});

gulp.task('thumbnails', function (cb) {
	console.log('Generating thumbnails.');
	console.log('This task can take several minutes and is not designed to be run frequently.');
	exec('make/thumbnails.sh', function (err, stdout, stderr) {
		console.log(stderr);
		cb(err);
	});
});

gulp.task('pdf', function (cb) {
	console.log('Generating PDFs.');
	console.log('This task can take several minutes and is not designed to be run frequently.');
	exec('node make/pdf.js', function (err, stdout, stderr) {
		console.log(stderr);
		cb(err);
	});
});

gulp.task('copy-pdf', function () {
	return gulp.src('app/pdf/**/*')
		.pipe(gulp.dest('dist/pdf'))
		.pipe($.size());
});

gulp.task('copy-data', function () {
	return gulp.src('app/data/*')
		.pipe(gulp.dest('dist/data'))
		.pipe($.size());
});

gulp.task('fonts', function () {
	return gulp.src('app/fonts/**/*.{eot,svg,ttf,woff}')
		.pipe(gulp.dest('dist/fonts'))
		.pipe($.size());
});

gulp.task('extras', function () {
	return gulp.src(['app/*.*', '!app/*.html'], { dot: true })
		.pipe(gulp.dest('dist'));
});

gulp.task('clean', function () {
	return gulp.src(['.tmp', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('setup', ['data', 'thumbnails', 'pdf'])

gulp.task('build', ['html', 'images', 'copy-pdf', 'copy-data', 'fonts', 'extras']);

gulp.task('default', ['clean'], function () {
	gulp.start('build');
});

gulp.task('connect', function () {
	var connect = require('connect');
	var app = connect()
		.use(require('connect-livereload')({ port: 35729 }))
		.use(connect.static('app'))
		.use(connect.static('.tmp'))
		.use(connect.directory('app'));

	require('http').createServer(app)
		.listen(9000)
		.on('listening', function () {
			console.log('Started connect web server on http://localhost:9000');
		});
});

gulp.task('serve', ['connect', 'styles'], function () {
	require('opn')('http://localhost:9000', 'Google Chrome');
});

// inject bower components
gulp.task('wiredep', function () {
	var wiredep = require('wiredep').stream;

	gulp.src('app/styles/*.scss')
		.pipe(wiredep({
			directory: 'app/bower_components'
		}))
		.pipe(gulp.dest('app/styles'));

	gulp.src('app/*.html')
		.pipe(wiredep({
			directory: 'app/bower_components'
		}))
		.pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect', 'serve'], function () {
	var server = $.livereload();

	// watch for changes

	gulp.watch([
		'app/*.html',
		'.tmp/styles/**/*.css',
		'app/scripts/**/*.js',
		'app/images/**/*'
	]).on('change', function (file) {
		server.changed(file.path);
	});

	gulp.watch('app/styles/**/*.scss', ['styles']);
	gulp.watch('app/scripts/**/*.js', ['scripts']);
	gulp.watch('app/images/**/*', ['images']);
	gulp.watch('bower.json', ['wiredep']);
});
<commit_msg>Added information on EMFILE recovery to gulpfile<commit_after>'use strict';
// generated on 2014-10-21 using generator-gulp-webapp 0.1.0

var gulp = require('gulp'),
exec = require('child_process').exec,
fs = require('fs');

// load plugins
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {
	return gulp.src('app/styles/main.scss')
		.pipe($.rubySass({
			style: 'expanded',
			precision: 10
		}))
		.pipe($.autoprefixer('last 2 versions'))
		.pipe(gulp.dest('.tmp/styles'))
		.pipe($.size());
});

gulp.task('scripts', function () {
	return gulp.src('app/scripts/**/*.js')
		.pipe($.jshint())
		.pipe($.jshint.reporter(require('jshint-stylish')))
		.pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
	var jsFilter = $.filter('**/*.js');
	var cssFilter = $.filter('**/*.css');

	return gulp.src('app/*.html')
		.pipe($.useref.assets({searchPath: '{.tmp,app}'}))
		.pipe(jsFilter)
		.pipe($.uglify())
		.pipe(jsFilter.restore())
		.pipe(cssFilter)
		.pipe($.csso())
		.pipe(cssFilter.restore())
		.pipe($.useref.restore())
		.pipe($.useref())
		.pipe(gulp.dest('dist'))
		.pipe($.size());
});

gulp.task('images', function () {
	return gulp.src('app/images/**/*')
		// .pipe($.cache($.imagemin({
		// 	optimizationLevel: 3,
		// 	progressive: true,
		// 	interlaced: true
		// })))
		.pipe(gulp.dest('dist/images'))
		.pipe($.size());
});

gulp.task('data', function (cb) {
	// Yes, this is quick and dirty.
	exec('node make/data.js', function (err, stdout, stderr) {
		console.log(stderr);
		cb(err);
	});
});

gulp.task('thumbnails', function (cb) {
	console.log('Generating thumbnails.');
	console.log('This task can take several minutes and is not designed to be run frequently.');
	exec('make/thumbnails.sh', function (err, stdout, stderr) {
		console.log(stderr);
		cb(err);
	});
});

gulp.task('pdf', function (cb) {
	console.log('Generating PDFs.');
	var command = 'node make/pdf.js';
	console.log('This task can take several minutes and is not designed to be run frequently.');
	exec(command, function (err, stdout, stderr) {
		console.log(stderr);
		if (stderr.indexOf('EMFILE') !== -1) {
			console.log([
				"Crashed with 'too many files' error due to terribly inefficient file handling",
				"in pdfkit. Try increasing your system's limit or run the script manually",
				"in several smaller batches, like this:","",
				"    $ " + command + " 0-500",
				"    $ " + command + " 501-1000",
				"etc."
			].join("\n"))
		}
		cb(err);
	});
});

gulp.task('copy-pdf', function () {
	return gulp.src('app/pdf/**/*')
		.pipe(gulp.dest('dist/pdf'))
		.pipe($.size());
});

gulp.task('copy-data', function () {
	return gulp.src('app/data/*')
		.pipe(gulp.dest('dist/data'))
		.pipe($.size());
});

gulp.task('fonts', function () {
	return gulp.src('app/fonts/**/*.{eot,svg,ttf,woff}')
		.pipe(gulp.dest('dist/fonts'))
		.pipe($.size());
});

gulp.task('extras', function () {
	return gulp.src(['app/*.*', '!app/*.html'], { dot: true })
		.pipe(gulp.dest('dist'));
});

gulp.task('clean', function () {
	return gulp.src(['.tmp', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('setup', ['data', 'thumbnails', 'pdf'])

gulp.task('build', ['html', 'images', 'copy-pdf', 'copy-data', 'fonts', 'extras']);

gulp.task('default', ['clean'], function () {
	gulp.start('build');
});

gulp.task('connect', function () {
	var connect = require('connect');
	var app = connect()
		.use(require('connect-livereload')({ port: 35729 }))
		.use(connect.static('app'))
		.use(connect.static('.tmp'))
		.use(connect.directory('app'));

	require('http').createServer(app)
		.listen(9000)
		.on('listening', function () {
			console.log('Started connect web server on http://localhost:9000');
		});
});

gulp.task('serve', ['connect', 'styles'], function () {
	require('opn')('http://localhost:9000', 'Google Chrome');
});

// inject bower components
gulp.task('wiredep', function () {
	var wiredep = require('wiredep').stream;

	gulp.src('app/styles/*.scss')
		.pipe(wiredep({
			directory: 'app/bower_components'
		}))
		.pipe(gulp.dest('app/styles'));

	gulp.src('app/*.html')
		.pipe(wiredep({
			directory: 'app/bower_components'
		}))
		.pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect', 'serve'], function () {
	var server = $.livereload();

	// watch for changes

	gulp.watch([
		'app/*.html',
		'.tmp/styles/**/*.css',
		'app/scripts/**/*.js',
		'app/images/**/*'
	]).on('change', function (file) {
		server.changed(file.path);
	});

	gulp.watch('app/styles/**/*.scss', ['styles']);
	gulp.watch('app/scripts/**/*.js', ['scripts']);
	gulp.watch('app/images/**/*', ['images']);
	gulp.watch('bower.json', ['wiredep']);
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE.txt file for terms.
 */

/*jslint nomen:true, node:true */

'use strict';

var core = require('./core');

module.exports = {

    describe: {
        summary: 'Compile dust templates to yui modules',
        extensions: ['dust'],
        nameParser: core.name
    },

    fileUpdated: function (evt, api) {

        var self = this,
            file = evt.file,
            source_path = file.fullPath,
            bundleName = file.bundleName,
            templateName = this.describe.nameParser(source_path),
            moduleName = bundleName + '-templates-' + templateName,
            destination_path = moduleName + '.js';

        return api.promise(function (fulfill, reject) {

            var compiled,
                partials;

            try {
                partials = core.partials(source_path);
                compiled = core.compile(source_path, templateName);
            } catch (e) {
                reject(e);
            }

            // trying to write the destination file which will fulfill or reject the initial promise
            api.writeFileInBundle(bundleName, destination_path,
                self._wrapAsYUI(bundleName, templateName, moduleName, compiled, partials))
                .then(function () {
                    // provisioning the module to be used on the server side automatically
                    evt.bundle.useServerModules = evt.bundle.useServerModules || [];
                    evt.bundle.useServerModules.push(moduleName);
                    // we are now ready to roll
                    fulfill();
                }, reject);

        });
    },

    _wrapAsYUI: function (bundleName, templateName, moduleName, compiled, partials) {

        // base dependency
        var dependencies = ["template-dust"];

        // each partial should be provisioned thru another yui module
        // and the name of the partial should translate into a yui module
        // to become a dependency
        partials = partials || [];
        partials.forEach(function (name) {
            // adding prefix to each partial
            dependencies.push(bundleName + '-templates-' + name);
        });

        return [
            'YUI.add("' + moduleName + '",function(Y, NAME){',
            '   var dust = Y.config.global.dust,',
            '       cache = Y.Template._cache = Y.Template._cache || {},',
            '       partials = {};',
            '',
            compiled,
            '',
            '   Y.Array.each(' + JSON.stringify(partials) + ', function (name) {',
            '       if (cache["' + bundleName + '/' + '" + name]) {',
            '           partials[name] = cache["' + bundleName + '/' + '" + name];',
            '       }',
            '   });',
            '',
            '   cache["' + bundleName + '/' + templateName + '"] = function (data) {',
            '       var content;',
            '       dust.render("' + templateName + '", data, function (err, content) {',
            '           result = content;',
            '       });',
            '       return result; // hack to make dust sync',
            '   };',
            '}, "", {requires: ' + JSON.stringify(dependencies) + '});'
        ].join('\n');

    }

};<commit_msg>there is not need to provision partials for dust since they are driven by the registered templates under Dust, so dependencies for the yui module will be enough<commit_after>/*
 * Copyright (c) 2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE.txt file for terms.
 */

/*jslint nomen:true, node:true */

'use strict';

var core = require('./core');

module.exports = {

    describe: {
        summary: 'Compile dust templates to yui modules',
        extensions: ['dust'],
        nameParser: core.name
    },

    fileUpdated: function (evt, api) {

        var self = this,
            file = evt.file,
            source_path = file.fullPath,
            bundleName = file.bundleName,
            templateName = this.describe.nameParser(source_path),
            moduleName = bundleName + '-templates-' + templateName,
            destination_path = moduleName + '.js';

        return api.promise(function (fulfill, reject) {

            var compiled,
                partials;

            try {
                partials = core.partials(source_path);
                compiled = core.compile(source_path, templateName);
            } catch (e) {
                reject(e);
            }

            // trying to write the destination file which will fulfill or reject the initial promise
            api.writeFileInBundle(bundleName, destination_path,
                self._wrapAsYUI(bundleName, templateName, moduleName, compiled, partials))
                .then(function () {
                    // provisioning the module to be used on the server side automatically
                    evt.bundle.useServerModules = evt.bundle.useServerModules || [];
                    evt.bundle.useServerModules.push(moduleName);
                    // we are now ready to roll
                    fulfill();
                }, reject);

        });
    },

    _wrapAsYUI: function (bundleName, templateName, moduleName, compiled, partials) {

        // base dependency
        var dependencies = ["template-dust"];

        // each partial should be provisioned thru another yui module
        // and the name of the partial should translate into a yui module
        // to become a dependency
        partials = partials || [];
        partials.forEach(function (name) {
            // adding prefix to each partial
            dependencies.push(bundleName + '-templates-' + name);
        });

        return [
            'YUI.add("' + moduleName + '",function(Y, NAME){',
            '   var dust = Y.config.global.dust,',
            '       cache = Y.Template._cache = Y.Template._cache || {};',
            '',
            compiled,
            '',
            '   cache["' + bundleName + '/' + templateName + '"] = function (data) {',
            '       var content;',
            '       dust.render("' + templateName + '", data, function (err, content) {',
            '           result = content;',
            '       });',
            '       return result; // hack to make dust sync',
            '   };',
            '}, "", {requires: ' + JSON.stringify(dependencies) + '});'
        ].join('\n');

    }

};<|endoftext|>


<commit_before>'use strict';

$(function() {
    $('.content__inner').prepend($('<div>', { class : 'content__item--sizer' }));
    $('.content__inner').prepend($('<div>', { class : 'content__item--gutter-sizer' }));

    var $isotope;

    var callIsotope = function() {
        if ($isotope == null) {
            $isotope = $('.content__inner').isotope({
                itemSelector: '.content__item',
                percentPosition: true,
                masonry: {
                    columnWidth: '.content__item--sizer',
                    gutter: '.content__item--gutter-sizer'
                }
            });

            $isotope.imagesLoaded().progress(function() {
                $isotope.isotope('layout');
            }).then(function() {
                $isotope.isotope('layout');
                setTimeout(function() { $isotope.isotope('layout'); }, 500);
            });
        } else {
            $isotope.isotope('layout');
        }

        $('.content').css('height', $('.content_inner').outerHeight());
    };

    $('.content__item').removeClass('content__item--unfolded').addClass('content__item--folded');

    callIsotope();

    $('.content__item').each(function() {
        var $this = $(this);

        if ($this.find('.when-unfolded').length > 0) {
            var fold, bindUnfold;

            fold = function($this) {
                return function(e) {
                    if ($this.hasClass('content__item--unfolded')) {
                        $this.removeClass('content__item--unfolded content__item--double')
                             .addClass('content__item--folded');

                        setTimeout(function() {
                            bindUnfold($this);
                        }, 100);

                        if (e != null) {
                            callIsotope();
                        }
                    }
                };
            };

            bindUnfold = function($this) {
                $this.css('cursor', 'pointer');

                $this.on('click.unfold', function() {
                    $this.css('cursor', '');

                    $this.off('click.unfold');

                    // Close everything else
                    $('.content__item').each(function() {
                        fold($(this))();
                    });

                    $this.removeClass('content__item--folded')
                         .addClass('content__item--unfolded content__item--double');

                    callIsotope();
                });
            };

            bindUnfold($this);
            $this.find('.when-unfolded .fa-remove').on('click.fold', fold($this));
        }

        // Handle iframes
        if ($this.hasClass('content__item--has-iframe')) {
            var iframeInserted = function($iframe) {
                $iframe.removeAttr('width');
                $iframe.removeAttr('height');
                $iframe.on('load', function() {
                    $this.css('display', 'block');

                    var width = '100%';
                    if ($iframe.parents('.content__item--has-iframe__wrapper').length > 0) {
                        width = 'calc(100% + 16px)';
                    }
                    $iframe.css('width', width);

                    var height = $iframe.innerWidth();
                    if ($iframe.parent().hasClass('s16x9')) {
                        height = (height / 16) * 9;
                    }
                    $iframe.css('min-height', height);

                    $iframe.parents('.content__item--has-iframe__wrapper')
                        .css('height', $this.innerWidth());
                    callIsotope();
                });
            };

            var $iframe = $this.find('iframe');
            if ($iframe.length > 0) {
                iframeInserted($iframe);
            } else {
                if (MutationObserver != null) {
                    var observer = new MutationObserver(function(mutations) {
                        _.each(mutations, function(mutation) {
                            _.each(mutation.addedNodes, function(newNode) {
                                if (newNode.tagName === 'IFRAME') {
                                    iframeInserted($(newNode));
                                    observer.disconnect();
                                }
                            });
                        });
                    });
                    observer.observe($this.find('.content__item--has-iframe__wrapper')[0], {
                        childList : true
                    });
                } else {
                    $this.on('DOMNodeInserted.paulloz', function(ev) {
                        if (ev.target.tagName === 'IFRAME') {
                            iframeInserted($(ev.target));
                            $this.off('DOMNodeInserted.paulloz');
                        }
                    });
                }
            }
        }
    });

    // Resize iframe wrappers on window resize
    $(window).on('resize', _.debounce(function() {
        $('.content__item--has-iframe').each(function() {
            var $this = $(this),
                height = $(this).innerWidth();
            if ($this.hasClass('s16x9')) {
                height = (height / 16) * 9;
            }
            $this.find('iframe').css('min-height', height);
            $this.find('.content__item--has-iframe__wrapper').css('height', $this.innerWidth());
        });

        callIsotope(true);
    }, 200));
});
<commit_msg>can link to an open item<commit_after>'use strict';

$(function() {
    $('.content__inner').prepend($('<div>', { class : 'content__item--sizer' }));
    $('.content__inner').prepend($('<div>', { class : 'content__item--gutter-sizer' }));

    var $isotope;

    var callIsotope = function() {
        if ($isotope == null) {
            $isotope = $('.content__inner').isotope({
                itemSelector: '.content__item',
                percentPosition: true,
                masonry: {
                    columnWidth: '.content__item--sizer',
                    gutter: '.content__item--gutter-sizer'
                }
            });

            $isotope.imagesLoaded().progress(function() {
                $isotope.isotope('layout');
            }).then(function() {
                $isotope.isotope('layout');
                setTimeout(function() { $isotope.isotope('layout'); }, 500);
            });
        } else {
            $isotope.isotope('layout');
        }

        $('.content').css('height', $('.content_inner').outerHeight());
    };

    $('.content__item').removeClass('content__item--unfolded').addClass('content__item--folded');

    callIsotope();

    $('.content__item').each(function() {
        var $this = $(this);

        if ($this.find('.when-unfolded').length > 0) {
            var fold, bindUnfold;

            fold = function($this) {
                return function(e) {
                    if ($this.hasClass('content__item--unfolded')) {
                        history.pushState(null, null, '');
                        $this.removeClass('content__item--unfolded content__item--double')
                             .addClass('content__item--folded');

                        setTimeout(function() {
                            bindUnfold($this);
                        }, 100);

                        if (e != null) {
                            callIsotope();
                        }
                    }
                };
            };

            bindUnfold = function($this) {
                $this.css('cursor', 'pointer');

                $this.on('click.unfold', function() {
                    history.pushState(null, null, '#' + $this.attr('id') + 'o');

                    $this.css('cursor', '');

                    $this.off('click.unfold');

                    // Close everything else
                    $('.content__item').each(function() {
                        fold($(this))();
                    });

                    $this.removeClass('content__item--folded')
                         .addClass('content__item--unfolded content__item--double');

                    callIsotope();
                });
            };

            bindUnfold($this);
            $this.find('.when-unfolded .fa-remove').on('click.fold', fold($this));
        }

        // Handle iframes
        if ($this.hasClass('content__item--has-iframe')) {
            var iframeInserted = function($iframe) {
                $iframe.removeAttr('width');
                $iframe.removeAttr('height');
                $iframe.on('load', function() {
                    $this.css('display', 'block');

                    var width = '100%';
                    if ($iframe.parents('.content__item--has-iframe__wrapper').length > 0) {
                        width = 'calc(100% + 16px)';
                    }
                    $iframe.css('width', width);

                    var height = $iframe.innerWidth();
                    if ($iframe.parent().hasClass('s16x9')) {
                        height = (height / 16) * 9;
                    }
                    $iframe.css('min-height', height);

                    $iframe.parents('.content__item--has-iframe__wrapper')
                        .css('height', $this.innerWidth());
                    callIsotope();
                });
            };

            var $iframe = $this.find('iframe');
            if ($iframe.length > 0) {
                iframeInserted($iframe);
            } else {
                if (MutationObserver != null) {
                    var observer = new MutationObserver(function(mutations) {
                        _.each(mutations, function(mutation) {
                            _.each(mutation.addedNodes, function(newNode) {
                                if (newNode.tagName === 'IFRAME') {
                                    iframeInserted($(newNode));
                                    observer.disconnect();
                                }
                            });
                        });
                    });
                    observer.observe($this.find('.content__item--has-iframe__wrapper')[0], {
                        childList : true
                    });
                } else {
                    $this.on('DOMNodeInserted.paulloz', function(ev) {
                        if (ev.target.tagName === 'IFRAME') {
                            iframeInserted($(ev.target));
                            $this.off('DOMNodeInserted.paulloz');
                        }
                    });
                }
            }
        }
    });

    if (document.location.hash.length > 1) {
        var toUnfold = $(document.location.hash.replace(/o$/, ''));
        if (toUnfold.find('.when-unfolded').length > 0) {
            toUnfold.trigger('click.unfold');
        }
    }

    // Resize iframe wrappers on window resize
    $(window).on('resize', _.debounce(function() {
        $('.content__item--has-iframe').each(function() {
            var $this = $(this),
                height = $(this).innerWidth();
            if ($this.hasClass('s16x9')) {
                height = (height / 16) * 9;
            }
            $this.find('iframe').css('min-height', height);
            $this.find('.content__item--has-iframe__wrapper').css('height', $this.innerWidth());
        });

        callIsotope(true);
    }, 200));
});
<|endoftext|>


<commit_before>Cards.module('Set.Details', function(Details, App) {
	Details.NewCardView = Backbone.Marionette.ItemView.extend({
		template: "#set-details-newcard",
		events: {
			"click .btn-success": "saveCard",
			"click .btn.cancel": "cancel",
			"click .btn-pictureSearch": "pictureSearch",
			"keyup input": "keyupInput",
			"focus input": "focusInput"
		},
		ui: {
			saveBtn: ".btn-success",
			cancelBtn: ".btn.cancel",
			picSearchFrontbtn: "#set-details-newcard-btn-pic-front-seach",
			pictureSearchModal: "#pictureSearchModal"
		},
		cancel: function(ev) {
			history.back();
		},
		saveCard: function(ev) {
			this.ui.saveBtn.button('loading');

			var setId = this.model.get('id');
			var setName = this.model.get('name');

			var card = new Cards.Entities.Card({
				front: {
					text: $("#front-textarea").val(),
					text_plain: $("#front-textarea").val().replace(/(<([^>]+)>)/ig,""),
					picture: $("#set-details-newcard-input-pic-front-search").val() || null,
					video: null
				},
				back: {
					text: $("#back-textarea").val(),
					text_plain: $("#back-textarea").val().replace(/(<([^>]+)>)/ig,""),
					picture: $("#set-details-newcard-input-pic-back-search").val() || null,
					video: null
				},
				setId: setId
			});

			if(card.isValid()) {
				card.save({}, {
					success: function(model, response) {
						Cards.trigger("set:details", setId);
					},
					error: function(model, error) {
						this.ui.saveBtn.button('reset');
						alert("something went wrong");
					}
				});
			} else {
				alert('not valid');
				this.ui.saveBtn.button('reset');
			}
		},
		pictureSearch: function(ev) {
			ev.preventDefault();
			var that = this;

			var searchInput = $(ev.target).parent().prev();
			var searchString = searchInput.val();

			console.log("searching for", searchString);

			/*var loadSearch = function() {
				console.log("search loaded");
			}

			google.load('search', '1', {callback: loadSearch });
*/
			setTimeout(function(){
				var imageSearch = new google.search.ImageSearch();
				imageSearch.setResultSetSize(8);
				imageSearch.setNoHtmlGeneration();
				imageSearch.setRestriction(
				  google.search.Search.RESTRICT_SAFESEARCH,
				  google.search.Search.SAFESEARCH_STRICT
				);

				imageSearch.setSearchCompleteCallback(this, function(){
					console.log("results", imageSearch.results);
					if (imageSearch.results && imageSearch.results.length > 0) {

						var results = imageSearch.results;

						var table = $(document.createElement('table'));
						table.attr('id', 'google-imagesearch-result');
						var tbody = $(document.createElement('tbody'));

						table.append(tbody);
						$("#pictureSearchModal-body").empty();
						$("#pictureSearchModal-body").append(table);

						var tr;
						for(var i = 0; i < results.length; i++) {
							if(!(i % 2)) {
								tr = $(document.createElement('tr'));
							}

							var result = results[i];

							var td = $(document.createElement('td'));

							var imgElem = $(document.createElement('img'));
							imgElem.attr('src', result.tbUrl);
							imgElem.attr('height', result.tbHeight*1.5);
							imgElem.attr('width', result.tbWidth*1.5);
							imgElem.attr('title', result.title);
							imgElem.attr('alt', result.url);
							imgElem.addClass('img-polaroid');

							imgElem.bind('click', function(ev){
								searchInput.val($(ev.target).attr('alt'));
								that.ui.pictureSearchModal.modal('hide');
								$("#pictureSearchModal-body").empty();
							});
							td.append(imgElem);
							console.log(imgElem);
							tr.append(td);

							if(i % 2) {
								tbody.append(tr);
							}
						}
					} else {
						alert("no results");
						this.ui.pictureSearchModal.modal('hide');
					}
		        }, null);

		        imageSearch.execute(searchString);
		        $("#pictureSearchModal-footer").empty();
		        $("#pictureSearchModal-footer").append(google.search.Search.getBranding());

			}, 100);

			$("#pictureSearchModal-body").scrollTop();
			this.ui.pictureSearchModal.modal('show');

			this.ui.pictureSearchModal.on('hide', function() {
				$("#pictureSearchModal-body").empty();
			})
		},
		keyupInput: function(ev) {
			var value = $(ev.target).val();
		    var urlregex = new RegExp("^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
    		if (urlregex.test(value)) {
        		$(ev.target).next().attr('disabled', 'disabled');
    		} else {
    			$(ev.target).next().removeAttr('disabled');
    		}
		},
		focusInput: function(ev) {
			var loadSearch = function() {
				console.log("search loaded");
			}

			google.load('search', '1', {callback: loadSearch });
		},
		onShow: function() {
			var editorConfig = {
				"font-styles": false,
				"color": false,
				"lists": false,
				"image": false
			}

			$("#front-textarea").wysihtml5(editorConfig);
			$("#back-textarea").wysihtml5(editorConfig);
		}
	});
});<commit_msg>fix for newcard: back to correct view<commit_after>Cards.module('Set.Details', function(Details, App) {
	Details.NewCardView = Backbone.Marionette.ItemView.extend({
		template: "#set-details-newcard",
		events: {
			"click .btn-success": "saveCard",
			"click .btn.cancel": "cancel",
			"click .btn-pictureSearch": "pictureSearch",
			"keyup input": "keyupInput",
			"focus input": "focusInput"
		},
		ui: {
			saveBtn: ".btn-success",
			cancelBtn: ".btn.cancel",
			picSearchFrontbtn: "#set-details-newcard-btn-pic-front-seach",
			pictureSearchModal: "#pictureSearchModal"
		},
		cancel: function(ev) {
			history.back();
		},
		saveCard: function(ev) {
			this.ui.saveBtn.button('loading');

			var setId = this.model.get('id');
			var setName = this.model.get('name');

			var card = new Cards.Entities.Card({
				front: {
					text: $("#front-textarea").val(),
					text_plain: $("#front-textarea").val().replace(/(<([^>]+)>)/ig,""),
					picture: $("#set-details-newcard-input-pic-front-search").val() || null,
					video: null
				},
				back: {
					text: $("#back-textarea").val(),
					text_plain: $("#back-textarea").val().replace(/(<([^>]+)>)/ig,""),
					picture: $("#set-details-newcard-input-pic-back-search").val() || null,
					video: null
				},
				setId: setId
			});

			if(card.isValid()) {
				card.save({}, {
					success: function(model, response) {
						history.back();
					},
					error: function(model, error) {
						this.ui.saveBtn.button('reset');
						alert("something went wrong");
					}
				});
			} else {
				alert('not valid');
				this.ui.saveBtn.button('reset');
			}
		},
		pictureSearch: function(ev) {
			ev.preventDefault();
			var that = this;

			var searchInput = $(ev.target).parent().prev();
			var searchString = searchInput.val();

			console.log("searching for", searchString);

			/*var loadSearch = function() {
				console.log("search loaded");
			}

			google.load('search', '1', {callback: loadSearch });
*/
			setTimeout(function(){
				var imageSearch = new google.search.ImageSearch();
				imageSearch.setResultSetSize(8);
				imageSearch.setNoHtmlGeneration();
				imageSearch.setRestriction(
				  google.search.Search.RESTRICT_SAFESEARCH,
				  google.search.Search.SAFESEARCH_STRICT
				);

				imageSearch.setSearchCompleteCallback(this, function(){
					console.log("results", imageSearch.results);
					if (imageSearch.results && imageSearch.results.length > 0) {

						var results = imageSearch.results;

						var table = $(document.createElement('table'));
						table.attr('id', 'google-imagesearch-result');
						var tbody = $(document.createElement('tbody'));

						table.append(tbody);
						$("#pictureSearchModal-body").empty();
						$("#pictureSearchModal-body").append(table);

						var tr;
						for(var i = 0; i < results.length; i++) {
							if(!(i % 2)) {
								tr = $(document.createElement('tr'));
							}

							var result = results[i];

							var td = $(document.createElement('td'));

							var imgElem = $(document.createElement('img'));
							imgElem.attr('src', result.tbUrl);
							imgElem.attr('height', result.tbHeight*1.5);
							imgElem.attr('width', result.tbWidth*1.5);
							imgElem.attr('title', result.title);
							imgElem.attr('alt', result.url);
							imgElem.addClass('img-polaroid');

							imgElem.bind('click', function(ev){
								searchInput.val($(ev.target).attr('alt'));
								that.ui.pictureSearchModal.modal('hide');
								$("#pictureSearchModal-body").empty();
							});
							td.append(imgElem);
							console.log(imgElem);
							tr.append(td);

							if(i % 2) {
								tbody.append(tr);
							}
						}
					} else {
						alert("no results");
						this.ui.pictureSearchModal.modal('hide');
					}
		        }, null);

		        imageSearch.execute(searchString);
		        $("#pictureSearchModal-footer").empty();
		        $("#pictureSearchModal-footer").append(google.search.Search.getBranding());

			}, 100);

			$("#pictureSearchModal-body").scrollTop();
			this.ui.pictureSearchModal.modal('show');

			this.ui.pictureSearchModal.on('hide', function() {
				$("#pictureSearchModal-body").empty();
			})
		},
		keyupInput: function(ev) {
			var value = $(ev.target).val();
		    var urlregex = new RegExp("^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
    		if (urlregex.test(value)) {
        		$(ev.target).next().attr('disabled', 'disabled');
    		} else {
    			$(ev.target).next().removeAttr('disabled');
    		}
		},
		focusInput: function(ev) {
			var loadSearch = function() {
				console.log("search loaded");
			}

			google.load('search', '1', {callback: loadSearch });
		},
		onShow: function() {
			var editorConfig = {
				"font-styles": false,
				"color": false,
				"lists": false,
				"image": false
			}

			$("#front-textarea").wysihtml5(editorConfig);
			$("#back-textarea").wysihtml5(editorConfig);
		}
	});
});<|endoftext|>