<commit_before>/* jshint devel:true */
/* global saveAs, require, CodeMirror, alertify, cytoscape */

(function() {
  'use strict';

  var myCodeMirror = new CodeMirror(document.getElementById('editor'), {
    value: '{}',
    lineNumbers: true,
    mode: 'application/json',
    foldGutter: true,
    gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter', 'CodeMirror-lint-markers'],
    lint: {
      onUpdateLinting: function(annotations) {
        if (template && (!annotations || annotations.length === 0)) {
          template.refreshGraph();
          $('#embed_link').toggle(!template.hasChanged());
        }
      }
    }
  });
  myCodeMirror.setSize('100%', '800px');

  var graphArea = $('#graph_area');

  graphArea.css('background-image', 'url("images/aws-cloudformation-template.svg")');
  graphArea[0].addEventListener('dragover', function(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    evt.dataTransfer.dropEffect = 'copy';
  }, false);
  graphArea[0].addEventListener('drop', function(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    loadTemplate(template.fromFile, evt.dataTransfer.files[0]);
  }, false);

  var template = require('./template').template({
    'editor': {
      setValue: myCodeMirror.getDoc.setValue,
      getValue: myCodeMirror.getDoc.getValue
    },
    'cytolib': cytoscape,
    'graphContainer': graphArea[0],
    'jsonproxy': $.jsonp
  });
  $.ajax({
    url: 'styles/main.cycss',
    type: 'GET',
    dataType: 'text',
    success: function(responseText) {
      template.changeStyle(responseText);
    }
  });

  var isResizing = false,
    lastDownX = 0;

  var remoteInput = $('#remote_input');

  $('#remote_input').keypress(function(e) {
    if (e.which === 13) {
      loadTemplate(template.fromURL, getTemplateUrl());
      return false;
    }
  });

  var getTemplateUrl = function () {
    var url = remoteInput.val();
    if (remoteInput[0].checkValidity()){
      remoteInput.hide();
      return url;
    }
    return undefined;
  };

  var loadTemplate = function(loadFn, url) {
    if (!url) {
      return;
    }
    loadFn(
      url,
      function(templateLocation) {
        graphArea.css('background-image', '');
        if (typeof url === 'string') {
          if (remoteInput.val() !== url) {
            remoteInput.val(url);
          }
          var embedUrl = queryTools.createEmbedUrl(window.location, url);
          $('#embed_link').html('Use '+ embedUrl + ' to open directly');
        }
        else {
          $('#embed_link > a').remove();
        }
        alertify.success('Loaded template "' + templateLocation + '" successfully');
      },
      function(templateLocation, reason) {
        alertify.error('Unable to load template "' + templateLocation + '" because of ' + reason);
      }
    );
  };

  $('#open_template').click(function(event) {
    event.preventDefault();
    $('#template_input').click();
  });
  $('#template_input').change(function(event) {
    loadTemplate(template.fromFile, event.target.files[0]);
  });

  $('#open_url').click(function(event) {
    event.preventDefault();
    if (remoteInput.is(':visible')) {
      loadTemplate(template.fromURL, getTemplateUrl());
    }
    else {
      remoteInput.show();
    }
  });

  $('#save_template').click(function(event) {
    event.preventDefault();
    saveAs(
      new Blob( [template.text(2)], { type: 'text/plain;charset=utf-8' }),
      template.description() + '.json'
    );
    return false;
  });
  $('#save_graph').click(function(event) {
    event.preventDefault();
    var saveWindow = window.open('savegraph.html');
    saveWindow.onload = function() {
      saveWindow.document.getElementById('graphPNG').src = template.base64Image();
    };
    return false;
  });
  $('#graph_layout').change(function() {
    template.setLayout($('#graph_layout').val());
  });

  var container = $('#container'),
    editorPane = $('#editor_pane');

  $('#border').on('mousedown', function(e) {
    isResizing = true;
    lastDownX = e.clientX;
  });

  $(document).on('mousemove', function(e) {
    // we don't want to do anything if we aren't resizing.
    if (!isResizing) {
      return;
    }

    var offsetRight = container.width() - (e.clientX - container.offset().left);

    graphArea.css('right', offsetRight);
    editorPane.css('width', offsetRight);
  }).on('mouseup', function() {
    if (isResizing) {
      template.fitGraph();
    }
    // stop resizing
    isResizing = false;
  });
  var queryTools = require('./queryparser');
  $(document).ready(function() {
        //----- Parse Query -----//
  queryTools.parser(window.location.search,{
    onTemplate: function (url) {
      loadTemplate(template.fromURL, url);
    }
  });
  //----- Parse Query -----//
  });
})();
<commit_msg>Fixed editor wrapping object to forward setValue and getValue properly<commit_after>/* jshint devel:true */
/* global saveAs, require, CodeMirror, alertify, cytoscape */

(function() {
  'use strict';

  var myCodeMirror = new CodeMirror(document.getElementById('editor'), {
    value: '{}',
    lineNumbers: true,
    mode: 'application/json',
    foldGutter: true,
    gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter', 'CodeMirror-lint-markers'],
    lint: {
      onUpdateLinting: function(annotations) {
        if (template && (!annotations || annotations.length === 0)) {
          template.refreshGraph();
          $('#embed_link').toggle(!template.hasChanged());
        }
      }
    }
  });
  myCodeMirror.setSize('100%', '800px');

  var graphArea = $('#graph_area');

  graphArea.css('background-image', 'url("images/aws-cloudformation-template.svg")');
  graphArea[0].addEventListener('dragover', function(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    evt.dataTransfer.dropEffect = 'copy';
  }, false);
  graphArea[0].addEventListener('drop', function(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    loadTemplate(template.fromFile, evt.dataTransfer.files[0]);
  }, false);

  var template = require('./template').template({
    'editor': {
      setValue: function(value) { myCodeMirror.getDoc().setValue(value); },
      getValue: function() { return myCodeMirror.getDoc().getValue(); }
    },
    'cytolib': cytoscape,
    'graphContainer': graphArea[0],
    'jsonproxy': $.jsonp
  });
  $.ajax({
    url: 'styles/main.cycss',
    type: 'GET',
    dataType: 'text',
    success: function(responseText) {
      template.changeStyle(responseText);
    }
  });

  var isResizing = false,
    lastDownX = 0;

  var remoteInput = $('#remote_input');

  $('#remote_input').keypress(function(e) {
    if (e.which === 13) {
      loadTemplate(template.fromURL, getTemplateUrl());
      return false;
    }
  });

  var getTemplateUrl = function () {
    var url = remoteInput.val();
    if (remoteInput[0].checkValidity()){
      remoteInput.hide();
      return url;
    }
    return undefined;
  };

  var loadTemplate = function(loadFn, url) {
    if (!url) {
      return;
    }
    loadFn(
      url,
      function(templateLocation) {
        graphArea.css('background-image', '');
        if (typeof url === 'string') {
          if (remoteInput.val() !== url) {
            remoteInput.val(url);
          }
          var embedUrl = queryTools.createEmbedUrl(window.location, url);
          $('#embed_link').html('Use '+ embedUrl + ' to open directly');
        }
        else {
          $('#embed_link > a').remove();
        }
        alertify.success('Loaded template "' + templateLocation + '" successfully');
      },
      function(templateLocation, reason) {
        alertify.error('Unable to load template "' + templateLocation + '" because of ' + reason);
      }
    );
  };

  $('#open_template').click(function(event) {
    event.preventDefault();
    $('#template_input').click();
  });
  $('#template_input').change(function(event) {
    loadTemplate(template.fromFile, event.target.files[0]);
  });

  $('#open_url').click(function(event) {
    event.preventDefault();
    if (remoteInput.is(':visible')) {
      loadTemplate(template.fromURL, getTemplateUrl());
    }
    else {
      remoteInput.show();
    }
  });

  $('#save_template').click(function(event) {
    event.preventDefault();
    saveAs(
      new Blob( [template.text(2)], { type: 'text/plain;charset=utf-8' }),
      template.description() + '.json'
    );
    return false;
  });
  $('#save_graph').click(function(event) {
    event.preventDefault();
    var saveWindow = window.open('savegraph.html');
    saveWindow.onload = function() {
      saveWindow.document.getElementById('graphPNG').src = template.base64Image();
    };
    return false;
  });
  $('#graph_layout').change(function() {
    template.setLayout($('#graph_layout').val());
  });

  var container = $('#container'),
    editorPane = $('#editor_pane');

  $('#border').on('mousedown', function(e) {
    isResizing = true;
    lastDownX = e.clientX;
  });

  $(document).on('mousemove', function(e) {
    // we don't want to do anything if we aren't resizing.
    if (!isResizing) {
      return;
    }

    var offsetRight = container.width() - (e.clientX - container.offset().left);

    graphArea.css('right', offsetRight);
    editorPane.css('width', offsetRight);
  }).on('mouseup', function() {
    if (isResizing) {
      template.fitGraph();
    }
    // stop resizing
    isResizing = false;
  });
  var queryTools = require('./queryparser');
  $(document).ready(function() {
        //----- Parse Query -----//
  queryTools.parser(window.location.search,{
    onTemplate: function (url) {
      loadTemplate(template.fromURL, url);
    }
  });
  //----- Parse Query -----//
  });
})();
<|endoftext|>


<commit_before>'use strict';

var m = require('mithril');
var _ = require('underscore');
var classNames = require('classnames');
var Browser = require('./browser');

function Grid(args) {
  this.columnCount = args.columnCount;
  this.rowCount = args.rowCount;
  // The columns array where columns containing placed chips are stored
  this.columns = [];
  this.resetGrid();
}
// Reset the grid by removing all placed chips
Grid.prototype.resetGrid = function () {
  this.columns.length = 0;
  for (var c = 0; c < this.columnCount; c += 1) {
    this.columns.push([]);
  }
};

Grid.Component = {};

