<commit_before>var View = require('./view.js');
var api = require('../api.js');
var $ = require('jquery');
var _ = require('lodash');
var colors = require('../colors.js');

module.exports = View.extend({

  $id          : 'address-view',

  template     : require('./templates/address-lookup.hbs'),

  multipleElections : require('./templates/partials/multiple-elections.hbs'),

  mailOnly     : require('./templates/partials/mail-only.hbs'),

  events : {
    '#plus-icon click' : 'openAboutModal',
    '#close-button click' : 'closeAboutModal',
    '#not-found-button click' : 'closeNotFoundModal',
    '#submit-address-button click' : 'submitAddress',
    '#use-current-location click' : 'useCurrentLocation',
    '#use-registered-address click' : 'useRegisteredAddress',
    '#use-different-address click' : 'useDifferentAddress',
    '#out-of-state click' : 'useRegisteredAddress',
    '#select-language change' : 'selectLanguage'
  },

  hasSubmitted: false,

  address : '',

  resizer: function () {
    // constrain container to parent width
    if (this.$container.parent().width() < this.$container.width()) {
      this.$container.width(this.$container.parent().width());
    }
  },

  onBeforeRender : function(options) {
    this.assets = options.assets;
  },

  onAfterRender : function(options) {
    this.$addressInput = this.find('#address-input');
    this.$aboutModal = this.find('#about');
    this.$notFoundModal = this.find('#address-not-found');
    this.$currentLocationModal = this.find('#current-location');
    this.$fade = this.find('#fade');
    this.$loading = this.find('.loading');
    this.$outOfStateModal = this.find('#out-of-state');
    this.$selectLanguage = this.find('#select-language');

    // set theme
    if (options.theme)
      this.$el.css({background: "url(" + options.theme + ") no-repeat 50% 0"});

    // set container dimensions
    this.$container.css({
      'max-width': 'none',
      'width' : options.width,
      'height' : options.height
    });

    if (options.modal) {
      this.$container.addClass('vit-modal unexpanded');
    }

    // limit user-uploaded image width
    if (this.$container.width() > 600) {
      $('#user-image').css('max-width', '85%');
    }

    // apply custom colors
    if (options.colors) {
      colors.replace(options.colors);
    }

    // handle container clicks and hide modals
    this.$container.on('click', this.containerClick.bind(this));

    this.autocomplete = new google.maps.places.Autocomplete(this.$addressInput[0], {
      types: ['address'],
      componentRestrictions: { country: 'us' }
    });

    // debounce submissions
    this.hasSubmitted = false;

    // disable fast-click for place autocomplete by listening for DOM Node
    // Insertion. PAC doesn't work with fastlick. See:
    // https://github.com/ftlabs/fastclick/issues/316
    $(document).on({
      DOMNodeInserted: function() {
        $('.pac-item, .pac-item span', this).addClass('needsclick');
      }
    }, '.pac-container');

    // bind resize event
    // note: debounce
    this.resizer();
    $(window).on('resize', this.resizer.bind(this));

    // bind autocomplete listener
    google.maps.event.addListener(this.autocomplete, 'place_changed', this.autocompleteListener.bind(this));
  },

  autocompleteListener: function () {
    // TODO: replace this with a debouncer
    if (this.hasSubmitted) return;

    if (this.autocomplete.getPlace()) {
      this.address = this.autocomplete.getPlace().formatted_address || this.autocomplete.getPlace().name;
    } else {
      this.address = this.$addressInput.val();
    }

    // OVERRIDE: if what is in the text box is lengthier than the PAC address, use the former
    if (this.address.length < this.$addressInput.val().length) {
      this.address = this.$addressInput.val();
    }

    this.hasSubmitted = true;

    this._makeRequest({
      address: this.address
    });

    this.toggleLoadingDisplay();
  },

  currentLocationAutocompleteListener: function (response) {
    var address = this.autocomplete.getPlace().formatted_address || this.autocomplete.getPlace().name;

    var stateName = (response.state && response.state.length) ? response.state[0].name : '';
    var stateAbbr = (stateName === 'Washington' ? 'WA' : 'OR');

    if (address.indexOf(stateAbbr) !== -1) {

      if (!this.autocomplete.getPlace().geometry) {

        this._geocode(this.autocomplete.getPlace().name, function(geocodedLocation) {
          $.extend(response, { currentLocation: geocodedLocation });

          this.triggerRouteEvent('addressViewSubmit', response);
        }.bind(this))

      } else {
        var location = this.autocomplete.getPlace().geometry.location;

        $.extend(response, { currentLocation: location });

        this.triggerRouteEvent('addressViewSubmit', response);
      }

      this.toggleLoadingDisplay();
    } else {

      this.$loading.hide();
      this.$currentLocationModal.hide();
      this.$outOfStateModal.fadeIn('fast')
    }
  },

  submitAddress: function () {
    google.maps.event.trigger(this.autocomplete, 'place_changed');
  },

  onRemove: function() {
    this.$container.removeClass('unexpanded');

    google.maps.event.clearInstanceListeners(this.autocomplete);
  },

  handleElectionData: function(response) {
    console.log(response)
    this.response = response;

    var stateName = _.get(this.response, 'state[0].name');
    if (stateName === 'Washington' || stateName === 'Oregon') {
      this.showCurrentLocationModal();
    } else if (response.mailOnly) {
      this.showMailOnlyModal();
    } else if (response.otherElections) {
      this.showMultipleElectionsModal();
    } else this.triggerRouteEvent('addressViewSubmit', response);
  },

  submitElection: function () {
    var $elections = this.$multipleElectionsModal.find('.election');
    var $selected = $elections.filter('.selected');

    this.electionId = $selected.find('.election-id').text();

    this._makeRequest({
      address: this._parseAddress(this.response.normalizedInput),
      success: function(newResponse) {
        this.triggerRouteEvent('addressViewSubmit', newResponse);
      }.bind(this)
    });
  },

  selectElection: function (event) {
    var $elections = this.$multipleElectionsModal.find('.election');

    $elections.removeClass('selected');
    $(event.currentTarget).addClass('selected');

    event.stopPropagation();
  },

  openAboutModal: function (event) {
    this.$fade.fadeTo('fast', .2);
    this.$aboutModal.fadeIn('fast');

    event.stopPropagation();
  },

  closeAboutModal: function() {
    this.$aboutModal.fadeOut('fast');
    this.$fade.fadeOut('fast');
  },

  closeNotFoundModal: function() {
    this.$notFoundModal.hide();
    this.$fade.fadeOut('fast');
  },

  containerClick: function (event) {
    var $target = $(event.target);

    if (!$target.hasClass('modal') && !$target.parents('.modal').length > 0) {
      this.$aboutModal.hide();
      this.$notFoundModal.hide();
      this.$currentLocationModal.hide();
      this.$fade.fadeOut('fast');
    }
  },

  showMultipleElectionsModal: function () {
    this.$multipleElectionsModal = $(this.multipleElections({
      data: this.response,
      assets: this.assets
    }));

    var $elections = this.$multipleElectionsModal.find('.election');
    var $select = this.$multipleElectionsModal.find('button');

    $elections.on('click', this.selectElection.bind(this));
    $select.on('click', this.submitElection.bind(this));

    this.$el.append(this.$multipleElectionsModal);

    this.$multipleElectionsModal.fadeIn();
    this.$fade.fadeTo('fast', .2);
  },

  showCurrentLocationModal: function () {
    this.$currentLocationModal.fadeIn();
    this.$fade.fadeTo('fast', .2);
    this.$loading.hide();
  },

  showMailOnlyModal: function () {
    var $mailOnly = $(this.mailOnly(this.response));

    $mailOnly.find('button').on('click', this.useRegisteredAddress.bind(this));

    this.$el.append($mailOnly);
    $mailOnly.fadeIn();

    this.$fade.fadeTo('fast', .2);
    this.$loading.hide();
  },

  useCurrentLocation: function () {
    this.$currentLocationModal.fadeOut();
    this.$loading.show();

    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var lat = _.get(position, 'coords.latitude');
        var lng = _.get(position, 'coords.longitude');
        this._reverseGeocode(lat, lng,
          this._makeRequestWithCurrentLocation.bind(this, lat, lng));
      }.bind(this));
    } else {
      this.triggerRouteEvent('addressViewRerender');
    }
  },

  useRegisteredAddress: function () {
    this.triggerRouteEvent('addressViewSubmit', this.response);
  },

  useDifferentAddress: function () {
    var newInput = $('<input>')
      .attr('type', 'text')
      .attr('placeholder', "Enter a different address")
      .css('margin', '10px 0 0')
      .insertBefore('#current-location span');

    this.autocomplete = new google.maps.places.Autocomplete(newInput[0], {
      types: ['address'],
      componentRestrictions: { country: 'us' }
    });

    google.maps.event.addListener(this.autocomplete, 'place_changed', that.currentLocationAutocompleteListener.bind(that, response));
  },

  selectLanguage: function () {
    var selectedLanguage = this.$selectLanguage.val();

    this.triggerRouteEvent('addressViewRerender', selectedLanguage);
  },

  _reverseGeocode: function(lat, lng, callback) {
    var latLng = new google.maps.LatLng(lat, lng);
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'latLng': latLng
    }, function(results, status) {
      if (status === google.maps.GeocoderStatus.OK && results.length)
        callback(results[0].formatted_address);
    })
  },

  _makeRequestWithCurrentLocation: function (lat, lng, address) {
    var stateName = _.get(this.response, 'state[0].name');
    var stateAbbr = (stateName === 'Washington' ? 'WA' : 'OR');

    if (address.indexOf(stateAbbr) !== -1) {
      var currentLocation = new google.maps.LatLng(lat, lng);
      $.extend(this.response, { currentLocation: currentLocation });
      this.triggerRouteEvent('addressViewSubmit', this.response);
    } else {
      this.$loading.hide();
      this.$outOfStateModal.fadeIn()
    }
  }
});
<commit_msg>use registered address in the event of geolocation failure<commit_after>var View = require('./view.js');
var api = require('../api.js');
var $ = require('jquery');
var _ = require('lodash');
var colors = require('../colors.js');