Grid.Component.controller = function () {
  return {
    // Initialize position of pending chip to the leftmost column
    pendingChipX: 0,
    pendingChipY: 0,
    // Get the CSS translate string for the given coordinate map
    getTranslate: function (coords) {
      return 'translate(' + coords.x + 'px,' + coords.y + 'px)';
    },
    // Update the translation coordinates for the pending chip (this will take
    // effect on the next redraw)
    setPendingChipCoords: function (coords) {
      this.pendingChipX = coords.x;
      this.pendingChipY = coords.y;
    },
    // Get the left offset of the pointer column
    getPointerColumnX: function (game, event) {
      var chipWidth = event.currentTarget.offsetWidth / game.grid.columnCount;
      return Math.floor((event.pageX - event.currentTarget.offsetLeft) / chipWidth) * chipWidth;
    },
    // Get the index of the pointer column
    getPointerColumnIndex: function (game, event) {
      var chipWidth = event.currentTarget.offsetWidth / game.grid.columnCount;
      return Math.floor((event.pageX - event.currentTarget.offsetLeft) / chipWidth);
    },
    // Translate the pending chip to be aligned with the column nearest to the
    // user's pointer
    movePendingChipToPointerColumn: function (ctrl, game, event) {
      if (game.pendingChip) {
        // The pointer column is the grid column nearest to the cursor at any
        // given instant; keep track of the pointer column's X position so the
        // next pending chip can instantaneously appear there
        ctrl.pointerColumnX = ctrl.getPointerColumnX(game, event);
        if (!ctrl.transitionPendingChipY) {
          ctrl.setPendingChipCoords({
            x: ctrl.pointerColumnX,
            y: 0
          });
        }
        ctrl.transitionPendingChipX = true;
      }
    },
    // Get the coordinates of the chip slot element at the given column/row
    getSlotCoords: function (columnIndex, rowIndex) {
      var slotElem = document
        .getElementById('chip-slots')
        .getElementsByClassName('grid-column')[columnIndex]
        .getElementsByClassName('chip-slot')[rowIndex];
      var slotStyle = window.getComputedStyle(slotElem);
      return {
        x: slotElem.offsetLeft - parseInt(slotStyle['margin-left']),
        y: slotElem.offsetTop - parseInt(slotStyle['margin-top'])
      };
    },
    // Place the pending chip into the poiner column's next available slot
    placePendingChip: function (ctrl, game, event) {
      if (game.pendingChip && !ctrl.transitionPendingChipY) {
        var pendingChipElem = event.currentTarget.querySelector('.chip.pending');
        if (!pendingChipElem) {
          return;
        }
        // Get the column/row index where the pending chip is to be placed
        var columnIndex = ctrl.getPointerColumnIndex(game, event);
        var rowIndex = game.getNextAvailableSlot({column: columnIndex});
        // Do not allow user to place chip in column that is already full
        if (rowIndex === null) {
          return;
        }
        var slotCoords = ctrl.getSlotCoords(columnIndex, rowIndex);
        // If pending chip is not currently aligned with pointer column
        if (ctrl.pendingChipX !== slotCoords.x) {
          // First move pending chip into alignment with pointer column
          ctrl.movePendingChipToPointerColumn(ctrl, game, event);
        } else {
          // Otherwise, chip is already aligned; drop chip into place on grid
          ctrl.transitionPendingChipX = false;
          ctrl.transitionPendingChipY = true;
          // Translate chip to the visual position on the grid corresponding to
          // the above column and row
          ctrl.setPendingChipCoords(slotCoords);
          // Perform insertion on internal game grid once transition has ended
          ctrl.finishPlacingPendingChip(ctrl, game, pendingChipElem, columnIndex);
        }
      }
    },
    // Place the pending chip on the grid once the falling transition has ended
    finishPlacingPendingChip: function (ctrl, game, pendingChipElem, columnIndex) {
      var transitionendEventName = Browser.normalizeEventName('transitionend');
      pendingChipElem.addEventListener(transitionendEventName, function transitionend(event) {
        event.target.removeEventListener(transitionendEventName, transitionend);
        game.placePendingChip({column: columnIndex});
        ctrl.transitionPendingChipX = false;
        ctrl.transitionPendingChipY = false;
        // Check for winning connections (i.e. four in a row)
        game.checkForWin();
        // Check if the grid is completely full
        game.checkForFullGrid();
        // If the above checks have not ended the game, continue to next
        // player's turn
        game.endTurn();
        // Reset position of pending chip to be directly above pointer column
        ctrl.setPendingChipCoords({
          x: ctrl.pointerColumnX,
          y: 0
        });
        m.redraw();
      });
    }
  };
};
Grid.Component.view = function (ctrl, game) {
  var grid = game.grid;
  return m('div#grid', {
    onmousemove: _.partial(ctrl.movePendingChipToPointerColumn, ctrl, game),
    onclick: _.partial(ctrl.placePendingChip, ctrl, game)
  }, [
    // The chip that is about to be placed on the grid
    game.pendingChip ?
      m('div', {
        class: classNames(
          'chip',
          'pending',
          game.pendingChip.player.color,
           {'transition-x': ctrl.transitionPendingChipX},
           {'transition-y': ctrl.transitionPendingChipY}
        ),
        style: Browser.normalizeStyles({
          transform: ctrl.getTranslate({
            x: ctrl.pendingChipX,
            y: ctrl.pendingChipY
          })
        })
      }) : null,
    // Bottom grid of slots (indicating space chips can occupy)
    m('div#chip-slots', _.times(grid.columnCount, function (c) {
      return m('div.grid-column', _.times(grid.rowCount, function (r) {
        return m('div.chip-slot');
      }));
    })),
    // Top grid of placed chips
    m('div#placed-chips', _.times(grid.columnCount, function (c) {
      return m('div.grid-column', _.map(grid.columns[c], function (chip, r) {
        return m('div', {
          key: 'chip-' + [c, r].join('-'),
          class: classNames(
            'chip',
            'placed',
            chip.player.color,
            {'highlighted': chip.highlighted}
          )
        });
      }));
    }))
  ]);
};

module.exports = Grid;
<commit_msg>Fix bug where pending chip position would not reset<commit_after>'use strict';

var m = require('mithril');
var _ = require('underscore');
var classNames = require('classnames');
var Browser = require('./browser');

function Grid(args) {
  this.columnCount = args.columnCount;
  this.rowCount = args.rowCount;
  // The columns array where columns containing placed chips are stored
  this.columns = [];
  this.resetGrid();
}
// Reset the grid by removing all placed chips
Grid.prototype.resetGrid = function () {
  this.columns.length = 0;
  for (var c = 0; c < this.columnCount; c += 1) {
    this.columns.push([]);
  }
};

Grid.Component = {};

Grid.Component.controller = function () {
  return {
    // Initialize position of pending chip to the leftmost column
    pendingChipX: 0,
    pendingChipY: 0,
    // Get the CSS translate string for the given coordinate map
    getTranslate: function (coords) {
      return 'translate(' + coords.x + 'px,' + coords.y + 'px)';
    },
    // Update the translation coordinates for the pending chip (this will take
    // effect on the next redraw)
    setPendingChipCoords: function (coords) {
      this.pendingChipX = coords.x;
      this.pendingChipY = coords.y;
    },
    // Get the left offset of the pointer column
    getPointerColumnX: function (game, event) {
      var chipWidth = event.currentTarget.offsetWidth / game.grid.columnCount;
      return Math.floor((event.pageX - event.currentTarget.offsetLeft) / chipWidth) * chipWidth;
    },
    // Get the index of the pointer column
    getPointerColumnIndex: function (game, event) {
      var chipWidth = event.currentTarget.offsetWidth / game.grid.columnCount;
      return Math.floor((event.pageX - event.currentTarget.offsetLeft) / chipWidth);
    },
    // Translate the pending chip to be aligned with the column nearest to the
    // user's pointer
    movePendingChipToPointerColumn: function (ctrl, game, event) {
      if (game.pendingChip) {
        // The pointer column is the grid column nearest to the cursor at any
        // given instant; keep track of the pointer column's X position so the
        // next pending chip can instantaneously appear there
        ctrl.pointerColumnX = ctrl.getPointerColumnX(game, event);
        if (!ctrl.transitionPendingChipY) {
          ctrl.setPendingChipCoords({
            x: ctrl.pointerColumnX,
            y: 0
          });
        }
        ctrl.transitionPendingChipX = true;
      }
    },
    // Get the coordinates of the chip slot element at the given column/row
    getSlotCoords: function (columnIndex, rowIndex) {
      var slotElem = document
        .getElementById('chip-slots')
        .getElementsByClassName('grid-column')[columnIndex]
        .getElementsByClassName('chip-slot')[rowIndex];
      var slotStyle = window.getComputedStyle(slotElem);
      return {
        x: slotElem.offsetLeft - parseInt(slotStyle['margin-left']),
        y: slotElem.offsetTop - parseInt(slotStyle['margin-top'])
      };
    },
    // Place the pending chip into the poiner column's next available slot
    placePendingChip: function (ctrl, game, event) {
      if (game.pendingChip && !ctrl.transitionPendingChipY) {
        var pendingChipElem = event.currentTarget.querySelector('.chip.pending');
        if (!pendingChipElem) {
          return;
        }
        // Get the column/row index where the pending chip is to be placed
        var columnIndex = ctrl.getPointerColumnIndex(game, event);
        var rowIndex = game.getNextAvailableSlot({column: columnIndex});
        // Do not allow user to place chip in column that is already full
        if (rowIndex === null) {
          return;
        }
        var slotCoords = ctrl.getSlotCoords(columnIndex, rowIndex);
        // If pending chip is not currently aligned with pointer column
        if (ctrl.pendingChipX !== slotCoords.x) {
          // First move pending chip into alignment with pointer column
          ctrl.movePendingChipToPointerColumn(ctrl, game, event);
        } else {
          // Otherwise, chip is already aligned; drop chip into place on grid
          ctrl.transitionPendingChipX = false;
          ctrl.transitionPendingChipY = true;
          // Keep track of where chip was dropped on click
          ctrl.pointerColumnX = slotCoords.x;
          // Translate chip to the visual position on the grid corresponding to
          // the above column and row
          ctrl.setPendingChipCoords(slotCoords);
          // Perform insertion on internal game grid once transition has ended
          ctrl.finishPlacingPendingChip(ctrl, game, pendingChipElem, columnIndex);
        }
      }
    },
    // Place the pending chip on the grid once the falling transition has ended
    finishPlacingPendingChip: function (ctrl, game, pendingChipElem, columnIndex) {
      var transitionendEventName = Browser.normalizeEventName('transitionend');
      pendingChipElem.addEventListener(transitionendEventName, function transitionend(event) {
        event.target.removeEventListener(transitionendEventName, transitionend);
        game.placePendingChip({column: columnIndex});
        ctrl.transitionPendingChipX = false;
        ctrl.transitionPendingChipY = false;
        // Check for winning connections (i.e. four in a row)
        game.checkForWin();
        // Check if the grid is completely full
        game.checkForFullGrid();
        // If the above checks have not ended the game, continue to next
        // player's turn
        game.endTurn();
        // Reset position of pending chip to be directly above pointer column
        ctrl.setPendingChipCoords({
          x: ctrl.pointerColumnX,
          y: 0
        });
        m.redraw();
      });
    }
  };
};
Grid.Component.view = function (ctrl, game) {
  var grid = game.grid;
  return m('div#grid', {
    onmousemove: _.partial(ctrl.movePendingChipToPointerColumn, ctrl, game),
    onclick: _.partial(ctrl.placePendingChip, ctrl, game)
  }, [
    // The chip that is about to be placed on the grid
    game.pendingChip ?
      m('div', {
        class: classNames(
          'chip',
          'pending',
          game.pendingChip.player.color,
           {'transition-x': ctrl.transitionPendingChipX},
           {'transition-y': ctrl.transitionPendingChipY}
        ),
        style: Browser.normalizeStyles({
          transform: ctrl.getTranslate({
            x: ctrl.pendingChipX,
            y: ctrl.pendingChipY
          })
        })
      }) : null,
    // Bottom grid of slots (indicating space chips can occupy)
    m('div#chip-slots', _.times(grid.columnCount, function (c) {
      return m('div.grid-column', _.times(grid.rowCount, function (r) {
        return m('div.chip-slot');
      }));
    })),
    // Top grid of placed chips
    m('div#placed-chips', _.times(grid.columnCount, function (c) {
      return m('div.grid-column', _.map(grid.columns[c], function (chip, r) {
        return m('div', {
          key: 'chip-' + [c, r].join('-'),
          class: classNames(
            'chip',
            'placed',
            chip.player.color,
            {'highlighted': chip.highlighted}
          )
        });
      }));
    }))
  ]);
};

module.exports = Grid;
<|endoftext|>


<commit_before>/*global require*/
'use strict';

requirejs.config({
  baseUrl: 'scripts',
  shim: {
    handlebars: {
      exports: 'Handlebars'
    },
    cryptojs: {
      exports: 'CryptoJS'
    },
    progressbar: {
      exports: 'ProgressBar'
    },
    minEmoji: {
      exports: 'minEmoji'
    },
    chromaHash: ['jquery']
  },
  paths: {
    // libs
    cryptojs: 'https://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes',
    videojs: '//vjs.zencdn.net/4.6/video',
    jquery: '../bower_components/jquery/dist/jquery',
    underscore: '../bower_components/underscore/underscore',
    // lodash: '../bower_components/lodash/dist/lodash',
    backbone: '../bower_components/backbone/backbone',
    handlebars: '../bower_components/handlebars/handlebars',
    quickblox: '../bower_components/quickblox/quickblox.min',
    progressbar: '../bower_components/progressbar.js/lib/control/progressbar',
    loadImage: '../bower_components/blueimp-load-image/js/load-image',
    canvasToBlob: '../bower_components/blueimp-canvas-to-blob/js/canvas-to-blob',
    mCustomScrollbar: '../bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar',
    nicescroll: '../bower_components/jquery.nicescroll/jquery.nicescroll',
    mousewheel: '../bower_components/jquery-mousewheel/jquery.mousewheel',
    timeago: '../bower_components/jquery-timeago/jquery.timeago',
    minEmoji: '../vendor/emoji/js/minEmoji',
    chromaHash: '../bower_components/Chroma-Hash/jquery.chroma-hash',
    QBNotification: '../bower_components/web-notifications/qbNotification',

    // Q-municate application
    config: '../config',
    MainModule: 'app',
    // models
    UserModule: 'models/user',
    SessionModule: 'models/session',
    ContactModule: 'models/contact',
    DialogModule: 'models/dialog',
    MessageModule: 'models/message',
    AttachModule: 'models/attach',
    ContactListModule: 'models/contact_list',
    VideoChatModule: 'models/videochat',
    // views
    UserView: 'views/user',
    DialogView: 'views/dialog',
    MessageView: 'views/message',
    AttachView: 'views/attach',
    ContactListView: 'views/contact_list',
    VideoChatView: 'views/videochat',
    // events
    Events: 'events',
    // helpers
    Helpers: 'helpers',
    QBApiCalls: 'qbApiCalls'
  }
});