module.exports = View.extend({

  $id          : 'address-view',

  template     : require('./templates/address-lookup.hbs'),

  multipleElections : require('./templates/partials/multiple-elections.hbs'),

  mailOnly     : require('./templates/partials/mail-only.hbs'),

  events : {
    '#plus-icon click' : 'openAboutModal',
    '#close-button click' : 'closeAboutModal',
    '#not-found-button click' : 'closeNotFoundModal',
    '#submit-address-button click' : 'submitAddress',
    '#use-current-location click' : 'useCurrentLocation',
    '#use-registered-address click' : 'useRegisteredAddress',
    '#use-different-address click' : 'useDifferentAddress',
    '#out-of-state click' : 'useRegisteredAddress',
    '#select-language change' : 'selectLanguage'
  },

  hasSubmitted: false,

  address : '',

  resizer: function () {
    // constrain container to parent width
    if (this.$container.parent().width() < this.$container.width()) {
      this.$container.width(this.$container.parent().width());
    }
  },

  onBeforeRender : function(options) {
    this.assets = options.assets;
  },

  onAfterRender : function(options) {
    this.$addressInput = this.find('#address-input');
    this.$aboutModal = this.find('#about');
    this.$notFoundModal = this.find('#address-not-found');
    this.$currentLocationModal = this.find('#current-location');
    this.$fade = this.find('#fade');
    this.$loading = this.find('.loading');
    this.$outOfStateModal = this.find('#out-of-state');
    this.$selectLanguage = this.find('#select-language');

    // set theme
    if (options.theme)
      this.$el.css({background: "url(" + options.theme + ") no-repeat 50% 0"});

    // set container dimensions
    this.$container.css({
      'max-width': 'none',
      'width' : options.width,
      'height' : options.height
    });

    if (options.modal) {
      this.$container.addClass('vit-modal unexpanded');
    }

    // limit user-uploaded image width
    if (this.$container.width() > 600) {
      $('#user-image').css('max-width', '85%');
    }

    // apply custom colors
    if (options.colors) {
      colors.replace(options.colors);
    }

    // handle container clicks and hide modals
    this.$container.on('click', this.containerClick.bind(this));

    this.autocomplete = new google.maps.places.Autocomplete(this.$addressInput[0], {
      types: ['address'],
      componentRestrictions: { country: 'us' }
    });

    // debounce submissions
    this.hasSubmitted = false;

    // disable fast-click for place autocomplete by listening for DOM Node
    // Insertion. PAC doesn't work with fastlick. See:
    // https://github.com/ftlabs/fastclick/issues/316
    $(document).on({
      DOMNodeInserted: function() {
        $('.pac-item, .pac-item span', this).addClass('needsclick');
      }
    }, '.pac-container');

    // bind resize event
    // note: debounce
    this.resizer();
    $(window).on('resize', this.resizer.bind(this));

    // bind autocomplete listener
    google.maps.event.addListener(this.autocomplete, 'place_changed', this.autocompleteListener.bind(this));
  },

  autocompleteListener: function () {
    // TODO: replace this with a debouncer
    if (this.hasSubmitted) return;

    if (this.autocomplete.getPlace()) {
      this.address = this.autocomplete.getPlace().formatted_address || this.autocomplete.getPlace().name;
    } else {
      this.address = this.$addressInput.val();
    }

    // OVERRIDE: if what is in the text box is lengthier than the PAC address, use the former
    if (this.address.length < this.$addressInput.val().length) {
      this.address = this.$addressInput.val();
    }

    this.hasSubmitted = true;

    this._makeRequest({
      address: this.address
    });

    this.toggleLoadingDisplay();
  },

  currentLocationAutocompleteListener: function (response) {
    var address = this.autocomplete.getPlace().formatted_address || this.autocomplete.getPlace().name;

    var stateName = (response.state && response.state.length) ? response.state[0].name : '';
    var stateAbbr = (stateName === 'Washington' ? 'WA' : 'OR');

    if (address.indexOf(stateAbbr) !== -1) {

      if (!this.autocomplete.getPlace().geometry) {

        this._geocode(this.autocomplete.getPlace().name, function(geocodedLocation) {
          $.extend(response, { currentLocation: geocodedLocation });

          this.triggerRouteEvent('addressViewSubmit', response);
        }.bind(this))

      } else {
        var location = this.autocomplete.getPlace().geometry.location;

        $.extend(response, { currentLocation: location });

        this.triggerRouteEvent('addressViewSubmit', response);
      }

      this.toggleLoadingDisplay();
    } else {

      this.$loading.hide();
      this.$currentLocationModal.hide();
      this.$outOfStateModal.fadeIn('fast')
    }
  },

  submitAddress: function () {
    google.maps.event.trigger(this.autocomplete, 'place_changed');
  },

  onRemove: function() {
    this.$container.removeClass('unexpanded');

    google.maps.event.clearInstanceListeners(this.autocomplete);
  },

  handleElectionData: function(response) {
    console.log(response)
    this.response = response;

    var stateName = _.get(this.response, 'state[0].name');
    if (stateName === 'Washington' || stateName === 'Oregon') {
      this.showCurrentLocationModal();
    } else if (response.mailOnly) {
      this.showMailOnlyModal();
    } else if (response.otherElections) {
      this.showMultipleElectionsModal();
    } else this.triggerRouteEvent('addressViewSubmit', response);
  },

  submitElection: function () {
    var $elections = this.$multipleElectionsModal.find('.election');
    var $selected = $elections.filter('.selected');

    this.electionId = $selected.find('.election-id').text();

    this._makeRequest({
      address: this._parseAddress(this.response.normalizedInput),
      success: function(newResponse) {
        this.triggerRouteEvent('addressViewSubmit', newResponse);
      }.bind(this)
    });
  },

  selectElection: function (event) {
    var $elections = this.$multipleElectionsModal.find('.election');

    $elections.removeClass('selected');
    $(event.currentTarget).addClass('selected');

    event.stopPropagation();
  },

  openAboutModal: function (event) {
    this.$fade.fadeTo('fast', .2);
    this.$aboutModal.fadeIn('fast');

    event.stopPropagation();
  },

  closeAboutModal: function() {
    this.$aboutModal.fadeOut('fast');
    this.$fade.fadeOut('fast');
  },

  closeNotFoundModal: function() {
    this.$notFoundModal.hide();
    this.$fade.fadeOut('fast');
  },

  containerClick: function (event) {
    var $target = $(event.target);

    if (!$target.hasClass('modal') && !$target.parents('.modal').length > 0) {
      this.$aboutModal.hide();
      this.$notFoundModal.hide();
      this.$currentLocationModal.hide();
      this.$fade.fadeOut('fast');
    }
  },

  showMultipleElectionsModal: function () {
    this.$multipleElectionsModal = $(this.multipleElections({
      data: this.response,
      assets: this.assets
    }));

    var $elections = this.$multipleElectionsModal.find('.election');
    var $select = this.$multipleElectionsModal.find('button');

    $elections.on('click', this.selectElection.bind(this));
    $select.on('click', this.submitElection.bind(this));

    this.$el.append(this.$multipleElectionsModal);

    this.$multipleElectionsModal.fadeIn();
    this.$fade.fadeTo('fast', .2);
  },

  showCurrentLocationModal: function () {
    this.$currentLocationModal.fadeIn();
    this.$fade.fadeTo('fast', .2);
    this.$loading.hide();
  },

  showMailOnlyModal: function () {
    var $mailOnly = $(this.mailOnly(this.response));

    $mailOnly.find('button').on('click', this.useRegisteredAddress.bind(this));

    this.$el.append($mailOnly);
    $mailOnly.fadeIn();

    this.$fade.fadeTo('fast', .2);
    this.$loading.hide();
  },

  useCurrentLocation: function () {
    this.$currentLocationModal.fadeOut();
    this.$loading.show();

    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var lat = _.get(position, 'coords.latitude');
        var lng = _.get(position, 'coords.longitude');
        this._reverseGeocode(lat, lng,
          this._makeRequestWithCurrentLocation.bind(this, lat, lng));
      }.bind(this), this.useRegisteredAddress.bind(this));
    } else {
      this.triggerRouteEvent('addressViewRerender');
    }
  },

  useRegisteredAddress: function () {
    this.triggerRouteEvent('addressViewSubmit', this.response);
  },

  useDifferentAddress: function () {
    var newInput = $('<input>')
      .attr('type', 'text')
      .attr('placeholder', "Enter a different address")
      .css('margin', '10px 0 0')
      .insertBefore('#current-location span');

    this.autocomplete = new google.maps.places.Autocomplete(newInput[0], {
      types: ['address'],
      componentRestrictions: { country: 'us' }
    });

    google.maps.event.addListener(this.autocomplete, 'place_changed', that.currentLocationAutocompleteListener.bind(that, response));
  },

  selectLanguage: function () {
    var selectedLanguage = this.$selectLanguage.val();

    this.triggerRouteEvent('addressViewRerender', selectedLanguage);
  },

  _reverseGeocode: function(lat, lng, callback) {
    var latLng = new google.maps.LatLng(lat, lng);
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'latLng': latLng
    }, function(results, status) {
      if (status === google.maps.GeocoderStatus.OK && results.length)
        callback(results[0].formatted_address);
    })
  },

  _makeRequestWithCurrentLocation: function (lat, lng, address) {
    var stateName = _.get(this.response, 'state[0].name');
    var stateAbbr = (stateName === 'Washington' ? 'WA' : 'OR');

    if (address.indexOf(stateAbbr) !== -1) {
      var currentLocation = new google.maps.LatLng(lat, lng);
      $.extend(this.response, { currentLocation: currentLocation });
      this.triggerRouteEvent('addressViewSubmit', this.response);
    } else {
      this.$loading.hide();
      this.$outOfStateModal.fadeIn()
    }
  }
});
<|endoftext|>


<commit_before>import React from 'react';
import TrayContent from '../traycontent/index.js';
import Radium from 'radium';

//const bellImg = require('../../images/bell-white.png');

class DropdownTray extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        // trayControl style
        const trayControlStyle = {
          display: 'flex',
          alignItems: 'flex-end',
          marginRight: '18px',
          cursor: 'pointer',
          zIndex: '2',
          padding: '11px',

          backgroundColor: 'transparent'
        };

        // styles menu list dropdown, sets transition to/from off page
        const menuListStyle = {
          position: 'absolute',
          maxHeight: '100vh', // this
          width: '272px',
          //top: '10px',
          overflow: 'hidden',
          opacity: '1',
          zIndex: '1',
          visibility: 'visible',
          //backgroundColor: '#ffffff',
          transition: 'max-height .4s ease-in, opacity .3s ease-in'
        };

        const btnStyle = {
          position: 'absolute',
          left: '0',
          right: '0',
          top: '0',
          bottom: '2px',
          margin: '0',
          padding: '0',
          border: 'none',
          color: 'transparent',
          backgroundColor: 'transparent',
          //outline: 'none',
          cursor: 'pointer',
          width: '100%'
        };

        const contentStyle = this.props.visibleContent ?
                          {...menuListStyle} :
                          {...menuListStyle, maxHeight: '0',
                              opacity: '0',
                              visibility: 'hidden',
                              transition: 'max-height .4s ease-out, opacity .4s ease-out, visibility 1s'};

        return (

                {/*fill the controlLable span with the icon/text that user will see */}
                {console.log('control button has focus');}}>Click to Toggle Tray
                {/* use button for click handling and for accessibility */}
                <button onClick={()=>this.props.cbClickTrayControl()}
                    style={btnStyle}
                    >Click to toggle Tray</button>

              <TrayContent contentStyle={contentStyle} visibleContent={this.props.visibleContent} userName={this.props.userName} userstate={this.props.userstate}/>

        );
    }
}

DropdownTray.propTypes = {
  cbClickTrayControl : React.PropTypes.func,
  menuItems : React.PropTypes.array,
  userName : React.PropTypes.string,
  userstate : React.PropTypes.object,
  visibleContent : React.PropTypes.bool
};

export default Radium(DropdownTray);
<commit_msg>Added transition to "top" attribute<commit_after>import React from 'react';
import TrayContent from '../traycontent/index.js';
import Radium from 'radium';

//const bellImg = require('../../images/bell-white.png');

class DropdownTray extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        // trayControl style
        const trayControlStyle = {
          display: 'flex',
          alignItems: 'flex-end',
          marginRight: '18px',
          cursor: 'pointer',
          zIndex: '2',
          padding: '11px',
          backgroundColor: 'transparent'
        };

        const btnStyle = {
          position: 'absolute',
          left: '0',
          right: '0',
          top: '0',
          bottom: '2px',
          margin: '0',
          padding: '0',
          border: 'none',
          color: 'transparent',
          backgroundColor: 'transparent',
          outline: 'none',
          cursor: 'pointer',
          width: '100%'
        };

        // styles menu list dropdown, sets transition to/from off page
        const menuListStyle = {
          position: 'absolute',
          maxHeight: '100vh', // this
          width: '272px',
          top: '0px',
          overflow: 'hidden',
          opacity: '1',
          zIndex: '1',
          visibility: 'visible',
          //backgroundColor: '#ffffff',
          transition: 'max-height .4s ease-in, opacity .3s ease-in, top .2s ease-in'
        };

        const contentStyle = this.props.visibleContent ?
                          {...menuListStyle} :
                          {...menuListStyle, maxHeight: '0',
                              opacity: '0',
                              top: '-10px',
                              visibility: 'hidden',
                              transition: 'max-height .4s ease-out, opacity .4s ease-out, top .2s ease-out, visibility 1s'};

        return (

                {/*fill the controlLable span with the icon/text that user will see */}
                {console.log('control button has focus');}}>Click to Toggle Tray
                {/* use button for click handling and for accessibility */}
                <button onClick={()=>this.props.cbClickTrayControl()}
                    style={btnStyle}
                    aria-expanded={this.props.visibleContent? true : false}
                    >Click to toggle Tray</button>

              <TrayContent contentStyle={contentStyle} visibleContent={this.props.visibleContent} userName={this.props.userName} userstate={this.props.userstate}/>

        );
    }
}

DropdownTray.propTypes = {
  cbClickTrayControl : React.PropTypes.func,
  menuItems : React.PropTypes.array,
  userName : React.PropTypes.string,
  userstate : React.PropTypes.object,
  visibleContent : React.PropTypes.bool
};

export default Radium(DropdownTray);
<|endoftext|>


<commit_before>define(
  [
  ],
  function () {
    'use strict';

    return Backbone.View.extend(
      {
        initialize: function (options) {
            var data = this.$el.data();
            this.initMap([data.fromLat, data.fromLng], [data.toLat, data.toLng]);
        },
        initMap: function (from, to) {

          var mapContainer = this.$el.empty()[0];

          var leafletMap = L.map(mapContainer, {
            dragging: false,
            touchZoom: false,
            scrollWheelZoom: false,
            doubleClickZoom: false,
            boxZoom: false,
            tap: false,
            trackResize: false,
            keyboard: false,
            zoomControl: false,
            attributionControl: false,
            layers:[]
          });

          L.tileLayer(
            'http://{s}.tiles.mapbox.com/v3/{user}.{map}/{z}/{x}/{y}.png',
            {
              user: 'nakeditchyfeet',
              map: 'map-9xnn0a7i'
            }
          ).addTo(leafletMap);

          var line = L.polyline([from, to]).addTo(leafletMap);
          leafletMap.fitBounds(line.getBounds());

        },
      }
    );
  }
);<commit_msg>Dealing with it when the window is resized - making the map re-center into the correct place...<commit_after>define(
  [
  ],
  function () {
    'use strict';

    return Backbone.View.extend(
      {
        initialize: function (options) {
            var data = this.$el.data();
            this.initMap([data.fromLat, data.fromLng], [data.toLat, data.toLng]);
        },
        initMap: function (from, to) {

          var mapContainer = this.$el.empty()[0];

          var leafletMap = L.map(mapContainer, {
            animate: false,
            dragging: false,
            touchZoom: false,
            scrollWheelZoom: false,
            doubleClickZoom: false,
            boxZoom: false,
            tap: false,
            trackResize: false,
            keyboard: false,
            zoomControl: false,
            attributionControl: false,
            layers:[]
          });

          L.tileLayer(
            'http://{s}.tiles.mapbox.com/v3/{user}.{map}/{z}/{x}/{y}.png',
            {
              user: 'nakeditchyfeet',
              map: 'map-9xnn0a7i'
            }
          ).addTo(leafletMap);

          var line = L.polyline([from, to]).addTo(leafletMap);
          $(window).on('resize', _.throttle(function() {
            leafletMap.invalidateSize();
            leafletMap.fitBounds(line.getBounds());
          }, 200)).trigger('resize');
        }
      }
    );
  }
);<|endoftext|>