requirejs([
  'jquery', 'config',
  'minEmoji', 'MainModule',
  'backbone', 'QBNotification'
], function ($, QMCONFIG, minEmoji, QM, Backbone, QBNotification) {
  var APP;

  // Application initialization
  $(document).ready(function() {
    $.ajaxSetup({ cache: true });
    $.getScript('https://connect.facebook.net/en_US/sdk.js', function() {
      FB.init({
        appId: QMCONFIG.fbAccount.appId,
        version: 'v2.1'
      });
      if (QMCONFIG.debug) console.log('FB init', FB);

      // emoji smiles run
      $('.smiles-group').each(function() {
        var obj = $(this);
        obj.html(minEmoji(obj.text()));
      });

      if (QMCONFIG.notification && QBNotification.isSupported()) {
        QBNotification.requestPermission();
      }

      APP = new QM();
      APP.init();
    });
  });

});
<commit_msg>fix for QM build<commit_after>/*global require*/
'use strict';

requirejs.config({
  baseUrl: 'scripts',
  shim: {
    handlebars: {
      exports: 'Handlebars'
    },
    cryptojs: {
      exports: 'CryptoJS'
    },
    progressbar: {
      exports: 'ProgressBar'
    },
    minEmoji: {
      exports: 'minEmoji'
    },
    chromaHash: ['jquery']
  },
  paths: {
    // libs
    cryptojs: 'https://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes',
    videojs: '//vjs.zencdn.net/4.6/video',
    jquery: '../bower_components/jquery/dist/jquery',
    underscore: '../bower_components/underscore/underscore',
    // lodash: '../bower_components/lodash/dist/lodash',
    backbone: '../bower_components/backbone/backbone',
    handlebars: '../bower_components/handlebars/handlebars',
    quickblox: '../bower_components/quickblox/quickblox.min',
    progressbar: '../bower_components/progressbar.js/lib/control/progressbar',
    loadImage: '../bower_components/blueimp-load-image/js/load-image',
    canvasToBlob: '../bower_components/blueimp-canvas-to-blob/js/canvas-to-blob',
    mCustomScrollbar: '../bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar',
    nicescroll: '../bower_components/jquery.nicescroll/jquery.nicescroll.min',
    mousewheel: '../bower_components/jquery-mousewheel/jquery.mousewheel',
    timeago: '../bower_components/jquery-timeago/jquery.timeago',
    minEmoji: '../vendor/emoji/js/minEmoji',
    chromaHash: '../bower_components/Chroma-Hash/jquery.chroma-hash',
    QBNotification: '../bower_components/web-notifications/qbNotification',

    // Q-municate application
    config: '../config',
    MainModule: 'app',
    // models
    UserModule: 'models/user',
    SessionModule: 'models/session',
    ContactModule: 'models/contact',
    DialogModule: 'models/dialog',
    MessageModule: 'models/message',
    AttachModule: 'models/attach',
    ContactListModule: 'models/contact_list',
    VideoChatModule: 'models/videochat',
    // views
    UserView: 'views/user',
    DialogView: 'views/dialog',
    MessageView: 'views/message',
    AttachView: 'views/attach',
    ContactListView: 'views/contact_list',
    VideoChatView: 'views/videochat',
    // events
    Events: 'events',
    // helpers
    Helpers: 'helpers',
    QBApiCalls: 'qbApiCalls'
  }
});

requirejs([
  'jquery', 'config',
  'minEmoji', 'MainModule',
  'backbone', 'QBNotification'
], function ($, QMCONFIG, minEmoji, QM, Backbone, QBNotification) {
  var APP;

  // Application initialization
  $(document).ready(function() {
    $.ajaxSetup({ cache: true });
    $.getScript('https://connect.facebook.net/en_US/sdk.js', function() {
      FB.init({
        appId: QMCONFIG.fbAccount.appId,
        version: 'v2.1'
      });
      if (QMCONFIG.debug) console.log('FB init', FB);

      // emoji smiles run
      $('.smiles-group').each(function() {
        var obj = $(this);
        obj.html(minEmoji(obj.text()));
      });

      if (QMCONFIG.notification && QBNotification.isSupported()) {
        QBNotification.requestPermission();
      }

      APP = new QM();
      APP.init();
    });
  });

});
<|endoftext|>