<commit_before>(function (window, document, $, undefined) {

    var global_information = {};
    var default_row = {};
    var defaults = {
        rows: [],
        element: null,
        template: function () {},
        children: [],
        events: {},
        count: 1,
        templates: {}
    };
    var compiled_templates = {};

    /**
     * This function generates a random number, if this number has been generated before
     * it will generate another.
     * @param  {int} length The 'length' is the number of digits in the number, defaults to 10
     * @return {int} Random number
     */
    var getID = (function (length) {
        var IDs = [undefined];

        return function () {
            for (
                var id;
                IDs.indexOf(id) > -1;
                id = Math.floor(
                    Math.random() * Math.pow(10, length || 10)
                )
            );

            return id;
        };
    })();

    /**
     * Get on object to run methods from
     * @param  {object} element Element to run the methods on
     * @return {object} Allows you to run methods
     */
    var getMethods = function (element) {

        var roles = {

            /**
             * Handle clicking the add button, add a list item.
             * @param  {event} e the event variable from the event.
             * @param  {int} index The index 1-based index of the list item that was clicked
             */
            'add': function (e, index) {
                this.add(index - 1);
                this.render();
            },

            /**
             * Handle clicking the delelete button, deletes a list item
             * @param  {event} e the event variable from the event.
             * @param  {int} index The index 1-based index of the list item that was clicked
             */
            'delete': function (e, index) {
                this['delete'](index - 1);
                this.render();
            }
        };
        var methods = {

            /**
             * Initiate the plugin.
             * @param  {string|object} selector The element to run the plugin on
             * @param  {object} options  Options for the plugin. Defaults to {}
             */
            'init': function (selector, options) {
                if (!options) options = {};

                if (!this.getInformation()) {
                    if (options.events) {
                        $.each(options.events, function (index, events) {
                            if (typeof events === 'function') {
                                options.events[index] = [events];
                            }
                        });
                    }

                    var $selector = $(selector);
                    var template_html = this.giveAttrs($selector.html());

                    var info = $.extend(true, {}, defaults, {
                        element: element
                    }, options || {});

                    this.saveInformation(info);

                    if (info.children) {

                        var children = [];

                        $.each(info.children, function (name, child) {
                            if (typeof child === 'string') {
                                child = {
                                    selector: child
                                };
                            }

                            if (!child.name) child.name = name;

                            if (!child.options) child.options = {};

                            child.element = $(child.selector);

                            children.push(child);
                        });

                        info.children = children;
                    }

                    $.each(info.templates, function (name, template) {
                        compiled_templates[name] = run.compileTemplate(template);
                    });

                    var $copy = $('<div/>').html(template_html);
                    var $elements;

                    var handler = function($elements) {
                        $elements.each(function () {
                            var $this = $(this);
                            var name = $this.data('template');
                            var template = compiled_templates[name];

                            template($this);
                        });
                    };

                    while (($elements = $copy.find('[data-template]')).length > 0) {
                        handler($elements);
                    }

                    template_html = $copy.html();
                    info.template = swig.compile(template_html);
                    this.saveInformation(info);

                    for (var i = 0, l = info.count; i < info.count; i++) {
                        this.add(i);
                    }

                    var key = this.getKey();

                    // element.on('click', '[data-role]', function(e) {
                    //     var $this = $(this),
                    //         role = $this.data('role');

                    //     if (roles[role] && $this.data('parent') === key) {
                    //         e.preventDefault();
                    //         roles[role].call(run, e, $this.data('index'));
                    //     }
                    // });
                }

                this.render();
                this.events('init');
            },

            /**
             * Generate a function to replace template placeholders
             * @param  {string|object} template The subtemplate
             * @return {function}
             */
            'compileTemplate': function (template) {
                template = this.giveAttrs(template);

                /**
                 * Replace the $element with the subtemplate
                 * @param  {object} $element Subtemplate placeholder
                 */
                return function ($element) {
                    template = run.runOnString(template, function ($ele) {
                        var $content = $ele.find('[data-content]');

                        if ($content.length > 0) {
                            var html = $element.html();

                            $content.after(html);
                            $content.remove();
                        }
                    });

                    $element.after(template);
                    $element.remove();
                };
            },

            /**
             * Run a callback on a string as if it were an element
             * @param  {string|object}   string   The string to run the callback on
             * @param  {function} callback  the callback to run
             * @return {string]}            The result of the callback
             */
            'runOnString': function (string, callback) {
                if (typeof string !== 'string') string = string.html();
                var $ele = $('<div/>').html(string);

                callback($ele);

                return $ele.html();
            },

            /**
             * Give the attributes to the elements we need to hook into
             * @param  {object|string} $element The element to find children in
             * @return {object|string}          The element after the attributes have been added
             */
            'giveAttrs': function ($element) {
                var return_text = false;

                var key = this.getKey();

                if (typeof $element === 'string') {
                    $element = $('<div/>').html($element);
                    return_text = true;
                }

                var $specials = $element.find('[value], input, button, textarea, select').each(function (i) {
                    $(this).attr('data-identifier', '{{ item.identifier }}-' + i);
                });

                $specials = $specials.add($element.find('[data-role]')).each(function () {
                    $(this).attr('data-parent', key);
                });

                $specials.add($element.find('[data-sublist]')).each(function () {
                    $(this).attr('data-index', '{{ loop.index }}');
                });

                if (return_text) {
                    $element = $element.html();
                }

                return $element;
            },

            /**
             * Add another item to list
             * @param  {int} index The index to add the item after
             */
            'add': function (index) {
                this.events('before_add');

                var info = this.getInformation();
                var row = jQuery.extend(true, {}, default_row);

                row.identifier = this.getKey() + '-' + getID();
                info.rows.splice(index + 1, 0, row);

                this.saveInformation(info);
                this.events('add', index);
            },

            /**
             * Remove an item from the list
             * @param  {int} index The index of the item to remove
             */
            'delete': function (index) {
                this.events('before_delete', index);

                var info = this.getInformation();
                info.rows.splice(index, 1);

                this.saveInformation(info);
                this.events('delete', index);
            },

            /**
             * Render the list
             * @param  {object} vars List of variables to pass to the swig template
             */
            'render': function (vars) {

                this.events('before_render');

                var info = this.getInformation();
                var children = info.children;

                var rows = {};

                var data = {};

                $.each(children, function (index, child) {
                    element.find('[data-sublist="' + child.name + '"]').each(function (index) {
                        rows[child.name + '-' + index] = $(this).list('getInformation').rows;
                    });
                });

                element.find('[data-identifier]').each(function () {
                    data[$(this).data('identifier')] = this;
                });

                var real_rows = this.getInformation().rows;

                element.html(info.template($.extend(true, {}, {
                    list: real_rows,
                    length: real_rows.length,
                    showdelete: real_rows.length > 1
                }, vars || {}, info.render_options || {})));

                this.events('render_before_fix');

                element.find('[data-role]').on('click', function (e) {

                    var $this = $(this);
                    var role = $this.data('role');

                    if ($this.data('has-assigned')) return;

                    $this.data('has-assigned', true);

                    if (roles[role]) {
                        e.preventDefault();
                        roles[role].call(run, e, $this.data('index'));
                    }
                });

                $.each(children, function (index, child) {

                    element.find('[data-sublist="' + child.name + '"]').each(function (index) {

                        var row_name = child.name + '-' + index;

                        if (!rows[row_name]) rows[row_name] = [];

                        var $this = $(this);

                        $this.list(child.element, child.options);

                        var info = $this.list('getInformation');
                        info.render_options = {
                            owner: {
                                index: $this.data('index')
                            }
                        };

                        $this.list('saveInformation', info).list('render');

                        if (rows[row_name].length > 0) {
                            info = $this.list('getInformation');
                            info.rows = rows[row_name];
                            $this.list('saveInformation', info).list('render');
                        }

                    });
                });

                $.each(data, function (identifier, ele) {
                    var $new = element.find('[data-identifier="' + identifier + '"]');

                    var $ele = $(ele);

                    if ($new.length > 0) {

                        $.each(run.attrs($new[0]), function (name, attr) {
                            if (name !== 'type') {
                                $ele.attr(name, attr);
                            }
                        });

                        $ele.insertAfter($new);
                        $new.remove();

                    }

                });

                this.events('render');

            },

            /**
             * Get the stored information about the current plugin instance.
             * @return {object} The info
             */
            'getInformation': function () {
                return global_information[this.getKey()];
            },

            /**
             * Get a key to identify the current instance
             * @return {int} The instance
             */
            'getKey': function () {
                if (!element.data('info-key')) {
                    element.data('info-key', getID());
                }

                return element.data('info-key');
            },

            /**
             * Save information about the current instance
             * @param  {object} info Information to save
             */
            'saveInformation': function (info) {
                this.events('save_info', info);
                global_information[this.getKey()] = info;
            },

            /**
             * Get key-value object of the attributes of a DOMElement
             * @param  {DOMElement} ele The element to fetch attributes from
             * @return {object}     key-value object of attributes
             */
            'attrs': function (ele) {
                ele = ele || element;
                var attrs = {};

                $.each(ele.attributes, function () {
                    attrs[this.nodeName] = this.nodeValue;
                });

                return attrs;
            },

            /**
             * Run event callbacks
             * @param {string} event_name The name of the events to run
             */
            'events': function () {
                if (arguments.length > 0) {
                    var event_name = arguments[0];
                    var info = this.getInformation();
                    var args = Array.prototype.slice.call(arguments, 1);

                    if (info && info.events[event_name]) {
                        $.each(info.events[event_name], function () {
                            this.apply(element, args);
                        });
                    }
                }
            },

            /**
             * Assign an event handler
             * @param  {string} event   the event type
             * @param  {function} handler the handler for the event
             */
            'on': function (event, handler) {
                var info = this.getInformation();

                if (!info.events[event]) info.events[event] = [];

                info.events[event].push(handler);

                this.saveInformation(info);
            },

            /**
             * Remove an event handler
             * @param  {string} event   the event type
             * @param  {function} handler the handler for the event
             */
            'off': function (event, handler) {
                var info = this.getInformation();
                if (info.events[event]) {
                    var index = info.events[event].indexOf(handler);

                    if (index > -1) {
                        info.events[event].splice(index, 1);
                    }
                }

                this.saveInformation(info);
            }
        };

        var run = function () {
            var name = Array.prototype.shift.call(arguments);

            return methods[name].apply(run, arguments);
        };

        $.each(methods, function (name) {

            run[name] = function () {

                Array.prototype.unshift.call(arguments, name);
                var args = arguments;

                return run.apply(run, args);
            };
        });

        return run;
    };

    $.fn.list = function () {

        if (arguments.length < 1) {
            Array.prototype.push.call(arguments, 'init');
        }

        var method = Array.prototype.splice.call(arguments, 0, 1)[0];

        if (!this.data('ran')) {

            this.data('ran', true);

            var selector;

            if (method !== 'init') {
                Array.prototype.unshift.call(arguments, method);
                method = 'init';
            }

            if (arguments.length < 1) {
                selector = '[type="text/swig"]';
            } else {
                selector = arguments[0];
                Array.prototype.splice.call(arguments, 0, 1);
            }

            Array.prototype.unshift.call(arguments, selector);
        }

        var result = getMethods(this)[method].apply(this, arguments);

        if (result) {
            return result;
        } else {
            return this;
        }
    };

})(window, document, jQuery);<commit_msg>Add the method runner. Fixes #7<commit_after>(function (window, document, $, undefined) {

    var global_information = {};
    var default_row = {};
    var defaults = {
        rows: [],
        element: null,
        template: function () {},
        children: [],
        events: {},
        count: 1,
        templates: {}
    };
    var compiled_templates = {};

    /**
     * This function generates a random number, if this number has been generated before
     * it will generate another.
     * @param  {int} length The 'length' is the number of digits in the number, defaults to 10
     * @return {int} Random number
     */
    var getID = (function (length) {
        var IDs = [undefined];

        return function () {
            for (
                var id;
                IDs.indexOf(id) > -1;
                id = Math.floor(
                    Math.random() * Math.pow(10, length || 10)
                )
            );

            return id;
        };
    })();

    /**
     * Get on object to run methods from
     * @param  {object} element Element to run the methods on
     * @return {object} Allows you to run methods
     */
    var getMethods = function (element) {

        var roles = {

            /**
             * Handle clicking the add button, add a list item.
             * @param  {event} e the event variable from the event.
             * @param  {int} index The index 1-based index of the list item that was clicked
             */
            'add': function (e, index) {
                this.add(index - 1);
                this.render();
            },

            /**
             * Handle clicking the delelete button, deletes a list item
             * @param  {event} e the event variable from the event.
             * @param  {int} index The index 1-based index of the list item that was clicked
             */
            'delete': function (e, index) {
                this['delete'](index - 1);
                this.render();
            }
        };
        var methods = {

            /**
             * Initiate the plugin.
             * @param  {string|object} selector The element to run the plugin on
             * @param  {object} options  Options for the plugin. Defaults to {}
             */
            'init': function (selector, options) {
                if (!options) options = {};

                if (!this.getInformation()) {
                    if (options.events) {
                        $.each(options.events, function (index, events) {
                            if (typeof events === 'function') {
                                options.events[index] = [events];
                            }
                        });
                    }

                    var $selector = $(selector);
                    var template_html = this.giveAttrs($selector.html());

                    var info = $.extend(true, {}, defaults, {
                        element: element
                    }, options || {});

                    this.saveInformation(info);

                    if (info.children) {

                        var children = [];

                        $.each(info.children, function (name, child) {
                            if (typeof child === 'string') {
                                child = {
                                    selector: child
                                };
                            }

                            if (!child.name) child.name = name;

                            if (!child.options) child.options = {};

                            child.element = $(child.selector);

                            children.push(child);
                        });

                        info.children = children;
                    }

                    $.each(info.templates, function (name, template) {
                        compiled_templates[name] = run.compileTemplate(template);
                    });

                    var $copy = $('<div/>').html(template_html);
                    var $elements;

                    var handler = function($elements) {
                        $elements.each(function () {
                            var $this = $(this);
                            var name = $this.data('template');
                            var template = compiled_templates[name];

                            template($this);
                        });
                    };

                    while (($elements = $copy.find('[data-template]')).length > 0) {
                        handler($elements);
                    }

                    template_html = $copy.html();
                    info.template = swig.compile(template_html);
                    this.saveInformation(info);

                    for (var i = 0, l = info.count; i < info.count; i++) {
                        this.add(i);
                    }

                    var key = this.getKey();

                    // element.on('click', '[data-role]', function(e) {
                    //     var $this = $(this),
                    //         role = $this.data('role');

                    //     if (roles[role] && $this.data('parent') === key) {
                    //         e.preventDefault();
                    //         roles[role].call(run, e, $this.data('index'));
                    //     }
                    // });
                }

                this.render();
                this.events('init');
            },

            /**
             * Generate a function to replace template placeholders
             * @param  {string|object} template The subtemplate
             * @return {function}
             */
            'compileTemplate': function (template) {
                template = this.giveAttrs(template);

                /**
                 * Replace the $element with the subtemplate
                 * @param  {object} $element Subtemplate placeholder
                 */
                return function ($element) {
                    template = run.runOnString(template, function ($ele) {
                        var $content = $ele.find('[data-content]');

                        if ($content.length > 0) {
                            var html = $element.html();

                            $content.after(html);
                            $content.remove();
                        }
                    });

                    $element.after(template);
                    $element.remove();
                };
            },

            /**
             * Run a callback on a string as if it were an element
             * @param  {string|object}   string   The string to run the callback on
             * @param  {function} callback  the callback to run
             * @return {string]}            The result of the callback
             */
            'runOnString': function (string, callback) {
                if (typeof string !== 'string') string = string.html();
                var $ele = $('<div/>').html(string);

                callback($ele);

                return $ele.html();
            },

            /**
             * Give the attributes to the elements we need to hook into
             * @param  {object|string} $element The element to find children in
             * @return {object|string}          The element after the attributes have been added
             */
            'giveAttrs': function ($element) {
                var return_text = false;

                var key = this.getKey();

                if (typeof $element === 'string') {
                    $element = $('<div/>').html($element);
                    return_text = true;
                }

                var $specials = $element.find('[value], input, button, textarea, select').each(function (i) {
                    $(this).attr('data-identifier', '{{ item.identifier }}-' + i);
                });

                $specials = $specials.add($element.find('[data-role]')).each(function () {
                    $(this).attr('data-parent', key);
                });

                $specials.add($element.find('[data-sublist]')).each(function () {
                    $(this).attr('data-index', '{{ loop.index }}');
                });

                if (return_text) {
                    $element = $element.html();
                }

                return $element;
            },

            /**
             * Add another item to list
             * @param  {int} index The index to add the item after
             */
            'add': function (index) {
                this.events('before_add');

                var info = this.getInformation();
                var row = jQuery.extend(true, {}, default_row);

                row.identifier = this.getKey() + '-' + getID();
                info.rows.splice(index + 1, 0, row);

                this.saveInformation(info);
                this.events('add', index);
            },

            /**
             * Remove an item from the list
             * @param  {int} index The index of the item to remove
             */
            'delete': function (index) {
                this.events('before_delete', index);

                var info = this.getInformation();
                info.rows.splice(index, 1);

                this.saveInformation(info);
                this.events('delete', index);
            },

            /**
             * Render the list
             * @param  {object} vars List of variables to pass to the swig template
             */
            'render': function (vars) {

                this.events('before_render');

                var info = this.getInformation();
                var children = info.children;

                var rows = {};

                var data = {};

                $.each(children, function (index, child) {
                    element.find('[data-sublist="' + child.name + '"]').each(function (index) {
                        rows[child.name + '-' + index] = $(this).list('getInformation').rows;
                    });
                });

                element.find('[data-identifier]').each(function () {
                    data[$(this).data('identifier')] = this;
                });

                var real_rows = this.getInformation().rows;

                element.html(info.template($.extend(true, {}, {
                    list: real_rows,
                    length: real_rows.length,
                    showdelete: real_rows.length > 1
                }, vars || {}, info.render_options || {})));

                this.events('render_before_fix');

                element.find('[data-role]').on('click', function (e) {

                    var $this = $(this);
                    var role = $this.data('role');

                    if ($this.data('has-assigned')) return;

                    $this.data('has-assigned', true);

                    if (roles[role]) {
                        e.preventDefault();
                        roles[role].call(run, e, $this.data('index'));
                    }
                });

                $.each(children, function (index, child) {

                    element.find('[data-sublist="' + child.name + '"]').each(function (index) {

                        var row_name = child.name + '-' + index;

                        if (!rows[row_name]) rows[row_name] = [];

                        var $this = $(this);

                        $this.list(child.element, child.options);

                        var info = $this.list('getInformation');
                        info.render_options = {
                            owner: {
                                index: $this.data('index')
                            }
                        };

                        $this.list('saveInformation', info).list('render');

                        if (rows[row_name].length > 0) {
                            info = $this.list('getInformation');
                            info.rows = rows[row_name];
                            $this.list('saveInformation', info).list('render');
                        }

                    });
                });

                $.each(data, function (identifier, ele) {
                    var $new = element.find('[data-identifier="' + identifier + '"]');

                    var $ele = $(ele);

                    if ($new.length > 0) {

                        $.each(run.attrs($new[0]), function (name, attr) {
                            if (name !== 'type') {
                                $ele.attr(name, attr);
                            }
                        });

                        $ele.insertAfter($new);
                        $new.remove();

                    }

                });

                this.events('render');

            },

            /**
             * Get the stored information about the current plugin instance.
             * @return {object} The info
             */
            'getInformation': function () {
                return global_information[this.getKey()];
            },

            /**
             * Get a key to identify the current instance
             * @return {int} The instance
             */
            'getKey': function () {
                if (!element.data('info-key')) {
                    element.data('info-key', getID());
                }

                return element.data('info-key');
            },

            /**
             * Save information about the current instance
             * @param  {object} info Information to save
             */
            'saveInformation': function (info) {
                this.events('save_info', info);
                global_information[this.getKey()] = info;
            },

            /**
             * Get key-value object of the attributes of a DOMElement
             * @param  {DOMElement} ele The element to fetch attributes from
             * @return {object}     key-value object of attributes
             */
            'attrs': function (ele) {
                ele = ele || element;
                var attrs = {};

                $.each(ele.attributes, function () {
                    attrs[this.nodeName] = this.nodeValue;
                });

                return attrs;
            },

            /**
             * Run event callbacks
             * @param {string} event_name The name of the events to run
             */
            'events': function () {
                if (arguments.length > 0) {
                    var event_name = arguments[0];
                    var info = this.getInformation();
                    var args = Array.prototype.slice.call(arguments, 1);

                    if (info && info.events[event_name]) {
                        $.each(info.events[event_name], function () {
                            this.apply(element, args);
                        });
                    }
                }
            },

            /**
             * Assign an event handler
             * @param  {string} event   the event type
             * @param  {function} handler the handler for the event
             */
            'on': function (event, handler) {
                var info = this.getInformation();

                if (!info.events[event]) info.events[event] = [];

                info.events[event].push(handler);

                this.saveInformation(info);
            },

            /**
             * Remove an event handler
             * @param  {string} event   the event type
             * @param  {function} handler the handler for the event
             */
            'off': function (event, handler) {
                var info = this.getInformation();
                if (info.events[event]) {
                    var index = info.events[event].indexOf(handler);

                    if (index > -1) {
                        info.events[event].splice(index, 1);
                    }
                }

                this.saveInformation(info);
            },

            /**
             * Grab the method runner
             * @return {object} Method runner.
             */
            'methodRunner': function() {
                return run;
            }
        };

        var run = function () {
            var name = Array.prototype.shift.call(arguments);

            return methods[name].apply(run, arguments);
        };

        $.each(methods, function (name) {

            run[name] = function () {

                Array.prototype.unshift.call(arguments, name);
                var args = arguments;

                return run.apply(run, args);
            };
        });

        return run;
    };

    $.fn.list = function () {

        if (arguments.length < 1) {
            Array.prototype.push.call(arguments, 'init');
        }

        var method = Array.prototype.splice.call(arguments, 0, 1)[0];

        if (!this.data('ran')) {

            this.data('ran', true);

            var selector;

            if (method !== 'init') {
                Array.prototype.unshift.call(arguments, method);
                method = 'init';
            }

            if (arguments.length < 1) {
                selector = '[type="text/swig"]';
            } else {
                selector = arguments[0];
                Array.prototype.splice.call(arguments, 0, 1);
            }

            Array.prototype.unshift.call(arguments, selector);
        }

        var result = getMethods(this)[method].apply(this, arguments);

        if (result) {
            return result;
        } else {
            return this;
        }
    };

})(window, document, jQuery);<|endoftext|>


<commit_before>var injector    = require( 'injector' )
  , utils       = require( 'utils' )
  , async       = require( 'async' )
  , config      = require( 'config' )
  , path        = require( 'path' )
  , ormUtils    = require( path.resolve( path.join( __dirname, '..', 'lib', 'utils.js' ) ) )
  , env         = utils.bootstrapEnv()
  , moduleLdr   = env.moduleLoader;

// Rebase once our modules have loaded
moduleLdr.on( 'modulesLoaded', function() {
    var sequelize = injector.getInstance( 'sequelize' );

    console.log('Forcing Database to be created! (Note: All your data will disapear!)');
    async.waterfall(
        [
            function createDatabase( callback ) {
                var query = 'CREATE DATABASE ' + ( config[ 'clever-orm' ].db.options.dialect === 'mysql' ? 'IF NOT EXISTS ' : '' ) + config[ 'clever-orm' ].db.database;

                sequelize.query( query, { raw: true } )
                    .success( function() {
                        callback( null );
                    })
                    .error( callback );
            },

            function rebaseDatabase( callback ) {
                sequelize
                    .sync( { force: true } )
                    .success( function() {
                        callback( null );
                    })
                    .error( callback );
            }
        ],
        function shutdown( err ) {
            if ( err === null ) {
                console.log( 'Database is rebased' );
                process.exit( 0 );
            } else {
                console.error('Error ' + env.config['clever-orm'].db.options.dialect, err);
                process.exit( 1 );
            }
        }
    );
});