<commit_before>$(document).ready(function() {
  if (window.orientation === undefined) { // use video on desktop
    var $player = $('#player');
    var player = $player.get(0);
    var $parent = $player.parent();
    var $win = $(window);
    var resizeTimeout = null;
    var shouldResize = false;
    var shouldPosition = false;
    var videoRatio = 854 / 460;

    player.volume = 0.5; // half of system volume

    var resize = function() {
      if (!shouldResize) { return; }

      var height = $parent.height();
      var width = $parent.width();
      var viewportRatio = width / height;
      var scale = 1;

      if (videoRatio < viewportRatio) {
        // viewport more widescreen than video aspect ratio
        scale = viewportRatio / videoRatio;
      } else if (viewportRatio < videoRatio) {
        // viewport more square than video aspect ratio
        scale = videoRatio / viewportRatio;
      }

      var offset = positionVideo(scale, width, height);
      setVideoTransform(scale, offset);
    };

    var setVideoTransform = function(scale, offset) {
      offset = $.extend({ x: 0, y: 0 }, offset);
      var transform = 'translate(' + Math.round(offset.x) + 'px,' + Math.round(offset.y) +
        'px) scale(' + scale  + ')';
      $player.css({
        '-webkit-transform': transform,
        'transform': transform
      });
    };

    // accounts for transform origins on scaled video
    var positionVideo = function(scale, width, height) {
      if (!shouldPosition) { return false; }

      var x = parseInt($player.data('origin-x'), 10);
      var y = parseInt($player.data('origin-y'), 10);
      setVideoOrigin(x, y);

      var viewportRatio = width / height;
      var scaledHeight = scale * height;
      var scaledWidth = scale * width;
      var percentFromX = (x - 50) / 100;
      var percentFromY = (y - 50) / 100;
      var offset = {};

      if (videoRatio < viewportRatio) {
        offset.x = (scaledWidth - width) * percentFromX;
      } else if (viewportRatio < videoRatio) {
        offset.y = (scaledHeight - height) * percentFromY;
      }

      return offset;
    };

    var setVideoOrigin = function(x, y) {
      var origin = x + '% ' + y + '%';
      $player.css({
        '-webkit-transform-origin': origin,
        'transform-origin': origin
      });
    };

    $win.on('resize', function() {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(resize, 100);
    });

    shouldResize = true;
    shouldPosition = true;
    resize();

    var animateText = function() {
      $('#spinner').remove();
      $player.css('visibility', 'visible');
      player.play();

      setTimeout(function() {
        $('.name').fadeIn(2300)
        $('ul li:nth-child(1)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 200 });
        $('ul li:nth-child(2)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 400 });
        $('ul li:nth-child(3)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 500 });

        setTimeout(function() {
          $('.contact').fadeIn(1400, function() {
            $(this)
              .mouseover(function() {
                $('.bottom').css('opacity', 1);
                $('.top').css('opacity', 0);
              })
              .mouseout(function() {
                $('.bottom').css('opacity', 0);
                $('.top').css('opacity', 1);
              })
              .click(function(){
                window.location = 'mailto:caripearl10@gmail.com';
              });
          });
          $('.contact-label').textillate({ in: {effect: 'fadeInUp'}, initialDelay: 200 });
        }, 3100);
      }, 4700);
    };

    var checkIfLoaded = function() {
      if (player.duration === player.buffered.end(0)) {
        clearInterval(loadingInterval);
        animateText();
      }
    };

    var loadingInterval;
    player.addEventListener('loadedmetadata', function() {
      loadingInterval = setInterval(checkIfLoaded, 30);
    });
  } else { // revert to background image on mobile (pending image)
    $('#spinner').remove();
    $('#player').remove();
    $('body').addClass('mobile');

    $('.name').fadeIn(3000);
    $('ul li:nth-child(1)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 700 });
    $('ul li:nth-child(2)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 900 });
    $('ul li:nth-child(3)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 1000 });

    setTimeout(function() {
      $('.contact').fadeIn(2000, function() {
        $(this)
          .mouseover(function() {
            $('.bottom').css('opacity', 1);
            $('.top').css('opacity', 0);
          })
          .mouseout(function() {
            $('.bottom').css('opacity', 0);
            $('.top').css('opacity', 1);
          })
          .click(function(){
            window.location = 'mailto:caripearl10@gmail.com';
          });
      });
      $('.contact-label').textillate({ in: {effect: 'fadeInUp'}, initialDelay: 400 });
    }, 3900);
  }
});
<commit_msg>Oh Firefox...<commit_after>$(document).ready(function() {
  if (window.orientation === undefined) { // use video on desktop
    var $player = $('#player');
    var player = $player.get(0);
    var $parent = $player.parent();
    var $win = $(window);
    var resizeTimeout = null;
    var shouldResize = false;
    var shouldPosition = false;
    var videoRatio = 854 / 460;

    player.volume = 0.5; // half of system volume

    var resize = function() {
      if (!shouldResize) { return; }

      var height = $parent.height();
      var width = $parent.width();
      var viewportRatio = width / height;
      var scale = 1;

      if (videoRatio < viewportRatio) {
        // viewport more widescreen than video aspect ratio
        scale = viewportRatio / videoRatio;
      } else if (viewportRatio < videoRatio) {
        // viewport more square than video aspect ratio
        scale = videoRatio / viewportRatio;
      }

      var offset = positionVideo(scale, width, height);
      setVideoTransform(scale, offset);
    };

    var setVideoTransform = function(scale, offset) {
      offset = $.extend({ x: 0, y: 0 }, offset);
      var transform = 'translate(' + Math.round(offset.x) + 'px,' + Math.round(offset.y) +
        'px) scale(' + scale  + ')';
      $player.css({
        '-webkit-transform': transform,
        'transform': transform
      });
    };

    // accounts for transform origins on scaled video
    var positionVideo = function(scale, width, height) {
      if (!shouldPosition) { return false; }

      var x = parseInt($player.data('origin-x'), 10);
      var y = parseInt($player.data('origin-y'), 10);
      setVideoOrigin(x, y);

      var viewportRatio = width / height;
      var scaledHeight = scale * height;
      var scaledWidth = scale * width;
      var percentFromX = (x - 50) / 100;
      var percentFromY = (y - 50) / 100;
      var offset = {};

      if (videoRatio < viewportRatio) {
        offset.x = (scaledWidth - width) * percentFromX;
      } else if (viewportRatio < videoRatio) {
        offset.y = (scaledHeight - height) * percentFromY;
      }

      return offset;
    };

    var setVideoOrigin = function(x, y) {
      var origin = x + '% ' + y + '%';
      $player.css({
        '-webkit-transform-origin': origin,
        'transform-origin': origin
      });
    };

    $win.on('resize', function() {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(resize, 100);
    });

    shouldResize = true;
    shouldPosition = true;
    resize();

    var animateText = function() {
      $('#spinner').remove();
      $player.css('visibility', 'visible');
      player.play();

      setTimeout(function() {
        $('.name').fadeIn(2300)
        $('ul li:nth-child(1)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 200 });
        $('ul li:nth-child(2)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 400 });
        $('ul li:nth-child(3)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 500 });

        setTimeout(function() {
          $('.contact').fadeIn(1400, function() {
            $(this)
              .mouseover(function() {
                $('.bottom').css('opacity', 1);
                $('.top').css('opacity', 0);
              })
              .mouseout(function() {
                $('.bottom').css('opacity', 0);
                $('.top').css('opacity', 1);
              })
              .click(function(){
                window.location = 'mailto:caripearl10@gmail.com';
              });
          });
          $('.contact-label').textillate({ in: {effect: 'fadeInUp'}, initialDelay: 200 });
        }, 3100);
      }, 4700);
    };

    var checkIfLoaded = function() {
      if (player.duration - player.buffered.end(0) < 1) { // Firefox never completely fills buffer!
        clearInterval(loadingInterval);
        animateText();
      }
    };

    var loadingInterval;
    player.addEventListener('loadedmetadata', function() {
      loadingInterval = setInterval(checkIfLoaded, 30);
    });
  } else { // revert to background image on mobile (pending image)
    $('#spinner').remove();
    $('#player').remove();
    $('body').addClass('mobile');

    $('.name').fadeIn(3000);
    $('ul li:nth-child(1)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 700 });
    $('ul li:nth-child(2)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 900 });
    $('ul li:nth-child(3)').textillate({ in: {effect: 'fadeInLeft'}, initialDelay: 1000 });

    setTimeout(function() {
      $('.contact').fadeIn(2000, function() {
        $(this)
          .mouseover(function() {
            $('.bottom').css('opacity', 1);
            $('.top').css('opacity', 0);
          })
          .mouseout(function() {
            $('.bottom').css('opacity', 0);
            $('.top').css('opacity', 1);
          })
          .click(function(){
            window.location = 'mailto:caripearl10@gmail.com';
          });
      });
      $('.contact-label').textillate({ in: {effect: 'fadeInUp'}, initialDelay: 400 });
    }, 3900);
  }
});
<|endoftext|>


<commit_before>require.config({
    packages: [{
        name     : 'ace',
        location : '../bower_components/ace/lib/ace',
        main     : 'ace'
    }],
    paths: {
        // Dependencies            :  and libraries
        text                       :  '../bower_components/requirejs-text/text',
        jquery                     :  '../bower_components/jquery/jquery',
        underscore                 :  '../bower_components/underscore/underscore',
        // Backbone &              :  Marionette
        backbone                   :  '../bower_components/backbone/backbone',
        marionette                 :  '../bower_components/marionette/lib/core/amd/backbone.marionette',
        localStorage               :  '../bower_components/backbone.localStorage/backbone.localStorage',
        'backbone.wreqr'           :  '../bower_components/backbone.wreqr/lib/amd/backbone.wreqr',
        'backbone.babysitter'      :  '../bower_components/backbone.babysitter/lib/amd/backbone.babysitter',
        'backbone.relational'      :  '../bower_components/backbone-relational/backbone-relational',
        'backbone.assosiations'    :  '../bower_components/backbone-associations/backbone-associations',
        // Keybindings             :
        'Mousetrap'                :  '../bower_components/mousetrap/mousetrap',
        'backbone.mousetrap'       :  '../bower_components/backbone.mousetrap/backbone.mousetrap',
        // Pagedown                :
        'pagedown-ace'             :  '../bower_components/pagedown-ace/Markdown.Editor',
        'pagedown.converter'       :  '../bower_components/pagedown-ace/Markdown.Converter',
        'pagedown-extra'           :  '../bower_components/pagedown-extra/Markdown.Extra',
        'pagedown.sanitizer'       :  '../bower_components/pagedown-ace/Markdown.Sanitizer',
        checklist                  :  'libs/checklist',
        'typeahead'                :  '../bower_components/typeahead.js/dist/typeahead.min',
        'tagsinput'           : '../bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput.min',
        // Other                   :  libraries
        'bootstrap'                :  '../bower_components/bootstrap/dist/js/bootstrap.min',
        'prettify'                 :  '../bower_components/google-code-prettify/src/prettify',
        'bootstrap-modal'          :  'libs/bootstrap-modal/src/backbone.bootstrap-modal',
        // 'bootstrap-modal'       :  '../bower_components/backbone.bootstrap-modal/src/backbone.bootstrap-modal',
        // Collections             :  scripts
        'notesCollection'          :  'collections/notes',
        // View                    :  scripts here
        'modalRegion'              :  'views/modal',
        'sidebar'                  :  'views/composite/sidebar',
        'noteForm'                 :  'views/item/noteForm',
        'noteSidebar'              :  'views/composite/noteSidebar',
        'noteSidebarItem'          :  'views/item/noteSidebarItem',
        'noteItem'                 :  'views/item/noteItem',
        'notebookLayout'           :  'views/layouts/notebook',
        'notebookSidebar'          :  'views/composite/notebookSidebar',
        'notebookSidebarItem'      :  'views/item/notebookSidebarItem',
        'notebookForm'             :  'views/item/notebookForm',
        'tagForm'                  :  'views/item/tagForm',
        'tagsSidebar'              :  'views/composite/tags',
        'tagSidebarItem'           :  'views/item/tagSidebarItem',
        // Templates               :  here
        'modalTempl'               :  'templates/modal.html',
        'noteFormTempl'            :  'templates/notes/form.html',
        'noteAddTempl'             :  'templates/notes/add.html',
        'noteSidebarTempl'         :  'templates/notes/sidebarList.html',
        'noteSidebarItemTempl'     :  'templates/notes/sidebarListItem.html',
        'noteItemTempl'            :  'templates/notes/item.html',
        'notebookLayoutTempl'      :  'templates/notebooks/layout.html',
        'notebookSidebarTempl'     :  'templates/notebooks/sidebarList.html',
        'notebookSidebarItemTempl' :  'templates/notebooks/sidebarListItem.html',
        'notebookFormTempl'        :  'templates/notebooks/form.html',
        'tagFormTempl'             :  'templates/tags/form.html',
        'tagsSidebarTempl'         :  'templates/tags/sidebarList.html',
        'tagSidebarItemTempl'      :  'templates/tags/sidebarListItem.html'
>>>>>>> master
    },
    shim: {
        underscore: {
            exports: '_'
        },
        backbone: {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        },
        localStorage: {
            deps: ['underscore', 'backbone']
        },
        'backbone.relational': {
            deps: ['backbone']
        },
        'backbone.assosiations': {
            deps: ['backbone']
        },
        bootstrap: {
            deps: ['jquery'],
            exports: '$'
        },
        'Mousetrap': {},
        'backbone.mousetrap': {
            deps: ['Mousetrap']
        },
        ace: {
            exports: 'ace'
        },
        'pagedown-extra': ['pagedown-ace'],
        'pagedown-ace': [
            '../bower_components/pagedown-ace/Markdown.Converter',
            '../bower_components/pagedown-ace/Markdown.Sanitizer'
        ],
        prettify: {
            exports: 'prettify'
        },
        'bootstrap-modal': {
            deps: ['bootstrap', 'underscore', 'jquery'],
            exports: 'Backbone.BootstrapModal'
        }
    },
    waitSeconds: 8
});

require(['jquery', 'router', 'app'],
function ($, Router, App) {
    'use strict';

    // App starts here
    new Router();
    App.start();
);
<commit_msg>update<commit_after>require.config({
    packages: [{
        name     : 'ace',
        location : '../bower_components/ace/lib/ace',
        main     : 'ace'
    }],
    paths: {
        // Dependencies            :  and libraries
        text                       :  '../bower_components/requirejs-text/text',
        jquery                     :  '../bower_components/jquery/jquery',
        underscore                 :  '../bower_components/underscore/underscore',
        // Backbone &              :  Marionette
        backbone                   :  '../bower_components/backbone/backbone',
        marionette                 :  '../bower_components/marionette/lib/core/amd/backbone.marionette',
        localStorage               :  '../bower_components/backbone.localStorage/backbone.localStorage',
        'backbone.wreqr'           :  '../bower_components/backbone.wreqr/lib/amd/backbone.wreqr',
        'backbone.babysitter'      :  '../bower_components/backbone.babysitter/lib/amd/backbone.babysitter',
        'backbone.relational'      :  '../bower_components/backbone-relational/backbone-relational',
        'backbone.assosiations'    :  '../bower_components/backbone-associations/backbone-associations',
        // Keybindings             :
        'Mousetrap'                :  '../bower_components/mousetrap/mousetrap',
        'backbone.mousetrap'       :  '../bower_components/backbone.mousetrap/backbone.mousetrap',
        // Pagedown                :
        'pagedown-ace'             :  '../bower_components/pagedown-ace/Markdown.Editor',
        'pagedown.converter'       :  '../bower_components/pagedown-ace/Markdown.Converter',
        'pagedown-extra'           :  '../bower_components/pagedown-extra/Markdown.Extra',
        'pagedown.sanitizer'       :  '../bower_components/pagedown-ace/Markdown.Sanitizer',
        checklist                  :  'libs/checklist',
        'typeahead'                :  '../bower_components/typeahead.js/dist/typeahead.min',
        'tagsinput'           : '../bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput.min',
        // Other                   :  libraries
        'bootstrap'                :  '../bower_components/bootstrap/dist/js/bootstrap.min',
        'prettify'                 :  '../bower_components/google-code-prettify/src/prettify',
        'bootstrap-modal'          :  'libs/bootstrap-modal/src/backbone.bootstrap-modal',
        // 'bootstrap-modal'       :  '../bower_components/backbone.bootstrap-modal/src/backbone.bootstrap-modal',
        // Collections             :  scripts
        'notesCollection'          :  'collections/notes',
        // View                    :  scripts here
        'modalRegion'              :  'views/modal',
        'sidebar'                  :  'views/composite/sidebar',
        'noteForm'                 :  'views/item/noteForm',
        'noteSidebar'              :  'views/composite/noteSidebar',
        'noteSidebarItem'          :  'views/item/noteSidebarItem',
        'noteItem'                 :  'views/item/noteItem',
        'notebookLayout'           :  'views/layouts/notebook',
        'notebookSidebar'          :  'views/composite/notebookSidebar',
        'notebookSidebarItem'      :  'views/item/notebookSidebarItem',
        'notebookForm'             :  'views/item/notebookForm',
        'tagForm'                  :  'views/item/tagForm',
        'tagsSidebar'              :  'views/composite/tags',
        'tagSidebarItem'           :  'views/item/tagSidebarItem',
        // Templates               :  here
        'modalTempl'               :  'templates/modal.html',
        'noteFormTempl'            :  'templates/notes/form.html',
        'noteAddTempl'             :  'templates/notes/add.html',
        'noteSidebarTempl'         :  'templates/notes/sidebarList.html',
        'noteSidebarItemTempl'     :  'templates/notes/sidebarListItem.html',
        'noteItemTempl'            :  'templates/notes/item.html',
        'notebookLayoutTempl'      :  'templates/notebooks/layout.html',
        'notebookSidebarTempl'     :  'templates/notebooks/sidebarList.html',
        'notebookSidebarItemTempl' :  'templates/notebooks/sidebarListItem.html',
        'notebookFormTempl'        :  'templates/notebooks/form.html',
        'tagFormTempl'             :  'templates/tags/form.html',
        'tagsSidebarTempl'         :  'templates/tags/sidebarList.html',
        'tagSidebarItemTempl'      :  'templates/tags/sidebarListItem.html'
    },
    shim: {
        underscore: {
            exports: '_'
        },
        backbone: {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        },
        localStorage: {
            deps: ['underscore', 'backbone']
        },
        'backbone.relational': {
            deps: ['backbone']
        },
        'backbone.assosiations': {
            deps: ['backbone']
        },
        bootstrap: {
            deps: ['jquery'],
            exports: '$'
        },
        'Mousetrap': {},
        'backbone.mousetrap': {
            deps: ['Mousetrap']
        },
        ace: {
            exports: 'ace'
        },
        'pagedown-extra': ['pagedown-ace'],
        'pagedown-ace': [
            '../bower_components/pagedown-ace/Markdown.Converter',
            '../bower_components/pagedown-ace/Markdown.Sanitizer'
        ],
        prettify: {
            exports: 'prettify'
        },
        'bootstrap-modal': {
            deps: ['bootstrap', 'underscore', 'jquery'],
            exports: 'Backbone.BootstrapModal'
        }
    },
    waitSeconds: 8
});

require(['jquery', 'router', 'app'],
function ($, Router, App) {
    'use strict';

    // App starts here
    new Router();
    App.start();
);
<|endoftext|>


<commit_before>console.log('\'Allo \'Allo!');
<commit_msg>removed default scripts from generator<commit_after><|endoftext|>


<commit_before>/*!
 *
 *  QR Code scanner.
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR COND5ITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */
(function() {
  'use strict';

  var QRCodeCamera = function(element) {
    // Controls the Camera and the QRCode Module

    var cameraManager = new CameraManager('camera');

    var qrCodeManager = new QRCodeManager('qrcode');
    var processingFrame = false;

    cameraManager.onframe = function(imageData) {
      // There is a frame in the camera, what should we do with it?
      if(processingFrame == false) {
        processingFrame = true;
        var detectedQRCode = qrCodeManager.detectQRCode(imageData, function(url) {
          if(url !== undefined) {
            qrCodeManager.showDialog(url);
          }
          processingFrame = false;
        });
      }
    };
  };

  var QRCodeManager = function(element) {
    var root = document.getElementById(element);
    var canvas = document.getElementById("qr-canvas");
    var qrcodeData = root.querySelector(".QRCodeSuccessDialog-data");
    var qrcodeNavigate = root.querySelector(".QRCodeSuccessDialog-navigate");
    var qrcodeIgnore = root.querySelector(".QRCodeSuccessDialog-ignore");
    var qrcodeShare = root.querySelector(".QRCodeSuccessDialog-share");

    var client = new QRClient();

    var self = this;

    this.currentUrl = undefined;

    if(navigator.share) {
      // Sharing is supported so let's make the UI visible
      qrcodeShare.classList.remove('hidden');
    }

    this.detectQRCode = function(imageData, callback) {
      callback = callback || function() {};

      client.decode(imageData, function(result) {
        if(result !== undefined) {
          self.currentUrl = result;
        }
        callback(result);
      });
    };

    this.showDialog = function(url) {
      root.style.display = 'block';
      qrcodeData.innerText = url;
    };

    this.closeDialog = function() {
      root.style.display = 'none';
      self.qrcodeNavigate = "";
      qrcodeData.innerText = "";
    };

    qrcodeIgnore.addEventListener("click", function() {
      this.closeDialog();
    }.bind(this));

    qrcodeShare.addEventListener("click", function() {
      if(navigator.share) {
        navigator.share({
          title: this.currentUrl,
          text: this.currentUrl,
          url: this.currentUrl
        }).then(function() {
          self.closeDialog();
        }).catch(function() {
          self.closeDialog();
        })
      }

    }.bind(this));

    qrcodeNavigate.addEventListener("click", function() {
      // I really want this to be a link.
      window.location = this.currentUrl;
      this.closeDialog();
    }.bind(this));

  };

  var WebCamManager = function(cameraRoot) {
    var cameraToggleInput = cameraRoot.querySelector('.Camera-toggle-input');
    var cameraToggle = cameraRoot.querySelector('.Camera-toggle');
    var cameraVideo = cameraRoot.querySelector('.Camera-video');

    var source = new CameraSource(cameraVideo);

    this.getDimensions = function() {
      return source.getDimensions();
    };

    source.getCameras(function(cameras) {
      if(cameras.length == 1) {
        cameraToggle.style.display="none";
      }

      // Set the source
      source.setCamera(0);
    });

    source.onframeready = function(imageData) {
      // The Source has some data, we need to push it the controller.
      this.onframeready(imageData);
    }.bind(this);

    var toggleFacingState = function(camera) {
      var facing = camera.facing ? camera.facing : 'user';
      cameraRoot.classList.remove('Camera--facing-environment');
      cameraRoot.classList.remove('Camera--facing-user');
      cameraRoot.classList.add('Camera--facing-' + facing);
    };

    cameraToggleInput.addEventListener('change', function(e) {
      // this is the input element, not the control
      var cameraIdx = 0;

      if(e.target.checked === true) {
        cameraIdx = 1;
      }
      source.stop();
      source.setCamera(cameraIdx);
    });

    // When using the web cam, we need to turn it off when we aren't using it
    document.addEventListener('visibilitychange', function(e) {
      if(document.visibilityState === 'hidden') {
        // Disconnect the camera.
        source.stop();
      }
      else {
        var cameraIdx = 0;

        if(this.checked === true) {
          cameraIdx = 1;
        }
        source.setCamera(cameraIdx);
      }
    });

  };

  var CameraFallbackManager = function(element) {
    var uploadForm = element.querySelector('.CameraFallback-form');
    var inputElement = element.querySelector('.CameraFallback-input');
    var image = new Image();

    this.onframeready = function() {};

    // We don't need to upload anything.
    uploadForm.addEventListener('submit', function(e) {
      e.preventDefault();
      return false;
    });

    inputElement.addEventListener('change', function(e) {
      var objectURL = URL.createObjectURL(e.target.files[0]);
      image.onload = function() {
        this.onframeready(image);
        URL.revokeObjectURL(objectURL);
      }.bind(this);

      image.src = objectURL;

    }.bind(this));

    this.getDimensions = function() {
      return {
        width: image.naturalWidth,
        height: image.naturalHeight
      };
    };
  };

  var CameraSource = function(videoElement) {
    var stream;
    var cameras = [];
    var self = this;
    var gUM = (navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia || null);

    this.stop = function() {
      if(stream) {
        stream.getTracks().forEach(function(t) { t.stop(); } );
      }
    };

    this.getDimensions = function() {
      return {
        width: videoElement.videoWidth,
        height: videoElement.videoHeight
      };
    };

    this.getCameras = function(cb) {
      cb = cb || function() {};

      if('getSources' in MediaStreamTrack) {
        MediaStreamTrack.getSources(function(sources) {

          for(var i = 0; i < sources.length; i++) {
            var source = sources[i];
            if(source.kind === 'video') {

              if(source.facing === 'environment') {
                // cameras facing the environment are pushed to the front of the page
                cameras.unshift(source);
              }
              else {
                cameras.push(source);
              }
            }
          }
          cb(cameras);
        });
      }
      else {
        // We can't pick the correct camera because the API doesn't support it.
        cb(cameras);
      }
    };

    this.setCamera = function(idx) {
      var params;
      var videoSource = cameras[idx];

      if(videoSource === undefined && cameras.length == 0) {
        // Because we have no source information, have to assume it user facing.
        params = { video: true, audio: false };
      }
      else {
        params = { video: { optional: [{sourceId: videoSource.id}] }, audio: false };
      }

      gUM.call(navigator, params, function(cameraStream) {
        stream = cameraStream;

        videoElement.onloadeddata = function(e) {

          var onframe = function() {
            self.onframeready(videoElement);
            requestAnimationFrame(onframe);
          };

          requestAnimationFrame(onframe);

          // The video is ready, and the camera captured
          if(videoSource === undefined) {
            // There is no meta data about the camera, assume user facing.
            videoSource = {
              'facing': 'user'
            };
          }
        };

        videoElement.srcObject = stream;
        videoElement.load();
        videoElement.play();
      }, function(error) {});
    };
  };

  var CameraManager = function(element) {
    // The camera gets a video stream, and adds it to a canvas.
    // The canvas is analysed but also displayed to the user.
    // The video is never show
    var self = this;
    var gUM = (navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia || null);

    if(location.hash == "#nogum") gUM = null;

    var root = document.getElementById(element);
    var cameraRoot;
    var sourceManager;

    // Where are we getting the data from
    if(gUM === null) {
      cameraRoot = root.querySelector('.CameraFallback');
      sourceManager = new CameraFallbackManager(cameraRoot);
    }
    else {
      cameraRoot = root.querySelector('.CameraRealtime');
      sourceManager = new WebCamManager(cameraRoot);
    }

    cameraRoot.classList.remove('hidden');

    var cameraCanvas = root.querySelector('.Camera-display');
    var cameraOverlay = root.querySelector('.Camera-overlay');
    var canvas = cameraCanvas.getContext('2d');

    // Variables
    var dWidth;
    var dHeight;
    var dx = 0;
    var dy = 0;

    var sx = 0;
    var sy = 0;
    var sHeight;
    var sWidth;
    var scaleX;
    var scaleY;
    var scaleFactor = 1;

    var cameras = [];
    var coordinatesHaveChanged = true;
    var prevCoordinates = 0;

    var overlayCoords = { x:0, y: 0, width: cameraCanvas.width, height: cameraCanvas.height };

    sourceManager.onframeready = function(frameData) {
      setupVariables();
      // Work out which part of the video to capture and apply to canvas.
      canvas.drawImage(frameData, sx/scaleFactor, sy/scaleFactor, sWidth/scaleFactor, sHeight/scaleFactor, dx, dy, dWidth, dHeight);

      drawOverlay(dWidth, dHeight, scaleFactor);

      // A frame has been captured.
      var imageData = canvas.getImageData(overlayCoords.x, overlayCoords.y, overlayCoords.width, overlayCoords.height);

      if(self.onframe) self.onframe(imageData);

      coordinatesHaveChanged = false;
    };

    var drawOverlay = function(width, height) {
      var minLength = Math.min(width, height);
      var boxHeightSize = (height + 64 - minLength) / 2;
      var boxWidthSize = (width + 64 - minLength) / 2;

      if(coordinatesHaveChanged) {
        cameraOverlay.style.borderTopWidth = boxHeightSize + "px";
        cameraOverlay.style.borderLeftWidth = boxWidthSize + "px";
        cameraOverlay.style.borderRightWidth = boxWidthSize + "px";
        cameraOverlay.style.borderBottomWidth = boxHeightSize + "px";

        overlayCoords.x = boxWidthSize;
        overlayCoords.y = boxHeightSize
        overlayCoords.width = cameraCanvas.width - (boxWidthSize * 2);
        overlayCoords.height = cameraCanvas.height - (boxHeightSize * 2);

        coordinatesHaveChanged = false;
      }
    };

    var setupVariables = function(e) {

      if(cameraCanvas.width == window.innerWidth)
        return;

      var sourceDimensions = sourceManager.getDimensions();
      var sourceHeight = sourceDimensions.height;
      var sourceWidth = sourceDimensions.width;

      dWidth = cameraCanvas.width = window.innerWidth;
      dHeight = cameraCanvas.height = window.innerHeight;
      dx = 0;
      dy = 0;

      sx = 0;
      sy = 0;

      // Make the video coordinate space the same as the window.
      // size in the longest dimension.
      // Then center and clip. and map back to correct space.
      scaleX = (dWidth / sourceDimensions.width);
      scaleY = (dHeight / sourceHeight);
      scaleFactor = Math.max(scaleX, scaleY);

      // Trim the left
      sx = ((sourceWidth * scaleFactor) / 2) - (dWidth/ 2);
      sy = ((sourceHeight * scaleFactor) / 2) - (dHeight / 2);

      // Trim the right.
      sWidth = (sourceWidth * scaleFactor) - sx * 2;
      sHeight = (sourceHeight * scaleFactor) - sy * 2;

      return (sourceWidth > 0);
    };

    window.addEventListener('resize', function(e) {
      coordinatesHaveChanged = true;
      setupVariables();
    }.bind(this));
  };

  window.addEventListener('load', function() {
    var camera = new QRCodeCamera();
  });
})();
<commit_msg>Fixing iOS static image capture<commit_after>/*!
 *
 *  QR Code scanner.
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR COND5ITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */
(function() {
  'use strict';

  var QRCodeCamera = function(element) {
    // Controls the Camera and the QRCode Module

    var cameraManager = new CameraManager('camera');

    var qrCodeManager = new QRCodeManager('qrcode');
    var processingFrame = false;

    cameraManager.onframe = function(imageData) {
      // There is a frame in the camera, what should we do with it?
      if(processingFrame == false) {
        processingFrame = true;
        var detectedQRCode = qrCodeManager.detectQRCode(imageData, function(url) {
          if(url !== undefined) {
            qrCodeManager.showDialog(url);
          }
          processingFrame = false;
        });
      }
    };
  };

  var QRCodeManager = function(element) {
    var root = document.getElementById(element);
    var canvas = document.getElementById("qr-canvas");
    var qrcodeData = root.querySelector(".QRCodeSuccessDialog-data");
    var qrcodeNavigate = root.querySelector(".QRCodeSuccessDialog-navigate");
    var qrcodeIgnore = root.querySelector(".QRCodeSuccessDialog-ignore");
    var qrcodeShare = root.querySelector(".QRCodeSuccessDialog-share");

    var client = new QRClient();

    var self = this;

    this.currentUrl = undefined;

    if(navigator.share) {
      // Sharing is supported so let's make the UI visible
      qrcodeShare.classList.remove('hidden');
    }

    this.detectQRCode = function(imageData, callback) {
      callback = callback || function() {};

      client.decode(imageData, function(result) {
        if(result !== undefined) {
          self.currentUrl = result;
        }
        callback(result);
      });
    };

    this.showDialog = function(url) {
      root.style.display = 'block';
      qrcodeData.innerText = url;
    };

    this.closeDialog = function() {
      root.style.display = 'none';
      self.qrcodeNavigate = "";
      qrcodeData.innerText = "";
    };

    qrcodeIgnore.addEventListener("click", function() {
      this.closeDialog();
    }.bind(this));

    qrcodeShare.addEventListener("click", function() {
      if(navigator.share) {
        navigator.share({
          title: this.currentUrl,
          text: this.currentUrl,
          url: this.currentUrl
        }).then(function() {
          self.closeDialog();
        }).catch(function() {
          self.closeDialog();
        })
      }

    }.bind(this));

    qrcodeNavigate.addEventListener("click", function() {
      // I really want this to be a link.
      window.location = this.currentUrl;
      this.closeDialog();
    }.bind(this));

  };

  var WebCamManager = function(cameraRoot) {
    var cameraToggleInput = cameraRoot.querySelector('.Camera-toggle-input');
    var cameraToggle = cameraRoot.querySelector('.Camera-toggle');
    var cameraVideo = cameraRoot.querySelector('.Camera-video');

    var source = new CameraSource(cameraVideo);

    this.getDimensions = function() {
      return source.getDimensions();
    };

    source.getCameras(function(cameras) {
      if(cameras.length == 1) {
        cameraToggle.style.display="none";
      }

      // Set the source
      source.setCamera(0);
    });

    source.onframeready = function(imageData) {
      // The Source has some data, we need to push it the controller.
      this.onframeready(imageData);
    }.bind(this);

    var toggleFacingState = function(camera) {
      var facing = camera.facing ? camera.facing : 'user';
      cameraRoot.classList.remove('Camera--facing-environment');
      cameraRoot.classList.remove('Camera--facing-user');
      cameraRoot.classList.add('Camera--facing-' + facing);
    };

    cameraToggleInput.addEventListener('change', function(e) {
      // this is the input element, not the control
      var cameraIdx = 0;

      if(e.target.checked === true) {
        cameraIdx = 1;
      }
      source.stop();
      source.setCamera(cameraIdx);
    });

    // When using the web cam, we need to turn it off when we aren't using it
    document.addEventListener('visibilitychange', function(e) {
      if(document.visibilityState === 'hidden') {
        // Disconnect the camera.
        source.stop();
      }
      else {
        var cameraIdx = 0;

        if(this.checked === true) {
          cameraIdx = 1;
        }
        source.setCamera(cameraIdx);
      }
    });

  };

  var CameraFallbackManager = function(element) {
    var uploadForm = element.querySelector('.CameraFallback-form');
    var inputElement = element.querySelector('.CameraFallback-input');
    var image = new Image();

    this.onframeready = function() {};

    // We don't need to upload anything.
    uploadForm.addEventListener('submit', function(e) {
      e.preventDefault();
      return false;
    });

    inputElement.addEventListener('change', function(e) {
      var objectURL = URL.createObjectURL(e.target.files[0]);
      image.onload = function() {
        this.onframeready(image);
        URL.revokeObjectURL(objectURL);
      }.bind(this);

      image.src = objectURL;

    }.bind(this));

    this.getDimensions = function() {
      return {
        width: image.naturalWidth,
        height: image.naturalHeight,
        shouldLayout: false
      };
    };
  };

  var CameraSource = function(videoElement) {
    var stream;
    var cameras = [];
    var self = this;
    var gUM = (navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia || null);

    this.stop = function() {
      if(stream) {
        stream.getTracks().forEach(function(t) { t.stop(); } );
      }
    };

    this.getDimensions = function() {
      return {
        width: videoElement.videoWidth,
        height: videoElement.videoHeight,
        shouldLayout: true
      };
    };

    this.getCameras = function(cb) {
      cb = cb || function() {};

      if('getSources' in MediaStreamTrack) {
        MediaStreamTrack.getSources(function(sources) {

          for(var i = 0; i < sources.length; i++) {
            var source = sources[i];
            if(source.kind === 'video') {

              if(source.facing === 'environment') {
                // cameras facing the environment are pushed to the front of the page
                cameras.unshift(source);
              }
              else {
                cameras.push(source);
              }
            }
          }
          cb(cameras);
        });
      }
      else {
        // We can't pick the correct camera because the API doesn't support it.
        cb(cameras);
      }
    };

    this.setCamera = function(idx) {
      var params;
      var videoSource = cameras[idx];

      if(videoSource === undefined && cameras.length == 0) {
        // Because we have no source information, have to assume it user facing.
        params = { video: true, audio: false };
      }
      else {
        params = { video: { optional: [{sourceId: videoSource.id}] }, audio: false };
      }

      gUM.call(navigator, params, function(cameraStream) {
        stream = cameraStream;

        videoElement.onloadeddata = function(e) {

          var onframe = function() {
            self.onframeready(videoElement);
            requestAnimationFrame(onframe);
          };

          requestAnimationFrame(onframe);

          // The video is ready, and the camera captured
          if(videoSource === undefined) {
            // There is no meta data about the camera, assume user facing.
            videoSource = {
              'facing': 'user'
            };
          }
        };

        videoElement.srcObject = stream;
        videoElement.load();
        videoElement.play();
      }, function(error) {});
    };
  };

  var CameraManager = function(element) {
    // The camera gets a video stream, and adds it to a canvas.
    // The canvas is analysed but also displayed to the user.
    // The video is never show
    var self = this;
    var gUM = (navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia || null);

    if(location.hash == "#nogum") gUM = null;

    var root = document.getElementById(element);
    var cameraRoot;
    var sourceManager;

    // Where are we getting the data from
    if(gUM === null) {
      cameraRoot = root.querySelector('.CameraFallback');
      sourceManager = new CameraFallbackManager(cameraRoot);
    }
    else {
      cameraRoot = root.querySelector('.CameraRealtime');
      sourceManager = new WebCamManager(cameraRoot);
    }

    cameraRoot.classList.remove('hidden');

    var cameraCanvas = root.querySelector('.Camera-display');
    var cameraOverlay = root.querySelector('.Camera-overlay');
    var canvas = cameraCanvas.getContext('2d');

    // Variables
    var dWidth;
    var dHeight;
    var dx = 0;
    var dy = 0;

    var sx = 0;
    var sy = 0;
    var sHeight;
    var sWidth;
    var scaleX;
    var scaleY;
    var scaleFactor = 1;

    var cameras = [];
    var coordinatesHaveChanged = true;
    var prevCoordinates = 0;

    var overlayCoords = { x:0, y: 0, width: cameraCanvas.width, height: cameraCanvas.height };

    sourceManager.onframeready = function(frameData) {
      setupVariables();
      // Work out which part of the video to capture and apply to canvas.
      canvas.drawImage(frameData, sx/scaleFactor, sy/scaleFactor, sWidth/scaleFactor, sHeight/scaleFactor, dx, dy, dWidth, dHeight);

      drawOverlay(dWidth, dHeight, scaleFactor);

      // A frame has been captured.
      var imageData = canvas.getImageData(overlayCoords.x, overlayCoords.y, overlayCoords.width, overlayCoords.height);

      if(self.onframe) self.onframe(imageData);

      coordinatesHaveChanged = false;
    };

    var drawOverlay = function(width, height) {
      var minLength = Math.min(width, height);
      var boxHeightSize = (height + 64 - minLength) / 2;
      var boxWidthSize = (width + 64 - minLength) / 2;

      if(coordinatesHaveChanged) {
        cameraOverlay.style.borderTopWidth = boxHeightSize + "px";
        cameraOverlay.style.borderLeftWidth = boxWidthSize + "px";
        cameraOverlay.style.borderRightWidth = boxWidthSize + "px";
        cameraOverlay.style.borderBottomWidth = boxHeightSize + "px";

        overlayCoords.x = boxWidthSize;
        overlayCoords.y = boxHeightSize
        overlayCoords.width = cameraCanvas.width - (boxWidthSize * 2);
        overlayCoords.height = cameraCanvas.height - (boxHeightSize * 2);

        coordinatesHaveChanged = false;
      }
    };

    var setupVariables = function(e) {
      var sourceDimensions = sourceManager.getDimensions();

      if(cameraCanvas.width == window.innerWidth && sourceDimensions.shouldLayout)
        return;

      var sourceHeight = sourceDimensions.height;
      var sourceWidth = sourceDimensions.width;

      dWidth = cameraCanvas.width = window.innerWidth;
      dHeight = cameraCanvas.height = window.innerHeight;
      dx = 0;
      dy = 0;

      sx = 0;
      sy = 0;

      // Make the video coordinate space the same as the window.
      // size in the longest dimension.
      // Then center and clip. and map back to correct space.
      scaleX = (dWidth / sourceDimensions.width);
      scaleY = (dHeight / sourceHeight);
      scaleFactor = Math.max(scaleX, scaleY);

      // Trim the left
      sx = ((sourceWidth * scaleFactor) / 2) - (dWidth/ 2);
      sy = ((sourceHeight * scaleFactor) / 2) - (dHeight / 2);

      // Trim the right.
      sWidth = (sourceWidth * scaleFactor) - sx * 2;
      sHeight = (sourceHeight * scaleFactor) - sy * 2;

      return (sourceWidth > 0);
    };

    window.addEventListener('resize', function(e) {
      coordinatesHaveChanged = true;
      setupVariables();
    }.bind(this));
  };

  window.addEventListener('load', function() {
    var camera = new QRCodeCamera();
  });
})();
<|endoftext|>


<commit_before>'use strict';

/* Services */

angular.module('app.services', [])

.constant('swbCategories', [
  'big_picture_f',
  'civic_f',
  'healthy_habits_f',
  'health_conditions_f',
  'family_life_f',
  'family_stress_f',
  'summer_leisure_f',
  'job_market_f',
  'job_search_f',
  'personal_security_f',
  'fin_security_f',
  'home_finance_f'
])

.constant('swbSeries', [
  'life_eval',
  'life_eval_5',
  'happiness',
  'learn',
  'respect',
  'anger',
  'stress',
  'worry',
  'sadness',
  'laugh'
])

.constant('wellBeingAspects', [
  'current_life',
  'leisure',
  'housing',
  'loved_ones'
])

.constant('regionsMetadata', {
  USA: {
    name: 'États-Unis',
    prefix: 'US',
    label: 'All USA states + DC',
    values: {
      "DC": "District de Columbia",
      "AK": "Alaska",
      "AL": "Alabama",
      "AR": "Arkansas",
      "AZ": "Arizona",
      "CA": "Californie",
      "CO": "Colorado",
      "CT": "Connecticut",
      "DE": "Delaware",
      "FL": "Floride",
      "GA": "Géorgie",
      "HI": "Hawaï",
      "IA": "Iowa",
      "ID": "Idaho",
      "IL": "Illinois",
      "IN": "Indiana",
      "KS": "Kansas",
      "KY": "Kentucky",
      "LA": "Louisiane",
      "MA": "Massachusetts",
      "MD": "Maryland",
      "ME": "Maine",
      "MI": "Michigan",
      "MN": "Minnesota",
      "MO": "Missouri",
      "MS": "État du Mississippi",
      "MT": "Montana",
      "NC": "Caroline du Nord",
      "ND": "Dakota du Nord",
      "NE": "Nebraska",
      "NH": "New Hampshire",
      "NJ": "New Jersey",
      "NM": "Nouveau-Mexique",
      "NV": "Nevada",
      "NY": "État de New York",
      "OH": "Ohio",
      "OK": "Oklahoma",
      "OR": "Oregon",
      "PA": "Pennsylvanie",
      "RI": "Rhode Island",
      "SC": "Caroline du Sud",
      "SD": "Dakota du Sud",
      "TN": "Tennessee",
      "TX": "Texas",
      "UT": "Utah",
      "VA": "Virginie",
      "VT": "Vermont",
      "WA": "État de Washington",
      "WI": "Wisconsin",
      "WV": "Virginie-Occidentale",
      "WY": "Wyoming"
    }
  },
  FR: {
    name: 'France',
    prefix: 'FR',
    label: 'All France regions',
    values: {
      "A": "Alsace",
      "B": "Aquitaine",
      "C": "Auvergne",
      "D": "Bourgogne",
      "E": "Bretagne",
      "F": "Centre",
      "G": "Champagne-Ardenne",
      "H": "Corse",
      "I": "Franche-Comté",
      "J": "Île-de-France",
      "K": "Languedoc-Roussillon",
      "L": "Limousin",
      "M": "Lorraine",
      "N": "Midi-Pyrénées",
      "O": "Nord-Pas-de-Calais",
      "P": "Basse-Normandie",
      "Q": "Haute-Normandie",
      "R": "Pays-de-la-Loire",
      "S": "Picardie",
      "T": "Poitou-Charentes",
      "U": "Provence-Alpes-Côte d'Azur",
      "V": "Rhône-Alpes",
    }
  }
})

// Facets declaration
.factory('usStatesHex', function () {
  // Namespace
  var ns = {};

  ns.matrix = [
    [1,0,0,0,0,0,0,0,0,0,0,1],
    [0,0,0,0,0,0,0,0,0,1,1,0],
    [0,1,1,1,1,1,0,1,0,1,1,1],
    [0,1,1,1,1,1,1,1,1,1,1,0],
    [0,1,1,1,1,1,1,1,1,1,1,0],
    [0,1,1,1,1,1,1,1,1,1,0,0],
    [0,0,0,1,1,1,1,1,1,0,0,0],
    [1,0,0,0,1,0,0,1,0,0,0,0]
  ];

  ns.states = [
    { abbr: "AK", name: "Alaska" },
    { abbr: "ME", name: "Maine"},

    { abbr: "VT", name: "Vermont" },
    { abbr: "NH", name: "New Hampshire"},

    { abbr: "WA", name: "Washington" },
    { abbr: "MT", name: "Montana" },
    { abbr: "ND", name: "North Dakota" },
    { abbr: "MN", name: "Minnesota" },
    { abbr: "WI", name: "Wisconsin" },
    { abbr: "MI", name: "Michigan" },
    { abbr: "NY", name: "New York" },
    { abbr: "MA", name: "Massachusetts" },
    { abbr: "RI", name: "Rhode Island"},

    { abbr: "ID", name: "Idaho" },
    { abbr: "WY", name: "Wyoming" },
    { abbr: "SD", name: "South Dakota" },
    { abbr: "IA", name: "Iowa" },
    { abbr: "IL", name: "Illinois" },
    { abbr: "IN", name: "Indiana" },
    { abbr: "OH", name: "Ohio" },
    { abbr: "PA", name: "Pennsylvania" },
    { abbr: "NJ", name: "New Jersey" },
    { abbr: "CT", name: "Connecticut"},

    { abbr: "OR", name: "Oregon" },
    { abbr: "NV", name: "Nevada" },
    { abbr: "CO", name: "Colorado" },
    { abbr: "NE", name: "Nebraska" },
    { abbr: "MO", name: "Missouri" },
    { abbr: "KY", name: "Kentucky" },
    { abbr: "WV", name: "West Virgina" },
    { abbr: "VA", name: "Virginia" },
    { abbr: "MD", name: "Maryland" },
    { abbr: "DE", name: "Delaware"},

    { abbr: "CA", name: "California" },
    { abbr: "UT", name: "Utah" },
    { abbr: "NM", name: "New Mexico" },
    { abbr: "KS", name: "Kansas" },
    { abbr: "AR", name: "Arkansas" },
    { abbr: "TN", name: "Tennessee" },
    { abbr: "NC", name: "North Carolina" },
    { abbr: "SC", name: "South Carolina" },
    { abbr: "DC", name: "District of Columbia"},

    { abbr: "AZ", name: "Arizona" },
    { abbr: "OK", name: "Oklahoma" },
    { abbr: "LA", name: "Louisiana" },
    { abbr: "MS", name: "Mississippi" },
    { abbr: "AL", name: "Alabama" },
    { abbr: "GA", name: "Georgia"},

    { abbr: "HI", name: "Hawaii" },
    { abbr: "TX", name: "Texas" },
    { abbr: "FL", name: "Florida" }
  ];

  // Process data
  ns.data = []
  // hexagon shape variables
  var hex_di = 100
  var hex_rad = hex_di / 2
  // apothem
  var hex_apo = hex_rad * Math.cos(Math.PI / 6)
  // initial x
  var x = hex_rad / 2
  // initial y
  var y = hex_rad
  // constants
  var pi_six = Math.PI/6;
  var cos_six = Math.cos(pi_six);
  var sin_six = Math.sin(pi_six);
  // loop variables
  var offset = false
  // initial state index
  var state_index = 0
  var i, loop_x, loc_x, s, grid_plot, item
  for(i = 0; i < ns.matrix.length; i++) {
    loop_x = offset ? hex_apo * 2 : hex_apo;

    loc_x = x;
    for(s = 0; s < ns.matrix[i].length; s++) {
      // grid plot in 0 and 1 array
      grid_plot = ns.matrix[i][s];

      // if we have a plot in the grid
      if (grid_plot != 0) {
        // get the state
        item = ns.states[state_index];

        // hexagon polygon points
        item.hex = [
          [loc_x + loop_x, y - hex_rad],
          [loc_x + loop_x + cos_six * hex_rad, y - sin_six * hex_rad],
          [loc_x + loop_x + cos_six * hex_rad, y + sin_six * hex_rad],
          [loc_x + loop_x, y + hex_rad],
          [loc_x + loop_x - cos_six * hex_rad, y + sin_six * hex_rad],
          [loc_x + loop_x - cos_six * hex_rad, y - sin_six * hex_rad],
          [loc_x + loop_x, y - hex_rad]
        ]

        // stats
        item.xExtent = d3.extent(item.hex.map(function(d){return d[0]}))
        item.yExtent = d3.extent(item.hex.map(function(d){return d[1]}))
        item.x = ( item.xExtent[0] + item.xExtent[1] ) / 2
        item.y = ( item.yExtent[0] + item.yExtent[1] ) / 2

        ns.data.push(item);

        // increase the state index reference
        state_index++;
      }

      // move our x plot to next hex position
      loc_x += hex_apo * 2;
    }
    // move our y plot to next row position
    y += hex_di * 0.75;
    // toggle offset per row
    offset = !offset;
  }

  return ns;
})

// Facets declaration
.factory('Facets', function ( wellBeingAspects ,  regionsMetadata ) {
  // Namespace
  var ns = {};

  Facettage.debug = true;

  // Retrieve data from cache
  ns.coeffs = Facettage.newFacet('coefficients.csv', {
    cached: true,
    type: 'csv',
    unserialize: function (data) {
      return data.map( function (d) {
        wellBeingAspects.forEach( function (key) {
          d[key] = Number(d[key]);
        });
        return d;
      })
    }
  })

  ns.getSeries = function (country, region, topic) {
    // The name is an id as well as the path in the data cache
    // FIXME: the '/'' may not be the right path separator
    var name = region + '_' + topic + '.csv';
    // Require a facet (ie. create or get already created)
    return Facettage.requireFacet(name, {
      cached: true,
      /**
       * We use csvRows instead of csv because the first line
       * is not a header
       */
      type: 'csvRows',
      unserialize: function (data) {
        // Remove header
        data.shift();
        // Parse as numbers
        return data.map(Number);
      }
    });
  }

  return ns;
})<commit_msg>hex french regions<commit_after>'use strict';

/* Services */

angular.module('app.services', [])

.constant('swbCategories', [
  'big_picture_f',
  'civic_f',
  'healthy_habits_f',
  'health_conditions_f',
  'family_life_f',
  'family_stress_f',
  'summer_leisure_f',
  'job_market_f',
  'job_search_f',
  'personal_security_f',
  'fin_security_f',
  'home_finance_f'
])

.constant('swbSeries', [
  'life_eval',
  'life_eval_5',
  'happiness',
  'learn',
  'respect',
  'anger',
  'stress',
  'worry',
  'sadness',
  'laugh'
])

.constant('wellBeingAspects', [
  'current_life',
  'leisure',
  'housing',
  'loved_ones'
])

.constant('regionsMetadata', {
  USA: {
    name: 'États-Unis',
    prefix: 'US',
    label: 'All USA states + DC',
    values: {
      "DC": "District de Columbia",
      "AK": "Alaska",
      "AL": "Alabama",
      "AR": "Arkansas",
      "AZ": "Arizona",
      "CA": "Californie",
      "CO": "Colorado",
      "CT": "Connecticut",
      "DE": "Delaware",
      "FL": "Floride",
      "GA": "Géorgie",
      "HI": "Hawaï",
      "IA": "Iowa",
      "ID": "Idaho",
      "IL": "Illinois",
      "IN": "Indiana",
      "KS": "Kansas",
      "KY": "Kentucky",
      "LA": "Louisiane",
      "MA": "Massachusetts",
      "MD": "Maryland",
      "ME": "Maine",
      "MI": "Michigan",
      "MN": "Minnesota",
      "MO": "Missouri",
      "MS": "État du Mississippi",
      "MT": "Montana",
      "NC": "Caroline du Nord",
      "ND": "Dakota du Nord",
      "NE": "Nebraska",
      "NH": "New Hampshire",
      "NJ": "New Jersey",
      "NM": "Nouveau-Mexique",
      "NV": "Nevada",
      "NY": "État de New York",
      "OH": "Ohio",
      "OK": "Oklahoma",
      "OR": "Oregon",
      "PA": "Pennsylvanie",
      "RI": "Rhode Island",
      "SC": "Caroline du Sud",
      "SD": "Dakota du Sud",
      "TN": "Tennessee",
      "TX": "Texas",
      "UT": "Utah",
      "VA": "Virginie",
      "VT": "Vermont",
      "WA": "État de Washington",
      "WI": "Wisconsin",
      "WV": "Virginie-Occidentale",
      "WY": "Wyoming"
    }
  },
  FR: {
    name: 'France',
    prefix: 'FR',
    label: 'All France regions',
    values: {
      /*
      "A": "Alsace",
      "B": "Aquitaine",
      "C": "Auvergne",
      "D": "Bourgogne",
      "E": "Bretagne",
      "F": "Centre",
      "G": "Champagne-Ardenne",
      "H": "Corse",
      "I": "Franche-Comté",
      "J": "Île-de-France",
      "K": "Languedoc-Roussillon",
      "L": "Limousin",
      "M": "Lorraine",
      "N": "Midi-Pyrénées",
      "O": "Nord-Pas-de-Calais",
      "P": "Basse-Normandie",
      "Q": "Haute-Normandie",
      "R": "Pays-de-la-Loire",
      "S": "Picardie",
      "T": "Poitou-Charentes",
      "U": "Provence-Alpes-Côte d'Azur",
      "V": "Rhône-Alpes",
      */
      "ALS": "Alsace",
      "AQU": "Aquitaine",
      "AUV": "Auvergne",
      "BOU": "Bourgogne",
      "BRE": "Bretagne",
      "CEN": "Centre",
      "CHA": "Champagne-Ardenne",
      "COR": "Corse",
      "FRC": "Franche-Comté",
      "IDF": "Île-de-France",
      "LAN": "Languedoc-Roussillon",
      "LIM": "Limousin",
      "LOR": "Lorraine",
      "MID": "Midi-Pyrénées",
      "NPC": "Nord-Pas-de-Calais",
      "BNO": "Basse-Normandie",
      "HNO": "Haute-Normandie",
      "PDL": "Pays-de-la-Loire",
      "PIC": "Picardie",
      "POI": "Poitou-Charentes",
      "PAC": "Provence-Alpes-Côte d'Azur",
      "RHA": "Rhône-Alpes",
    }
  }
})

// US Hex tiling
.factory('usStatesHex', function () {
  // Namespace
  var ns = {};

  ns.matrix = [
    [1,0,0,0,0,0,0,0,0,0,0,1],
    [0,0,0,0,0,0,0,0,0,1,1,0],
    [0,1,1,1,1,1,0,1,0,1,1,1],
    [0,1,1,1,1,1,1,1,1,1,1,0],
    [0,1,1,1,1,1,1,1,1,1,1,0],
    [0,1,1,1,1,1,1,1,1,1,0,0],
    [0,0,0,1,1,1,1,1,1,0,0,0],
    [1,0,0,0,1,0,0,1,0,0,0,0]
  ];

  ns.states = [
    { abbr: "AK", name: "Alaska" },
    { abbr: "ME", name: "Maine"},

    { abbr: "VT", name: "Vermont" },
    { abbr: "NH", name: "New Hampshire"},

    { abbr: "WA", name: "Washington" },
    { abbr: "MT", name: "Montana" },
    { abbr: "ND", name: "North Dakota" },
    { abbr: "MN", name: "Minnesota" },
    { abbr: "WI", name: "Wisconsin" },
    { abbr: "MI", name: "Michigan" },
    { abbr: "NY", name: "New York" },
    { abbr: "MA", name: "Massachusetts" },
    { abbr: "RI", name: "Rhode Island"},

    { abbr: "ID", name: "Idaho" },
    { abbr: "WY", name: "Wyoming" },
    { abbr: "SD", name: "South Dakota" },
    { abbr: "IA", name: "Iowa" },
    { abbr: "IL", name: "Illinois" },
    { abbr: "IN", name: "Indiana" },
    { abbr: "OH", name: "Ohio" },
    { abbr: "PA", name: "Pennsylvania" },
    { abbr: "NJ", name: "New Jersey" },
    { abbr: "CT", name: "Connecticut"},

    { abbr: "OR", name: "Oregon" },
    { abbr: "NV", name: "Nevada" },
    { abbr: "CO", name: "Colorado" },
    { abbr: "NE", name: "Nebraska" },
    { abbr: "MO", name: "Missouri" },
    { abbr: "KY", name: "Kentucky" },
    { abbr: "WV", name: "West Virgina" },
    { abbr: "VA", name: "Virginia" },
    { abbr: "MD", name: "Maryland" },
    { abbr: "DE", name: "Delaware"},

    { abbr: "CA", name: "California" },
    { abbr: "UT", name: "Utah" },
    { abbr: "NM", name: "New Mexico" },
    { abbr: "KS", name: "Kansas" },
    { abbr: "AR", name: "Arkansas" },
    { abbr: "TN", name: "Tennessee" },
    { abbr: "NC", name: "North Carolina" },
    { abbr: "SC", name: "South Carolina" },
    { abbr: "DC", name: "District of Columbia"},

    { abbr: "AZ", name: "Arizona" },
    { abbr: "OK", name: "Oklahoma" },
    { abbr: "LA", name: "Louisiana" },
    { abbr: "MS", name: "Mississippi" },
    { abbr: "AL", name: "Alabama" },
    { abbr: "GA", name: "Georgia"},

    { abbr: "HI", name: "Hawaii" },
    { abbr: "TX", name: "Texas" },
    { abbr: "FL", name: "Florida" }
  ];

  // Process data
  ns.data = []
  // hexagon shape variables
  var hex_di = 100
  var hex_rad = hex_di / 2
  // apothem
  var hex_apo = hex_rad * Math.cos(Math.PI / 6)
  // initial x
  var x = hex_rad / 2
  // initial y
  var y = hex_rad
  // constants
  var pi_six = Math.PI/6;
  var cos_six = Math.cos(pi_six);
  var sin_six = Math.sin(pi_six);
  // loop variables
  var offset = false
  // initial state index
  var state_index = 0
  var i, loop_x, loc_x, s, grid_plot, item
  for(i = 0; i < ns.matrix.length; i++) {
    loop_x = offset ? hex_apo * 2 : hex_apo;

    loc_x = x;
    for(s = 0; s < ns.matrix[i].length; s++) {
      // grid plot in 0 and 1 array
      grid_plot = ns.matrix[i][s];

      // if we have a plot in the grid
      if (grid_plot != 0) {
        // get the state
        item = ns.states[state_index];

        // hexagon polygon points
        item.hex = [
          [loc_x + loop_x, y - hex_rad],
          [loc_x + loop_x + cos_six * hex_rad, y - sin_six * hex_rad],
          [loc_x + loop_x + cos_six * hex_rad, y + sin_six * hex_rad],
          [loc_x + loop_x, y + hex_rad],
          [loc_x + loop_x - cos_six * hex_rad, y + sin_six * hex_rad],
          [loc_x + loop_x - cos_six * hex_rad, y - sin_six * hex_rad],
          [loc_x + loop_x, y - hex_rad]
        ]

        // stats
        item.xExtent = d3.extent(item.hex.map(function(d){return d[0]}))
        item.yExtent = d3.extent(item.hex.map(function(d){return d[1]}))
        item.x = ( item.xExtent[0] + item.xExtent[1] ) / 2
        item.y = ( item.yExtent[0] + item.yExtent[1] ) / 2

        ns.data.push(item);

        // increase the state index reference
        state_index++;
      }

      // move our x plot to next hex position
      loc_x += hex_apo * 2;
    }
    // move our y plot to next row position
    y += hex_di * 0.75;
    // toggle offset per row
    offset = !offset;
  }

  return ns;
})

// FR Hex tiling
.factory('frRegionsHex', function () {
  // Namespace
  var ns = {};

  ns.matrix = [
    [0,0,1,0,0,0],
    [0,1,1,1,0,0],
    [1,1,1,1,1,0],
    [1,1,1,1,0,0],
    [0,1,1,1,1,0],
    [1,1,1,1,0,0],
    [0,0,0,0,0,1]
  ];

  ns.regions = [
    { abbr: "NPC", name: "Nord-Pas-de-Calais" },

    { abbr: "HNO", name: "Haute-Normandie" },
    { abbr: "PIC", name: "Picardie"},
    { abbr: "LOR", name: "Lorraine" },

    { abbr: "BRE", name: "Bretagne" },
    { abbr: "BNO", name: "Basse Normandie" },
    { abbr: "IDF", name: "Île-de-France" },
    { abbr: "CHA", name: "Champagne-Ardenne" },
    { abbr: "ALS", name: "Alsace" },

    { abbr: "PDL", name: "Pays-de-la-Loire" },
    { abbr: "CEN", name: "Centre" },
    { abbr: "BOU", name: "Bourgogne"},
    { abbr: "FRC", name: "Franche-Comté" },

    { abbr: "POI", name: "Poitou-Charentes" },
    { abbr: "LIM", name: "Limousin" },
    { abbr: "AUV", name: "Auvergne" },
    { abbr: "RHA", name: "Rhône-Alpes" },

    { abbr: "AQU", name: "Aquitaine" },
    { abbr: "MID", name: "Midi-Pyrénées" },
    { abbr: "LAN", name: "Languedoc-Roussillon" },
    { abbr: "PAC", name: "Provence-Alpes-Côte d'Azur" },

    { abbr: "COR", name: "Corse"}
  ];

  // Process data
  ns.data = []
  // hexagon shape variables
  var hex_di = 100
  var hex_rad = hex_di / 2
  // apothem
  var hex_apo = hex_rad * Math.cos(Math.PI / 6)
  // initial x
  var x = hex_rad / 2
  // initial y
  var y = hex_rad
  // constants
  var pi_six = Math.PI/6;
  var cos_six = Math.cos(pi_six);
  var sin_six = Math.sin(pi_six);
  // loop variables
  var offset = false
  // initial state index
  var state_index = 0
  var i, loop_x, loc_x, s, grid_plot, item
  for(i = 0; i < ns.matrix.length; i++) {
    loop_x = offset ? hex_apo * 2 : hex_apo;

    loc_x = x;
    for(s = 0; s < ns.matrix[i].length; s++) {
      // grid plot in 0 and 1 array
      grid_plot = ns.matrix[i][s];

      // if we have a plot in the grid
      if (grid_plot != 0) {
        // get the state
        item = ns.regions[state_index];

        // hexagon polygon points
        item.hex = [
          [loc_x + loop_x, y - hex_rad],
          [loc_x + loop_x + cos_six * hex_rad, y - sin_six * hex_rad],
          [loc_x + loop_x + cos_six * hex_rad, y + sin_six * hex_rad],
          [loc_x + loop_x, y + hex_rad],
          [loc_x + loop_x - cos_six * hex_rad, y + sin_six * hex_rad],
          [loc_x + loop_x - cos_six * hex_rad, y - sin_six * hex_rad],
          [loc_x + loop_x, y - hex_rad]
        ]

        // stats
        item.xExtent = d3.extent(item.hex.map(function(d){return d[0]}))
        item.yExtent = d3.extent(item.hex.map(function(d){return d[1]}))
        item.x = ( item.xExtent[0] + item.xExtent[1] ) / 2
        item.y = ( item.yExtent[0] + item.yExtent[1] ) / 2

        ns.data.push(item);

        // increase the state index reference
        state_index++;
      }

      // move our x plot to next hex position
      loc_x += hex_apo * 2;
    }
    // move our y plot to next row position
    y += hex_di * 0.75;
    // toggle offset per row
    offset = !offset;
  }

  return ns;
})

// Facets declaration
.factory('Facets', function ( wellBeingAspects ,  regionsMetadata ) {
  // Namespace
  var ns = {};

  Facettage.debug = true;

  // Retrieve data from cache
  ns.coeffs = Facettage.newFacet('coefficients.csv', {
    cached: true,
    type: 'csv',
    unserialize: function (data) {
      return data.map( function (d) {
        wellBeingAspects.forEach( function (key) {
          d[key] = Number(d[key]);
        });
        return d;
      })
    }
  })

  ns.getSeries = function (country, region, topic) {
    // The name is an id as well as the path in the data cache
    // FIXME: the '/'' may not be the right path separator
    var name = region + '_' + topic + '.csv';
    // Require a facet (ie. create or get already created)
    return Facettage.requireFacet(name, {
      cached: true,
      /**
       * We use csvRows instead of csv because the first line
       * is not a header
       */
      type: 'csvRows',
      unserialize: function (data) {
        // Remove header
        data.shift();
        // Parse as numbers
        return data.map(Number);
      }
    });
  }

  return ns;
})<|endoftext|>