ormUtils.supportSingleModule( env, process.argv && process.argv[ 2 ] != 'null' ? process.argv[ 2 ] : false );

// Load
moduleLdr.loadModules();<commit_msg>fix(rebase): Updated to run dialect specific sql file inside schema folder (ie. mysql.sql)<commit_after>var injector    = require( 'injector' )
  , util        = require( 'util' )
  , utils       = require( 'utils' )
  , async       = require( 'async' )
  , config      = require( 'config' )
  , path        = require( 'path' )
  , fs          = require( 'fs' )
  , ormUtils    = require( path.resolve( path.join( __dirname, '..', 'lib', 'utils.js' ) ) )
  , env         = utils.bootstrapEnv()
  , moduleLdr   = env.moduleLoader;

console.log( 'Using configuration:' );
console.log( util.inspect( config[ 'clever-orm' ].modelAssociations ) );

// Rebase once our modules have loaded
moduleLdr.on( 'modulesLoaded', function() {
    var sequelize = injector.getInstance( 'sequelize' );

    console.log('Forcing Database to be created! (Note: All your data will disapear!)');
    async.waterfall(
        [
            function createDatabase( callback ) {
                var query = 'CREATE DATABASE ' + ( config[ 'clever-orm' ].db.options.dialect === 'mysql' ? 'IF NOT EXISTS ' : '' ) + config[ 'clever-orm' ].db.database;

                sequelize.query( query, { raw: true } )
                    .success( function() {
                        callback( null );
                    })
                    .error( callback );
            },

            function rebaseDatabase( callback ) {
                sequelize
                    .sync( { force: true } )
                    .success( function() {
                        callback( null );
                    })
                    .error( callback );
            },

            function runDialectSqlFile( callback ) {
                var dialectSqlFile = path.resolve( path.join( __dirname, '..', '..', '..', 'schema', config[ 'clever-orm' ].db.options.dialect + '.sql' ) );

                if ( fs.existsSync( dialectSqlFile ) ) {
                    fs.readFile( dialectSqlFile, function( err, sql ) {
                        if ( err || !sql ) {
                            console.log( 'No specific dialect SQL found continuing...' );
                            return callback();
                        }

                        console.log( 'Running dialect specific SQL' );
                        sequelize.query( sql.toString(), null, { raw: true } ).success(function() {
                            callback( null );
                        })
                        .error( callback );
                    });
                } else {
                    callback( null );
                }
            }
        ],
        function shutdown( err ) {
            if ( err === null ) {
                console.log( 'Database is rebased' );
                process.exit( 0 );
            } else {
                console.error('Error ' + env.config['clever-orm'].db.options.dialect, err);
                process.exit( 1 );
            }
        }
    );
});

ormUtils.supportSingleModule( env, process.argv && process.argv[ 2 ] != 'null' ? process.argv[ 2 ] : false );

// Load
moduleLdr.loadModules();<|endoftext|>


<commit_before>/*globals require, $, console, angular*/

/**
 * @author rkereskenyi / https://github.com/rkereskenyi
 * @author nabana / https://github.com/nabana
 */

var DEBUG = false,
    _jqueryVersion = '2.1.0',
    _jqueryUIVersion = '1.10.4',
    _bootsrapVersion = '3.1.1';

// configure require path and modules
require.config({
    baseUrl: '/',

    map: {
         '*': {
            'css': 'lib/require/require-css/css',
            'text': 'lib/require/require-text/text'
        }
    },

    paths: {

        'domReady':	'lib/require/require-domready/domReady',

        //jQuery and stuff
        'jquery': 'lib/jquery/jquery-' + _jqueryVersion + ( DEBUG ? '.min' : '' ),
        'jquery-ui': 'lib/jquery/jquery-ui-' + _jqueryUIVersion + ( DEBUG ? '.min' : '' ),
        'jquery-ui-iPad': 'lib/jquery/jquery.ui.ipad',
        'jquery-WebGME': 'js/jquery.WebGME',
        'jquery-dataTables': 'lib/jquery/jquery.dataTables.min',
        'jquery-dataTables-bootstrapped': 'lib/jquery/jquery.dataTables.bootstrapped',
        'jquery-spectrum': 'lib/jquery/jquery.spectrum',

        //Bootsrap stuff
        'bootstrap': 'lib/bootstrap/' + _bootsrapVersion + '/js/bootstrap' + ( DEBUG ? '.min' : '' ),

        //Other modules
        'underscore': 'lib/underscore/underscore-min',
        'backbone': 'lib/backbone/backbone.min',
        'd3': 'lib/d3/d3.v3.min',
        'jscolor': 'lib/jscolor/jscolor',
        'superagent': 'lib/superagent/superagent',

        //RaphaelJS family
        'eve': 'lib/raphael/eve',   //needed because of raphael.core.js uses require with 'eve'
        'raphaeljs': 'lib/raphael/raphael.amd',
        'raphael_core': 'lib/raphael/raphael.core',
        'raphael_svg': 'lib/raphael/raphael.svg_fixed',
        'raphael_vml': 'lib/raphael/raphael.vml',

        //WebGME custom modules
        'logManager': 'common/LogManager',
        'eventDispatcher': 'common/EventDispatcher',

        'util': 'common/util',
        'core': 'common/core',
        'coreclient': 'common/core/users',
        'storage': 'common/storage',
        'blob': 'middleware/blob',

        'notificationManager': 'js/NotificationManager',
        'clientUtil': 'js/util',
        'loaderCircles': 'js/Loader/LoaderCircles',
        'loaderProgressBar': 'js/Loader/LoaderProgressBar',

        'codemirror': 'lib/codemirror/codemirror.amd',
        'jquery-csszoom': 'lib/jquery/jquery.csszoom',

        'jszip': 'lib/jszip/jszip',

        'moment': 'lib/moment/moment.min',

        // Angular and modules
        'angular': 'lib/angular/angular-1.2.19/angular' + ( DEBUG ? '.min' : '' ),
        'angular-route': 'lib/angular/angular-1.2.19/angular-route' + ( DEBUG ? '.min' : '' ),
        'angular-route-styles': 'lib/angular/angular-route-styles/route-styles',
        'angular-ui-bootstrap': 'lib/angular/ui-bootstrap/ui-bootstrap-tpls-0.11.0.min'
    },

    shim: {

        'angular-route': ['angular'],
        'angular-route-styles': ['angular'],
        'angular-ui-bootstrap': ['angular'],

        'jquery-ui': ['jquery'],
        'jquery-ui-iPad': ['jquery','jquery-ui'],

        'bootstrap': [
            'jquery',
            'css!lib/bootstrap/' + _bootsrapVersion + '/css/bootstrap.min.css',
            'css!lib/bootstrap/' + _bootsrapVersion + '/css/bootstrap-theme.min.css'
        ],

        'backbone': ['underscore'],
        'clientUtil': ['jquery'],
        'jquery-WebGME': ['bootstrap'],
        'jquery-dataTables': ['jquery'],
        'jquery-dataTables-bootstrapped': ['jquery-dataTables'],
        'js/WebGME': [
            'jquery-WebGME',
            'css!/css/main.css',
            'css!/css/themes/dawn.css',
            //'css!/fonts/font-awesome/css/font-awesome.min.css',
            'css!/fonts/webgme-icons/style.css'
        ],
        'jquery-csszoom': ['jquery-ui'],
        'jquery-spectrum': ['jquery'],
        'raphael_svg': ['raphael_core'],
        'raphael_vml': ['raphael_core']
    }
});

require(
    [
        'domReady',
        'jquery',
        'jquery-ui',
        'jquery-ui-iPad',
        'jquery-WebGME',
        'jquery-dataTables-bootstrapped',
        'bootstrap',
        'underscore',
        'backbone',
        'js/WebGME',
        'clientUtil',
        'bin/getconfig',

        'angular',
        'angular-route',
        'angular-route-styles',
        'angular-ui-bootstrap',

        'js/services/DataStoreService'

    ],
    function (domReady, jQuery, jQueryUi, jQueryUiiPad, jqueryWebGME, jqueryDataTables, bootstrap, underscore,
              backbone, webGME, util, CONFIG) {

        'use strict';

        domReady(function () {

            if (CONFIG.hasOwnProperty('debug')) {
                DEBUG = CONFIG.debug;
            }

            var d = util.getURLParameterByName('debug').toLowerCase();
            if (d === 'true') {
                DEBUG = true;
            }

            if (CONFIG.paths) {

                // attach external libraries to extlib/*

                var keys = Object.keys(CONFIG.paths);
                for (var i = 0; i < keys.length; i += 1) {

                    // assume this is a relative path from the current working directory
                    CONFIG.paths[keys[i]] = 'extlib/' + CONFIG.paths[keys[i]];
                }

                // update client config to route the external lib requests

                require.config({
                    paths: CONFIG.paths
                });

            }

            // Extended disable function
            jQuery.fn.extend({
                disable: function(state) {
                    return this.each(function() {
                        var $this = $(this);
                        if($this.is('input, button')) {
                          this.disabled = state;
                        } else {
                          $this.toggleClass('disabled', state);
                        }
                    });
                }
            });

            // Initialize Angular. For this time no better place.
            // has to be initialized as early as possible
            var gmeApp = angular.module(
                'gmeApp', [
                    'ngRoute',
                    'routeStyles',
                    'ui.bootstrap',
                    'gme.ui.projectsDialog',
                    'gme.ui.headerPanel',

                    'gme.services'
                ]);

//            NS.getNode(context, path)
//                .then(function (node) {
//                    node.on('update', fcn1);
//
//                    return node.getChildren();
//                })
//                .then(function (children) {
//                    for (var i = 0; i < children.length; i += 1) {
//                        if (children[i].getType() === 'M12') {
//                            children[i].on('update', updateM12);
//                        }
//                    }
//                })
//            ;

            // TODO: REMOVE - ONLY FOR TESTING
            WebGMEGlobal.gmeApp = gmeApp;
            gmeApp.controller('TestController', function ($scope, DataStoreService, NodeService) {
                var context = {
                    db: 'my-db-connection-id1',
                    projectId: 'Test',
                    branchId: 'b1',
                    territoryId: 'my_terr11111'
                };

//                DataStoreService.selectProject({db: 'my-db-connection-id', projectId:'Test'})
//                    .then(function () {
//                        return DataStoreService.selectBranch({db: 'my-db-connection-id', projectId: 'Test', branchId: 'b11'});
//                    })
//                    .then(function () {
//                        console.log('ready to work with objects...', context);
//                    })
//                    .catch(function (reason) {
//                        console.error(reason);
//                    });

                DataStoreService.connectToDatabase(context)
                    .then(function () {
                        // Once we have connected to the database we can register event handlers.

                        var rootNode;

                        NodeService.on(context, 'initialize', function(currentContext) {
                            NodeService.loadNode(currentContext, '')
                                .then(function (node) {
                                    rootNode = node;
                                    console.log(node);
                                    console.log(currentContext);
                                    //console.log(c);
                                });
                        });

                        NodeService.on(context, 'destroy', function(currentContext) {
                            rootNode = null;
                        });

                        // we can select any branch
                        DataStoreService.selectBranch(context)
                            .then(function () {
                                console.log('ready to work with objects...', context);
                                NodeService.loadNode(context, '')
                                    .then(function (node) {
                                        console.log(node.getAttribute('name'));
                                    });

                            })
                            .catch(function (reason) {
                                console.error(reason);
                            });

                    });

            });

            webGME.start( function(client) {

                gmeApp.value('gmeClient', client);
//                gmeApp.value('gmeClient', null);

                angular.bootstrap(document, [ 'gmeApp']);

            });

        });
    }
);
<commit_msg>Expose context and DataStoreService for testing.<commit_after>/*globals require, $, console, angular*/

/**
 * @author rkereskenyi / https://github.com/rkereskenyi
 * @author nabana / https://github.com/nabana
 */

var DEBUG = false,
    _jqueryVersion = '2.1.0',
    _jqueryUIVersion = '1.10.4',
    _bootsrapVersion = '3.1.1';

// configure require path and modules
require.config({
    baseUrl: '/',

    map: {
         '*': {
            'css': 'lib/require/require-css/css',
            'text': 'lib/require/require-text/text'
        }
    },

    paths: {

        'domReady':	'lib/require/require-domready/domReady',

        //jQuery and stuff
        'jquery': 'lib/jquery/jquery-' + _jqueryVersion + ( DEBUG ? '.min' : '' ),
        'jquery-ui': 'lib/jquery/jquery-ui-' + _jqueryUIVersion + ( DEBUG ? '.min' : '' ),
        'jquery-ui-iPad': 'lib/jquery/jquery.ui.ipad',
        'jquery-WebGME': 'js/jquery.WebGME',
        'jquery-dataTables': 'lib/jquery/jquery.dataTables.min',
        'jquery-dataTables-bootstrapped': 'lib/jquery/jquery.dataTables.bootstrapped',
        'jquery-spectrum': 'lib/jquery/jquery.spectrum',

        //Bootsrap stuff
        'bootstrap': 'lib/bootstrap/' + _bootsrapVersion + '/js/bootstrap' + ( DEBUG ? '.min' : '' ),

        //Other modules
        'underscore': 'lib/underscore/underscore-min',
        'backbone': 'lib/backbone/backbone.min',
        'd3': 'lib/d3/d3.v3.min',
        'jscolor': 'lib/jscolor/jscolor',
        'superagent': 'lib/superagent/superagent',

        //RaphaelJS family
        'eve': 'lib/raphael/eve',   //needed because of raphael.core.js uses require with 'eve'
        'raphaeljs': 'lib/raphael/raphael.amd',
        'raphael_core': 'lib/raphael/raphael.core',
        'raphael_svg': 'lib/raphael/raphael.svg_fixed',
        'raphael_vml': 'lib/raphael/raphael.vml',

        //WebGME custom modules
        'logManager': 'common/LogManager',
        'eventDispatcher': 'common/EventDispatcher',

        'util': 'common/util',
        'core': 'common/core',
        'coreclient': 'common/core/users',
        'storage': 'common/storage',
        'blob': 'middleware/blob',

        'notificationManager': 'js/NotificationManager',
        'clientUtil': 'js/util',
        'loaderCircles': 'js/Loader/LoaderCircles',
        'loaderProgressBar': 'js/Loader/LoaderProgressBar',

        'codemirror': 'lib/codemirror/codemirror.amd',
        'jquery-csszoom': 'lib/jquery/jquery.csszoom',

        'jszip': 'lib/jszip/jszip',

        'moment': 'lib/moment/moment.min',

        // Angular and modules
        'angular': 'lib/angular/angular-1.2.19/angular' + ( DEBUG ? '.min' : '' ),
        'angular-route': 'lib/angular/angular-1.2.19/angular-route' + ( DEBUG ? '.min' : '' ),
        'angular-route-styles': 'lib/angular/angular-route-styles/route-styles',
        'angular-ui-bootstrap': 'lib/angular/ui-bootstrap/ui-bootstrap-tpls-0.11.0.min'
    },

    shim: {

        'angular-route': ['angular'],
        'angular-route-styles': ['angular'],
        'angular-ui-bootstrap': ['angular'],

        'jquery-ui': ['jquery'],
        'jquery-ui-iPad': ['jquery','jquery-ui'],

        'bootstrap': [
            'jquery',
            'css!lib/bootstrap/' + _bootsrapVersion + '/css/bootstrap.min.css',
            'css!lib/bootstrap/' + _bootsrapVersion + '/css/bootstrap-theme.min.css'
        ],

        'backbone': ['underscore'],
        'clientUtil': ['jquery'],
        'jquery-WebGME': ['bootstrap'],
        'jquery-dataTables': ['jquery'],
        'jquery-dataTables-bootstrapped': ['jquery-dataTables'],
        'js/WebGME': [
            'jquery-WebGME',
            'css!/css/main.css',
            'css!/css/themes/dawn.css',
            //'css!/fonts/font-awesome/css/font-awesome.min.css',
            'css!/fonts/webgme-icons/style.css'
        ],
        'jquery-csszoom': ['jquery-ui'],
        'jquery-spectrum': ['jquery'],
        'raphael_svg': ['raphael_core'],
        'raphael_vml': ['raphael_core']
    }
});

require(
    [
        'domReady',
        'jquery',
        'jquery-ui',
        'jquery-ui-iPad',
        'jquery-WebGME',
        'jquery-dataTables-bootstrapped',
        'bootstrap',
        'underscore',
        'backbone',
        'js/WebGME',
        'clientUtil',
        'bin/getconfig',

        'angular',
        'angular-route',
        'angular-route-styles',
        'angular-ui-bootstrap',

        'js/services/DataStoreService'

    ],
    function (domReady, jQuery, jQueryUi, jQueryUiiPad, jqueryWebGME, jqueryDataTables, bootstrap, underscore,
              backbone, webGME, util, CONFIG) {

        'use strict';

        domReady(function () {

            if (CONFIG.hasOwnProperty('debug')) {
                DEBUG = CONFIG.debug;
            }

            var d = util.getURLParameterByName('debug').toLowerCase();
            if (d === 'true') {
                DEBUG = true;
            }

            if (CONFIG.paths) {

                // attach external libraries to extlib/*

                var keys = Object.keys(CONFIG.paths);
                for (var i = 0; i < keys.length; i += 1) {

                    // assume this is a relative path from the current working directory
                    CONFIG.paths[keys[i]] = 'extlib/' + CONFIG.paths[keys[i]];
                }

                // update client config to route the external lib requests

                require.config({
                    paths: CONFIG.paths
                });

            }

            // Extended disable function
            jQuery.fn.extend({
                disable: function(state) {
                    return this.each(function() {
                        var $this = $(this);
                        if($this.is('input, button')) {
                          this.disabled = state;
                        } else {
                          $this.toggleClass('disabled', state);
                        }
                    });
                }
            });

            // Initialize Angular. For this time no better place.
            // has to be initialized as early as possible
            var gmeApp = angular.module(
                'gmeApp', [
                    'ngRoute',
                    'routeStyles',
                    'ui.bootstrap',
                    'gme.ui.projectsDialog',
                    'gme.ui.headerPanel',

                    'gme.services'
                ]);

//            NS.getNode(context, path)
//                .then(function (node) {
//                    node.on('update', fcn1);
//
//                    return node.getChildren();
//                })
//                .then(function (children) {
//                    for (var i = 0; i < children.length; i += 1) {
//                        if (children[i].getType() === 'M12') {
//                            children[i].on('update', updateM12);
//                        }
//                    }
//                })
//            ;

            // TODO: REMOVE - ONLY FOR TESTING
            WebGMEGlobal.gmeApp = gmeApp;
            gmeApp.controller('TestController', function ($scope, DataStoreService, NodeService) {
                var context = {
                    db: 'my-db-connection-id1',
                    projectId: 'Test',
                    branchId: 'b1',
                    territoryId: 'my_terr11111'
                };

                WebGMEGlobal.context = context;
                WebGMEGlobal.DataStoreService = DataStoreService;

//                DataStoreService.selectProject({db: 'my-db-connection-id', projectId:'Test'})
//                    .then(function () {
//                        return DataStoreService.selectBranch({db: 'my-db-connection-id', projectId: 'Test', branchId: 'b11'});
//                    })
//                    .then(function () {
//                        console.log('ready to work with objects...', context);
//                    })
//                    .catch(function (reason) {
//                        console.error(reason);
//                    });

                DataStoreService.connectToDatabase(context)
                    .then(function () {
                        // Once we have connected to the database we can register event handlers.

                        var rootNode;

                        NodeService.on(context, 'initialize', function(currentContext) {
                            NodeService.loadNode(currentContext, '')
                                .then(function (node) {
                                    rootNode = node;
                                    console.log(node);
                                    console.log(currentContext);
                                    //console.log(c);
                                });
                        });

                        NodeService.on(context, 'destroy', function(currentContext) {
                            rootNode = null;
                        });

                        // we can select any branch
                        DataStoreService.selectBranch(context)
                            .then(function () {
                                console.log('ready to work with objects...', context);
                                NodeService.loadNode(context, '')
                                    .then(function (node) {
                                        console.log(node.getAttribute('name'));
                                    });

                            })
                            .catch(function (reason) {
                                console.error(reason);
                            });

                    });

            });

            webGME.start( function(client) {

                gmeApp.value('gmeClient', client);
//                gmeApp.value('gmeClient', null);

                angular.bootstrap(document, [ 'gmeApp']);

            });

        });
    }
);
<|endoftext|>