<commit_before>/**
 * This code is copyright (c) 2014 Topcoder Corporation
 */

(function (window, angular, undefined) {
  'use strict';

	angular
	  .module('edit.challenge')
	  .controller('CreateChallengeController', CreateChallengeController);

	CreateChallengeController.$inject = ['$scope', '$timeout', '$filter', '$state', 'ChallengeService', 'challenge'];

	function CreateChallengeController($scope, $timeout, $filter, $state, ChallengeService, challenge) {

    $scope.challenge = challenge;
    $scope.editDescription = true;
    $scope.publicBrowsing = {
      complete: false
    }

    /*save new challenge*/
    if ($scope.challenge && !$scope.challenge.id) {
      ChallengeService.createChallenge($scope.challenge).then(function(data) {
        $state.go('edit-challenge', {challengeId: data.id});
      });
    }

    /*watch challenge object*/
    $scope.$watch('challenge', function(newVal) {
      if (newVal.title && newVal.title.trim() && newVal.overview && newVal.overview.trim() && newVal.description && newVal.description.trim()) {
        $scope.publicBrowsing.complete = true;
      } else {
        $scope.publicBrowsing.complete = false;
      }
    }, true);

    /*save current challenge and related info*/
    $scope.saveChallenge = function() {
      //reset the flag that shows the growl notification
      $scope.showSuccessGrowl = false;
      if ($scope.timeLine.complete) {
        $scope.challenge.regStartAt = concatenateDateTime($scope.timeLine.stdt, $scope.timeLine.timeSelectedStart);
        $scope.challenge.subEndAt = concatenateDateTime($scope.timeLine.enddt, $scope.timeLine.timeSelectedEnd);
      };

      if ($scope.prizes.customerAccountName) {
        $scope.challenge.account = $scope.prizes.customerAccountName;
      };
      if ($scope.prizes.customerAccountId) {
        $scope.challenge.accountId = ''+$scope.prizes.customerAccountId;
      };
      // grap prizes
      var prizes = [];
      _.each($scope.placePrizes.places, function(place) {
        if (place.active && place.prize > 0) {
          prizes.push(Number(place.prize));
        }
      });
      $scope.challenge.prizes = prizes;
      $scope.challenge.projectSource = 'TOPCODER';
      $scope.challenge.projectId = $scope.challenge.projectId;

      // update challenge info
      ChallengeService.updateChallenge($scope.challenge).then(function(actionResponse) {
        //after a successful save show the growl
        $scope.showSuccessGrowl = true;

        console.log('updated challenge: ', actionResponse.id);
      }, function(errorResponse) {
        console.log('update challenge: error: ', errorResponse);
      });

    };

    /*get accounts based on the query string*/
    $scope.accounts = [];
    function getAccounts(query) {
      // query is field=value
      ChallengeService.getAccounts(query).then(function(data) {
        $scope.accounts = data;
      });
    };

    /*get all tags and initialize the tags input and initialize the tags input*/
    $scope.tags = $scope.challenge.tags;
    var tagNames = null;
    function getAllTags() {
      ChallengeService.getAllTags().then(function(data) {
        tagNames = new Bloodhound({
          datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
          queryTokenizer: Bloodhound.tokenizers.whitespace,
          local: data
        });
        tagNames.initialize();
        $('input.tags-input').tagsinput({
          typeaheadjs: {
            name: 'tagNames',
            displayKey: 'name',
            valueKey: 'name',
            source: tagNames.ttAdapter()
          },
          freeInput: false,
        });
        $scope.$watch('tags', function(){
          $scope.challenge.tags=$("input.tags-input").tagsinput('items');
        });
      });
    };
    getAllTags();

    /*launch a challenge*/
    $scope.launch = function() {
      ChallengeService.launch($scope.challenge).then(function(actionResponse) {
        console.log('launched challenge: ', $scope.challenge.id);
        window.location.href = '/manage/#/challenges?launchSuccess='+$scope.challenge.id;
      });
    }

    /*------------------------*/
    /*  file browsing section */
    /*------------------------*/
    $scope.fileBrowsing = {
      uploadedFiles: [],
      complete: false
    };

    /*---------------------*/
    /* requirement section */
    /*---------------------*/
    $scope.requirements = {
      content: '',
      requirementList: [],
      complete: false
    };

    /*-----------*/
    /* Time line */
    /*-----------*/
    $scope.timeLine = {
      minDate: new Date(),
      startOpened: false,
      endOpened: false,
      isopen: false,
      isopenStart: false,
      complete: false
    };

    var startNew = false;
	var dtTenSet;
    var dtMinDate = Date.now();
    var dtTenDayCounts = 240 * 60 * 60 * 1000;
	var regStartAt;
	var subEndAt;

    if ($scope.challenge.regStartAt) {
      regStartAt = new Date($scope.challenge.regStartAt);
	} else {
      regStartAt = new Date(dtMinDate);
      $scope.challenge.regStartAt = regStartAt.toISOString();

      dtTenSet = new Date(dtMinDate + dtTenDayCounts);
      $scope.challenge.subEndAt = dtTenSet.toISOString();
	}
    $scope.timeLine.stdt = regStartAt;
    $scope.timeLine.timeSelectedStart = $filter('date')(regStartAt, 'HH:mm:ss');

    if ($scope.challenge.subEndAt) {
      subEndAt = new Date($scope.challenge.subEndAt);
    } else {
      subEndAt = new Date(dtMinDate + dtTenDayCounts);
      $scope.challenge.subEndAt = subEndAt.toISOString();
    }
    $scope.timeLine.enddt = subEndAt;
    $scope.timeLine.timeSelectedEnd = $filter('date')(subEndAt, 'HH:mm:ss');

    /*open start calendar*/
    $scope.openStartCal = function($event) {
      $event.preventDefault();
      $event.stopPropagation();
      $scope.timeLine.startOpened = true;
      $scope.timeLine.endOpened = false;
    };

    /*end start calendar*/
    $scope.openEndCal = function($event) {
      $event.preventDefault();
      $event.stopPropagation();
      $scope.timeLine.endOpened = true;
      $scope.timeLine.startOpened = false;
    };

    /*calendar date format*/
    $scope.format = 'MM/dd/yyyy';
    $scope.dateOptions = {
      formatYear: 'yy',
      startingDay: 1
    };

    /*times*/
    $scope.times = _.times(24, function(n) {
      if (n <10) {
        return {'time': '0'+n+':00:00'};
      } else {
        return {'time': n+':00:00'};
      }
    });

    /*set start time*/
    $scope.setStartTime = function(time) {
      $scope.timeLine.timeSelectedStart = time.time;
      calculateDuration();
    };
    /*set end time*/
    $scope.setEndTime = function(time) {
      $scope.timeLine.timeSelectedEnd = time.time;
      calculateDuration();
    };

    function updateTimeLine(type) {
      if ($scope.timeLine.stdt > $scope.timeLine.enddt) {
        if (type === 'stdt') {
          $scope.timeLine.stdt = angular.copy($scope.timeLine.enddt);
        } else {
          $scope.timeLine.enddt = angular.copy($scope.timeLine.stdt);
        }
      }
      calculateDuration();
      if ($scope.timeLine.stdt && $scope.timeLine.enddt && $scope.timeLine.dateDiff > 0) {
        $scope.timeLine.complete = true;
      } else {
        $scope.timeLine.complete = false;
      }
    };

    /*set end date*/
    $scope.$watch('timeLine.stdt', function() {
      updateTimeLine('stdt');
    });

    /*watch end date*/
    $scope.$watch('timeLine.enddt', function() {
      updateTimeLine('enddt');
    });

    /*concatenate date and time*/
    function concatenateDateTime(date, hour) {
      // hour: hh:mm;ss
      var dateTime = angular.copy(date);
      if (hour) {
        var hms = hour.split(':');
        dateTime.setHours(hms[0], hms[1], hms[2], 0);
      }
      return dateTime;
    }

    /*get difference date*/
    function calculateDuration() {
      // use moment.js
      var start = moment(concatenateDateTime($scope.timeLine.stdt, $scope.timeLine.timeSelectedStart));
      var end = moment(concatenateDateTime($scope.timeLine.enddt, $scope.timeLine.timeSelectedEnd));
      $scope.timeLine.dateDiff = end.diff(start, 'days');
    }

    /*---------------*/
    /* Prize section */
    /*---------------*/
    $scope.prizes = {
      totalPrize: 0,
      customerAccountName: '',
      customerAccountId: '',
      activeCount: 2,
      complete: false
    };
    // default prize values
    $scope.placePrizes = {
      places: [
        {
          active: true,
          prize: '1200'
        }, {
          active: true,
          prize: '600'
        }, {
          active: false,
          prize: null
        }, {
          active: false,
          prize: null
        }, {
          active: false,
          prize: null
        }
      ]
    };

    function populatePrizes() {
      var prizes = $scope.challenge.prizes;
      if (!_.isEmpty(prizes)) {
        for (var i=0; i<prizes.length; i+=1) {
          if (prizes[i]) {
            $scope.placePrizes.places[i] = {active: true, prize: prizes[i]};
          }
        }
        if (prizes.length < 5) {
          for (var i=prizes.length; i<5; i+=1) {
            $scope.placePrizes.places[i] = {active: false, prize: null};
          }
        }
      };
    }

    // get prizes in the challenge
    if ($scope.challenge.id) {
      populatePrizes();
    }

    /*set Place prize*/
    $scope.setPlacePrize = function(place, index) {
      // only last one can be activated
      if (index !== 0 && !$scope.placePrizes.places[index - 1].active) {
        return false;
      }
      place.active = true;
      place.prize = '';
    };

    /*remove Place prize*/
    $scope.removePlacePrize = function(place, index) {
      place.active = false;
      place.prize = null;
    };

    /*reorder prizes in descending order*/
    function prizeReorder() {
      $scope.placePrizes.places.sort(function(a, b) {
        if (a.active && !b.active) {
          return -1;
        } else if (!a.active && b.active) {
          return 1;
        } else {
          return Number(b.prize) - Number(a.prize);
        }
      });
    }

    /* check prizes and set complete if prize and customer are set*/
    $scope.checkPrizeComplete = function() {
      $scope.prizes.complete = (!!($scope.prizes.totalPrize > 0 && $scope.placePrizes.places[0].prize > 0) && $scope.prizes.customerAccountId);
    };

    /*update prizes when input text loses a focus*/
    $scope.updatePrizes = function() {
      // reorder prize
      prizeReorder();

      $scope.prizes.totalPrize = 0;
      $scope.prizes.activeCount = 0;
      // calculate the total prize
      angular.forEach($scope.placePrizes.places, function(value, key) {
        if (value.active) {
          $scope.prizes.activeCount += 1;
        }
        if (value.prize) {
          $scope.prizes.totalPrize += parseInt(value.prize);
        }
      });
      $scope.checkPrizeComplete();
    };
    $scope.updatePrizes();

    $scope.$watch('prizes.customerAccountId', function() {
      $scope.checkPrizeComplete();
    }, true);

    /*customer account auto complete*/
    $scope.autoComplete = {
      options: {
        html: true,
        focusOpen: false,
        onlySelect: true,
        appendTo: '.customer-account-holder',
        position: {my: "left top", at: "left bottom", collision: "none"},

        source: function (request, response) {
          // customerAccountsList
          var promise = ChallengeService.getAccounts();
          promise.then(function(data) {
            response($.map(data, function(value) {
              if (value.name.toLowerCase().indexOf($scope.prizes.customerAccountName.toLowerCase()) > -1) {
                return {
                  label: value.name,
                  customerAccountId: value.id
                };
              }
            }));
          }, function(err) {
          });
        },
        select: function(event, ui) {
          console.log('item: ', ui.item);
          $scope.checkPrizeComplete();
          // values are in ui.item
          $scope.prizes.customerAccountId = ui.item.customerAccountId;
          $scope.prizes.customerAccountName = ui.item.label;
        }
      }
    };

	}  // end of CreateChallengeController

})(window, window.angular);
<commit_msg>updated map logic for prizes change from account to projectid<commit_after>/**
 * This code is copyright (c) 2014 Topcoder Corporation
 */

(function (window, angular, undefined) {
  'use strict';

	angular
	  .module('edit.challenge')
	  .controller('CreateChallengeController', CreateChallengeController);

	CreateChallengeController.$inject = ['$scope', '$timeout', '$filter', '$state', 'ChallengeService', 'challenge'];

	function CreateChallengeController($scope, $timeout, $filter, $state, ChallengeService, challenge) {

    $scope.challenge = challenge;
    $scope.editDescription = true;
    $scope.publicBrowsing = {
      complete: false
    }

    /*save new challenge*/
    if ($scope.challenge && !$scope.challenge.id) {
      ChallengeService.createChallenge($scope.challenge).then(function(data) {
        $state.go('edit-challenge', {challengeId: data.id});
      });
    }

    /*watch challenge object*/
    $scope.$watch('challenge', function(newVal) {
      if (newVal.title && newVal.title.trim() && newVal.overview && newVal.overview.trim() && newVal.description && newVal.description.trim()) {
        $scope.publicBrowsing.complete = true;
      } else {
        $scope.publicBrowsing.complete = false;
      }
    }, true);

    /*save current challenge and related info*/
    $scope.saveChallenge = function() {
      //reset the flag that shows the growl notification
      $scope.showSuccessGrowl = false;
      if ($scope.timeLine.complete) {
        $scope.challenge.regStartAt = concatenateDateTime($scope.timeLine.stdt, $scope.timeLine.timeSelectedStart);
        $scope.challenge.subEndAt = concatenateDateTime($scope.timeLine.enddt, $scope.timeLine.timeSelectedEnd);
      };

      if ($scope.prizes.customerAccountName) {
        $scope.challenge.account = $scope.prizes.customerAccountName;
      };
      if ($scope.prizes.customerAccountId) {
        $scope.challenge.accountId = ''+$scope.prizes.customerAccountId;
      };
      // grap prizes
      var prizes = [];
      _.each($scope.placePrizes.places, function(place) {
        if (place.active && place.prize > 0) {
          prizes.push(Number(place.prize));
        }
      });
      $scope.challenge.prizes = prizes;
      $scope.challenge.projectSource = 'TOPCODER';
      $scope.challenge.projectId = $scope.challenge.projectId;

      // update challenge info
      ChallengeService.updateChallenge($scope.challenge).then(function(actionResponse) {
        //after a successful save show the growl
        $scope.showSuccessGrowl = true;

        console.log('updated challenge: ', actionResponse.id);
      }, function(errorResponse) {
        console.log('update challenge: error: ', errorResponse);
      });

    };

    /*get accounts based on the query string*/
    $scope.accounts = [];
    function getAccounts(query) {
      // query is field=value
      ChallengeService.getAccounts(query).then(function(data) {
        $scope.accounts = data;
      });
    };

    /*get all tags and initialize the tags input and initialize the tags input*/
    $scope.tags = $scope.challenge.tags;
    var tagNames = null;
    function getAllTags() {
      ChallengeService.getAllTags().then(function(data) {
        tagNames = new Bloodhound({
          datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
          queryTokenizer: Bloodhound.tokenizers.whitespace,
          local: data
        });
        tagNames.initialize();
        $('input.tags-input').tagsinput({
          typeaheadjs: {
            name: 'tagNames',
            displayKey: 'name',
            valueKey: 'name',
            source: tagNames.ttAdapter()
          },
          freeInput: false,
        });
        $scope.$watch('tags', function(){
          $scope.challenge.tags=$("input.tags-input").tagsinput('items');
        });
      });
    };
    getAllTags();

    /*launch a challenge*/
    $scope.launch = function() {
      ChallengeService.launch($scope.challenge).then(function(actionResponse) {
        console.log('launched challenge: ', $scope.challenge.id);
        window.location.href = '/manage/#/challenges?launchSuccess='+$scope.challenge.id;
      });
    }

    /*------------------------*/
    /*  file browsing section */
    /*------------------------*/
    $scope.fileBrowsing = {
      uploadedFiles: [],
      complete: false
    };

    /*---------------------*/
    /* requirement section */
    /*---------------------*/
    $scope.requirements = {
      content: '',
      requirementList: [],
      complete: false
    };

    /*-----------*/
    /* Time line */
    /*-----------*/
    $scope.timeLine = {
      minDate: new Date(),
      startOpened: false,
      endOpened: false,
      isopen: false,
      isopenStart: false,
      complete: false
    };

    var startNew = false;
	var dtTenSet;
    var dtMinDate = Date.now();
    var dtTenDayCounts = 240 * 60 * 60 * 1000;
	var regStartAt;
	var subEndAt;

    if ($scope.challenge.regStartAt) {
      regStartAt = new Date($scope.challenge.regStartAt);
	} else {
      regStartAt = new Date(dtMinDate);
      $scope.challenge.regStartAt = regStartAt.toISOString();

      dtTenSet = new Date(dtMinDate + dtTenDayCounts);
      $scope.challenge.subEndAt = dtTenSet.toISOString();
	}
    $scope.timeLine.stdt = regStartAt;
    $scope.timeLine.timeSelectedStart = $filter('date')(regStartAt, 'HH:mm:ss');

    if ($scope.challenge.subEndAt) {
      subEndAt = new Date($scope.challenge.subEndAt);
    } else {
      subEndAt = new Date(dtMinDate + dtTenDayCounts);
      $scope.challenge.subEndAt = subEndAt.toISOString();
    }
    $scope.timeLine.enddt = subEndAt;
    $scope.timeLine.timeSelectedEnd = $filter('date')(subEndAt, 'HH:mm:ss');

    /*open start calendar*/
    $scope.openStartCal = function($event) {
      $event.preventDefault();
      $event.stopPropagation();
      $scope.timeLine.startOpened = true;
      $scope.timeLine.endOpened = false;
    };

    /*end start calendar*/
    $scope.openEndCal = function($event) {
      $event.preventDefault();
      $event.stopPropagation();
      $scope.timeLine.endOpened = true;
      $scope.timeLine.startOpened = false;
    };

    /*calendar date format*/
    $scope.format = 'MM/dd/yyyy';
    $scope.dateOptions = {
      formatYear: 'yy',
      startingDay: 1
    };

    /*times*/
    $scope.times = _.times(24, function(n) {
      if (n <10) {
        return {'time': '0'+n+':00:00'};
      } else {
        return {'time': n+':00:00'};
      }
    });

    /*set start time*/
    $scope.setStartTime = function(time) {
      $scope.timeLine.timeSelectedStart = time.time;
      calculateDuration();
    };
    /*set end time*/
    $scope.setEndTime = function(time) {
      $scope.timeLine.timeSelectedEnd = time.time;
      calculateDuration();
    };

    function updateTimeLine(type) {
      if ($scope.timeLine.stdt > $scope.timeLine.enddt) {
        if (type === 'stdt') {
          $scope.timeLine.stdt = angular.copy($scope.timeLine.enddt);
        } else {
          $scope.timeLine.enddt = angular.copy($scope.timeLine.stdt);
        }
      }
      calculateDuration();
      if ($scope.timeLine.stdt && $scope.timeLine.enddt && $scope.timeLine.dateDiff > 0) {
        $scope.timeLine.complete = true;
      } else {
        $scope.timeLine.complete = false;
      }
    };

    /*set end date*/
    $scope.$watch('timeLine.stdt', function() {
      updateTimeLine('stdt');
    });

    /*watch end date*/
    $scope.$watch('timeLine.enddt', function() {
      updateTimeLine('enddt');
    });

    /*concatenate date and time*/
    function concatenateDateTime(date, hour) {
      // hour: hh:mm;ss
      var dateTime = angular.copy(date);
      if (hour) {
        var hms = hour.split(':');
        dateTime.setHours(hms[0], hms[1], hms[2], 0);
      }
      return dateTime;
    }

    /*get difference date*/
    function calculateDuration() {
      // use moment.js
      var start = moment(concatenateDateTime($scope.timeLine.stdt, $scope.timeLine.timeSelectedStart));
      var end = moment(concatenateDateTime($scope.timeLine.enddt, $scope.timeLine.timeSelectedEnd));
      $scope.timeLine.dateDiff = end.diff(start, 'days');
    }

    /*---------------*/
    /* Prize section */
    /*---------------*/
    $scope.prizes = {
      totalPrize: 0,
      customerAccountName: '',
      customerAccountId: '',
      activeCount: 2,
      complete: false
    };
    // default prize values
    $scope.placePrizes = {
      places: [
        {
          active: true,
          prize: '1200'
        }, {
          active: true,
          prize: '600'
        }, {
          active: false,
          prize: null
        }, {
          active: false,
          prize: null
        }, {
          active: false,
          prize: null
        }
      ]
    };

    function populatePrizes() {
      var prizes = $scope.challenge.prizes;
      if (!_.isEmpty(prizes)) {
        for (var i=0; i<prizes.length; i+=1) {
          if (prizes[i]) {
            $scope.placePrizes.places[i] = {active: true, prize: prizes[i]};
          }
        }
        if (prizes.length < 5) {
          for (var i=prizes.length; i<5; i+=1) {
            $scope.placePrizes.places[i] = {active: false, prize: null};
          }
        }
      };
    }

    // get prizes in the challenge
    if ($scope.challenge.id) {
      populatePrizes();
    }

    /*set Place prize*/
    $scope.setPlacePrize = function(place, index) {
      // only last one can be activated
      if (index !== 0 && !$scope.placePrizes.places[index - 1].active) {
        return false;
      }
      place.active = true;
      place.prize = '';
    };

    /*remove Place prize*/
    $scope.removePlacePrize = function(place, index) {
      place.active = false;
      place.prize = null;
    };

    /*reorder prizes in descending order*/
    function prizeReorder() {
      $scope.placePrizes.places.sort(function(a, b) {
        if (a.active && !b.active) {
          return -1;
        } else if (!a.active && b.active) {
          return 1;
        } else {
          return Number(b.prize) - Number(a.prize);
        }
      });
    }

    /* check prizes and set complete if prize and customer are set*/
    $scope.checkPrizeComplete = function() {
      $scope.prizes.complete = (!!($scope.prizes.totalPrize > 0 && $scope.placePrizes.places[0].prize > 0) && $scope.challenge.projectId);
    };

    /*update prizes when input text loses a focus*/
    $scope.updatePrizes = function() {
      // reorder prize
      prizeReorder();

      $scope.prizes.totalPrize = 0;
      $scope.prizes.activeCount = 0;
      // calculate the total prize
      angular.forEach($scope.placePrizes.places, function(value, key) {
        if (value.active) {
          $scope.prizes.activeCount += 1;
        }
        if (value.prize) {
          $scope.prizes.totalPrize += parseInt(value.prize);
        }
      });
      $scope.checkPrizeComplete();
    };
    $scope.updatePrizes();

    $scope.$watch('challenge.projectId', function() {
      $scope.checkPrizeComplete();
    }, true);

    /*customer account auto complete*/
    $scope.autoComplete = {
      options: {
        html: true,
        focusOpen: false,
        onlySelect: true,
        appendTo: '.customer-account-holder',
        position: {my: "left top", at: "left bottom", collision: "none"},

        source: function (request, response) {
          // customerAccountsList
          var promise = ChallengeService.getAccounts();
          promise.then(function(data) {
            response($.map(data, function(value) {
              if (value.name.toLowerCase().indexOf($scope.prizes.customerAccountName.toLowerCase()) > -1) {
                return {
                  label: value.name,
                  customerAccountId: value.id
                };
              }
            }));
          }, function(err) {
          });
        },
        select: function(event, ui) {
          console.log('item: ', ui.item);
          $scope.checkPrizeComplete();
          // values are in ui.item
          $scope.prizes.customerAccountId = ui.item.customerAccountId;
          $scope.prizes.customerAccountName = ui.item.label;
        }
      }
    };

	}  // end of CreateChallengeController

})(window, window.angular);
<|endoftext|>


<commit_before>'use strict'

import $ from 'jquery'
import _ from 'lodash'
import { makeSafePath } from '../helpers/form'
import { setInputSelection } from '../helpers/pages'

// -> Move Existing Document

module.exports = (currentBasePath, alerts) => {
  if (currentBasePath !== '') {
    $('.btn-move-prompt').removeClass('is-hidden')
  }

  let moveInitialDocument = _.lastIndexOf(currentBasePath, '/') + 1

  $('.btn-move-prompt').on('click', (ev) => {
    $('#txt-move-prompt').val(currentBasePath)
    $('#modal-move-prompt').toggleClass('is-active')
    setInputSelection($('#txt-move-prompt').get(0), moveInitialDocument, currentBasePath.length)
    $('#txt-move-prompt').removeClass('is-danger').next().addClass('is-hidden')
  })

  $('#txt-move-prompt').on('keypress', (ev) => {
    if (ev.which === 13) {
      $('.btn-move-go').trigger('click')
    }
  })

  $('.btn-move-go').on('click', (ev) => {
    let newDocPath = makeSafePath($('#txt-move-prompt').val())
    if (_.isEmpty(newDocPath) || newDocPath === currentBasePath || newDocPath === 'home') {
      $('#txt-move-prompt').addClass('is-danger').next().removeClass('is-hidden')
    } else {
      $('#txt-move-prompt').parent().addClass('is-loading')

      $.ajax(window.location.href, {
        data: {
          move: newDocPath
        },
        dataType: 'json',
        method: 'PUT'
      }).then((rData, rStatus, rXHR) => {
        if (rData.ok) {
          window.location.assign('/' + newDocPath)
        } else {
          alerts.pushError('Something went wrong', rData.error)
        }
      }, (rXHR, rStatus, err) => {
        alerts.pushError('Something went wrong', 'Save operation failed.')
      })
    }
  })
}
<commit_msg>Fixed move dialog<commit_after>'use strict'

import $ from 'jquery'
import _ from 'lodash'
import { setInputSelection } from '../helpers/form'
import { makeSafePath } from '../helpers/pages'

// -> Move Existing Document

module.exports = (currentBasePath, alerts) => {
  if (currentBasePath !== '') {
    $('.btn-move-prompt').removeClass('is-hidden')
  }

  let moveInitialDocument = _.lastIndexOf(currentBasePath, '/') + 1

  $('.btn-move-prompt').on('click', (ev) => {
    $('#txt-move-prompt').val(currentBasePath)
    $('#modal-move-prompt').toggleClass('is-active')
    setInputSelection($('#txt-move-prompt').get(0), moveInitialDocument, currentBasePath.length)
    $('#txt-move-prompt').removeClass('is-danger').next().addClass('is-hidden')
  })

  $('#txt-move-prompt').on('keypress', (ev) => {
    if (ev.which === 13) {
      $('.btn-move-go').trigger('click')
    }
  })

  $('.btn-move-go').on('click', (ev) => {
    let newDocPath = makeSafePath($('#txt-move-prompt').val())
    if (_.isEmpty(newDocPath) || newDocPath === currentBasePath || newDocPath === 'home') {
      $('#txt-move-prompt').addClass('is-danger').next().removeClass('is-hidden')
    } else {
      $('#txt-move-prompt').parent().addClass('is-loading')

      $.ajax(window.location.href, {
        data: {
          move: newDocPath
        },
        dataType: 'json',
        method: 'PUT'
      }).then((rData, rStatus, rXHR) => {
        if (rData.ok) {
          window.location.assign('/' + newDocPath)
        } else {
          alerts.pushError('Something went wrong', rData.error)
        }
      }, (rXHR, rStatus, err) => {
        alerts.pushError('Something went wrong', 'Save operation failed.')
      })
    }
  })
}
<|endoftext|>


<commit_before>(function () {

  var Pontoon = {
        _doc: window,
        _ptn: window.top,
        _locale: "",
        _meta: {},
        _data: {}
  	  },
      jqueryAppended = false,
      script = document.createElement('script');

  // Main code
  function jqueryLoaded() {
    $.noConflict();
    jQuery(document).ready(function($) {

      /*
       * window.postMessage improved
       *
       * messageType data type to be sent to the other window
       * messageValue data value to be sent to the other window
       * otherWindow reference to another window
       * targetOrigin specifies what the origin of otherWindow must be
      */
      function postMessage(messageType, messageValue, otherWindow, targetOrigin) {
        var otherWindow = otherWindow || Pontoon._ptn,
            targetOrigin = targetOrigin || "*", // TODO: hardcode Pontoon domain name
            message = {
              type: messageType,
              value: messageValue
            }
        otherWindow.postMessage(JSON.stringify(message), targetOrigin);
      }

      /**
       * Send data to main Pontoon code
       */
      function sendData() {
        // Deep copy: http://api.jquery.com/jQuery.extend
        var data = $.extend(true, {}, Pontoon._data);
        $(data.entities).each(function () {
          delete this.node;
        });

        postMessage("data", data);
      }

      /**
       * Render main UI and handle events
       */
      function renderHandle() {
        sendData();
        postMessage("render");

        // Update UI and progress when saved
        $(".editableToolbar > .save").click(function () {
          var element = $(this).parent().get(0).target,
              entity = element.entity;

          entity.translation = $($(element).clone()).html();
          sendData();
          postMessage("save", entity.id);
        });

        // Update progress when cancelled
        $(".editableToolbar > .cancel").click(function () {
          var element = $(this).parent().get(0).target,
              entity = element.entity;

          $(element).html(element.prevValue);
          entity.translation = "";
          sendData();
          postMessage("cancel", entity.id);
        });

        // In-place keyboard shortcuts
        $("html").unbind("keydown.pontoon").bind("keydown.pontoon", function (e) {
          var key = e.keyCode || e.which,
              toolbar = $(".editableToolbar"),
              save = toolbar.find(".save"),
              target = toolbar.get(0).target,
              entity = target.entity,
              id = entity.id,
              next = id + 1,
              entities = Pontoon._data.entities;

          if (save.is(":visible")) {
            if (key === 13) { // Enter: confirm translation
              save.click();
              target.hideToolbar();
              return false;
            }

            if (key === 27) { // Esc: cancel translation
              toolbar.find(".cancel").click();
              target.hideToolbar();
              return false;
            }

            if (key === 9) { // Tab: confirm + move around entities
              // If on last entity, jump to the first
              if (next > entities.length) {
              	$.each(entities, function() {
                  if (this.body) {
                    next = this.id;
                  }
                });
              }
              save.click();
              $(target).removeClass("hovered");
              postMessage("hover", id);
              entities[next].hover();
              $(".editableToolbar > .edit").click();
              return false;
            }
          }
        });
      }

      /**
       * Extend entity object
       * TODO: move to main.js
       *
       * e Temporary entity object
       */
      function extendEntity(e) {
        e.hover = function () {
          this.node.get(0).showToolbar();
        };
        e.unhover = function () {
          this.node.get(0).hideToolbar();
        };
      }

      /**
       * Makes DOM nodes editable using contentEditable property
       * Based on editableText plugin by Andris Valums, http://valums.com
       *
       * node DOM node
       */
      function makeEditable(node) {
        // Save value to restore if user presses cancel
        node.prevValue = $(node).html().toString();

        // Show/hide toolbar
        node.showToolbar = function () {
          showToolbar(this);
        }
        node.hideToolbar = function () {
          hideToolbar(this);
        }

        // Hover handler
        $(node).hover(function () {
          this.entity.hover();
        }, function() {
          this.entity.unhover();
        });
      }

      /**
       * Extract entities from the document, not prepared for working with Pontoon
       *
       * Create entity object from every non-empty text node
       * Exclude nodes from special tags, e.g.


<commit_before>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');
var leaflet_label = require('./leaflet_label/leaflet.label-src.js');
var session = require('session');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();

  } else {

    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];
module.exports.makerpoint_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.cleanMarkerpoint = function() {
    var map = this.activeMap;
    for (i in this.makerpoint_creadas) {
        try {
                map.removeLayer(this.makerpoint_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.makerpoint_creadas = [];

};

module.exports.marker_map = function(from, to){
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true})
        .addTo(this.activeMap);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true})
        .addTo(this.activeMap);
    var _this = this;

    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();

            plan.setAddress('from', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    markerto.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();
            plan.setAddress('to', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    var name = to[2];

    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/icono.png',
        iconSize: [20, 20],
        iconAnchor: [0, 0],
        popupAnchor:  [-3, -76]
    });
    var markers = [
      L.marker([to[0], to[1]], {icon: IconEnd}).bindLabel(name, { direction: 'auto', noHide: true })
    ];

    var layer = L.layerGroup(markers).addTo(map);

     var myZoom = {
      start:  map.getZoom(),
      end: map.getZoom()
    };

    map.on('zoomend', function(e) {
        myZoom.end = map.getZoom();
        if (myZoom.end <= 10){
            layer.eachLayer(function (marker) {
                marker.hideLabel();
            });
        }
        if (myZoom.end > 10){
            layer.eachLayer(function (marker) {
                marker.showLabel();
            });
        }
    });

    this.makerpoint_creadas.push(layer);
    //this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(legs,mode) {
    var route = legs.legGeometry.points;
    var circle_from = [legs.from.lat, legs.from.lon, legs.from.name];
    var circle_to = [legs.to.lat, legs.to.lon, legs.to.name];
    var color = '#000';
    var weight = 5;
    var dasharray= '';

        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      //var bounds = new L.LatLngBounds([]);
      //var bounds = [];
      var boxpolys = new Array(boxes.length);
      /*
      for (var i = 0; i < boxes.length; i++) {
        //bounds.extend(boxes[i]);
        bounds.push(boxes[i]);
      }*/

      route.addTo(this.activeMap);
      //this.activeMap.fitBounds(bounds);
};

<commit_msg>change maps layers<commit_after>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');
var leaflet_label = require('./leaflet_label/leaflet.label-src.js');
var session = require('session');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();

  } else {

    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];
module.exports.makerpoint_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.cleanMarkerpoint = function() {
    var map = this.activeMap;
    for (i in this.makerpoint_creadas) {
        try {
                map.removeLayer(this.makerpoint_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.makerpoint_creadas = [];

};

module.exports.marker_map = function(from, to){
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true})
        .addTo(this.activeMap);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true})
        .addTo(this.activeMap);
    var _this = this;

    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();

            plan.setAddress('from', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    markerto.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();
            plan.setAddress('to', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    var name = to[2];

    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/icono.png',
        iconSize: [20, 20],
        iconAnchor: [0, 0],
        popupAnchor:  [-3, -76]
    });
    var markers = [
      L.marker([to[0], to[1]], {icon: IconEnd}).bindLabel(name, { direction: 'auto', noHide: true })
    ];

    //var layer = L.layerGroup(markers).addTo(map);
    //
    // var myZoom = {
    //  start:  map.getZoom(),
    //  end: map.getZoom()
    //};

    var conditionalLayer = L.conditionalMarkers(markers, {maxMarkers: 2}).addTo(map);

    //map.on('zoomend', function(e) {
    //    myZoom.end = map.getZoom();
    //    if (myZoom.end <= 10){
    //        layer.eachLayer(function (marker) {
    //            marker.hideLabel();
    //        });
    //    }
    //    if (myZoom.end > 10){
    //        layer.eachLayer(function (marker) {
    //            marker.showLabel();
    //        });
    //    }
    //});

    this.makerpoint_creadas.push(layer);
    //this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(legs,mode) {
    var route = legs.legGeometry.points;
    var circle_from = [legs.from.lat, legs.from.lon, legs.from.name];
    var circle_to = [legs.to.lat, legs.to.lon, legs.to.name];
    var color = '#000';
    var weight = 5;
    var dasharray= '';

        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      //var bounds = new L.LatLngBounds([]);
      //var bounds = [];
      var boxpolys = new Array(boxes.length);
      /*
      for (var i = 0; i < boxes.length; i++) {
        //bounds.extend(boxes[i]);
        bounds.push(boxes[i]);
      }*/

      route.addTo(this.activeMap);
      //this.activeMap.fitBounds(bounds);
};

<|endoftext|>


<commit_before>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true}).bindPopup('to').addTo(map);
    var _this = this;
    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       console.log("cordenadas drag from ->",result);
       _this.cleanPolyline();
    });

    markerto.on('dragend', function(e){
        var marker = e.target;
        var result = marker.getLatLng();
        console.log("cordenadas drag to ->",result);
        _this.cleanPolyline();
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    console.log("mapa point to ->", to);
    var name = to[2];
    var circle = L.circle([to[0], to[1]], 500, {
        color: '#000',
        fillColor: '#ffffff',
        fillOpacity: 1
    }).bindPopup(name).addTo(map);

    var myZoom = {
      start:  map.getZoom(),
      end: map.getZoom()
    };
    console.log(myZoom);
    map.on('zoomstart', function(e) {
       myZoom.start = map.getZoom();
        console.log("start zoom 1000 ", myZoom.start);
    });

    map.on('zoomend', function(e) {
        myZoom.end = map.getZoom();
         console.log("End zoom ", myZoom.end);
        var diff = myZoom.start - myZoom.end;
        if (diff > 0) {
            circle.setRadius(circle.getRadius() * 2);
        } else if (diff < 0) {
            circle.setRadius(circle.getRadius() / 2);
        }
    });

    this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';
        console.log("imprime mode ->", mode);
        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        console.log("pintamos datos ->", this.polyline_creadas);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<commit_msg>adding console<commit_after>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true}).bindPopup('to').addTo(map);
    var _this = this;
    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       console.log("cordenadas drag from ->",result);
       _this.cleanPolyline();
    });

    markerto.on('dragend', function(e){
        var marker = e.target;
        var result = marker.getLatLng();
        console.log("cordenadas drag to ->",result);
        _this.cleanPolyline();
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    console.log("mapa point to ->", to);
    var name = to[2];
    var circle = L.circle([to[0], to[1]], 400, {
        color: '#000',
        fillColor: '#ffffff',
        fillOpacity: 1
    }).bindPopup(name).addTo(map);

    var myZoom = {
      start:  map.getZoom(),
      end: map.getZoom()
    };
    console.log(myZoom);
    map.on('zoomstart', function(e) {
       myZoom.start = map.getZoom();
        console.log("start zoom 400 ", myZoom.start);
    });

    map.on('zoomend', function(e) {
        myZoom.end = map.getZoom();
         console.log("End zoom ", myZoom.end);
        var diff = myZoom.start - myZoom.end;
        if (diff > 0) {
            circle.setRadius(circle.getRadius() * 2);
        } else if (diff < 0) {
            circle.setRadius(circle.getRadius() / 2);
        }
    });

    this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';
        console.log("imprime mode ->", mode);
        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        console.log("pintamos datos ->", this.polyline_creadas);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<|endoftext|>


<commit_before>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');
var leaflet_label = require('./leaflet_label/leaflet.label-src.js');
var session = require('session');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();

  } else {

    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];
module.exports.makerpoint_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.cleanMarkerpoint = function() {
    var map = this.activeMap;
    for (i in this.makerpoint_creadas) {
        try {
                map.removeLayer(this.makerpoint_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.makerpoint_creadas = [];

};

module.exports.marker_map = function(from, to){
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true})
        .addTo(this.activeMap);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true})
        .addTo(this.activeMap);
    var _this = this;

    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();

            plan.setAddress('from', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    markerto.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();
            plan.setAddress('to', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    var name = to[2];

    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/icono.png',
        iconSize: [20, 20],
        iconAnchor: [0, 0],
        popupAnchor:  [-3, -76]
    });
    var markers = [
      L.marker([to[0], to[1]], {icon: IconEnd}).bindLabel(name)
    ];

    var layer = L.layerGroup(markers).addTo(map).eachLayer(function(layer){layer.showLabel()});

    this.makerpoint_creadas.push(layer);
    //this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(legs,mode) {
    console.log("routeColor ->",legs);
    var route = legs.legGeometry.points;
    var circle_from = [legs.from.lat, legs.from.lon, legs.from.name];
    var circle_to = [legs.to.lat, legs.to.lon, legs.to.name];
    var color = '#000';
    var weight = 5;
    var dasharray= '';

        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }

        else if(mode=="BUS") {
            //color = '#FEF0B5';
             weight = 5;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      //var bounds = new L.LatLngBounds([]);
      //var bounds = [];
      var boxpolys = new Array(boxes.length);
      /*
      for (var i = 0; i < boxes.length; i++) {
        //bounds.extend(boxes[i]);
        bounds.push(boxes[i]);
      }*/

      route.addTo(this.activeMap);
      //this.activeMap.fitBounds(bounds);
};

<commit_msg>routerColor<commit_after>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');
var leaflet_label = require('./leaflet_label/leaflet.label-src.js');
var session = require('session');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();

  } else {

    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];
module.exports.makerpoint_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.cleanMarkerpoint = function() {
    var map = this.activeMap;
    for (i in this.makerpoint_creadas) {
        try {
                map.removeLayer(this.makerpoint_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.makerpoint_creadas = [];

};

module.exports.marker_map = function(from, to){
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true})
        .addTo(this.activeMap);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true})
        .addTo(this.activeMap);
    var _this = this;

    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();

            plan.setAddress('from', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    markerto.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();
            plan.setAddress('to', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    var name = to[2];

    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/icono.png',
        iconSize: [20, 20],
        iconAnchor: [0, 0],
        popupAnchor:  [-3, -76]
    });
    var markers = [
      L.marker([to[0], to[1]], {icon: IconEnd}).bindLabel(name)
    ];

    var layer = L.layerGroup(markers).addTo(map).eachLayer(function(layer){layer.showLabel()});

    this.makerpoint_creadas.push(layer);
    //this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(legs,mode) {
    console.log("routeColor ->",legs.routeColor);
    var route = legs.legGeometry.points;
    var circle_from = [legs.from.lat, legs.from.lon, legs.from.name];
    var circle_to = [legs.to.lat, legs.to.lon, legs.to.name];
    var color = '#000';
    var weight = 5;
    var dasharray= '';

        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }

        else if(mode=="BUS") {
            //color = '#FEF0B5';
             weight = 5;
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      //var bounds = new L.LatLngBounds([]);
      //var bounds = [];
      var boxpolys = new Array(boxes.length);
      /*
      for (var i = 0; i < boxes.length; i++) {
        //bounds.extend(boxes[i]);
        bounds.push(boxes[i]);
      }*/

      route.addTo(this.activeMap);
      //this.activeMap.fitBounds(bounds);
};

<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { NavigationActions, addNavigationHelpers, StackNavigator, TabNavigator } from 'react-navigation';
import {
  createReduxBoundAddListener,
  createReactNavigationReduxMiddleware,
} from 'react-navigation-redux-helpers';
import { Text, View, StyleSheet } from 'react-native';
import { connect } from 'react-redux';
import { graphql, compose } from 'react-apollo';
import update from 'immutability-helper';
import { map } from 'lodash';
import { Buffer } from 'buffer';

import Groups from './screens/groups.screen';
import Messages from './screens/messages.screen';
import FinalizeGroup from './screens/finalize-group.screen';
import GroupDetails from './screens/group-details.screen';
import NewGroup from './screens/new-group.screen';
import Signin from './screens/signin.screen';

import { USER_QUERY } from './graphql/user.query';
import MESSAGE_ADDED_SUBSCRIPTION from './graphql/message-added.subscription';
import GROUP_ADDED_SUBSCRIPTION from './graphql/group-added.subscription';

import { wsClient } from './app';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  tabText: {
    color: '#777',
    fontSize: 10,
    justifyContent: 'center',
  },
  selected: {
    color: 'blue',
  },
});

const TestScreen = title => () => (
  <View style={styles.container}>
    <Text>
      {title}
    </Text>
  </View>
);

// tabs in main screen
const MainScreenNavigator = TabNavigator({
  Chats: { screen: Groups },
  Settings: { screen: TestScreen('Settings') },
}, {
  initialRouteName: 'Chats',
});

const AppNavigator = StackNavigator({
  Main: { screen: MainScreenNavigator },
  Signin: { screen: Signin },
  Messages: { screen: Messages },
  GroupDetails: { screen: GroupDetails },
  NewGroup: { screen: NewGroup },
  FinalizeGroup: { screen: FinalizeGroup },
}, {
  mode: 'modal',
});

// reducer initialization code
const initialState=AppNavigator.router.getStateForAction(NavigationActions.reset({
	index: 0,
	actions: [
	  NavigationActions.navigate({
		  routeName: 'Main',
	  }),
	],
}));

export const navigationReducer = (state = initialState, action) => {
  const nextState = AppNavigator.router.getStateForAction(action, state);

  // Simply return the original `state` if `nextState` is null or undefined.
  return nextState || state;
};

// Note: createReactNavigationReduxMiddleware must be run before createReduxBoundAddListener
export const navigationMiddleware = createReactNavigationReduxMiddleware(
  "root",
  state => state.nav,
);
const addListener = createReduxBoundAddListener("root");

class AppWithNavigationState extends Component {
  componentWillReceiveProps(nextProps) {
    if (!nextProps.user) {
      if (this.groupSubscription) {
        this.groupSubscription();
      }

      if (this.messagesSubscription) {
        this.messagesSubscription();
      }

      // clear the event subscription
      if (this.reconnected) {
        this.reconnected();
      }
    } else if (!this.reconnected) {
      this.reconnected = wsClient.onReconnected(() => {
        this.props.refetch(); // check for any data lost during disconnect
      }, this);
    }

    if (nextProps.user &&
      (!this.props.user || nextProps.user.groups.length !== this.props.user.groups.length)) {
      // unsubscribe from old

      if (typeof this.messagesSubscription === 'function') {
        this.messagesSubscription();
      }
      // subscribe to new
      if (nextProps.user.groups.length) {
        this.messagesSubscription = nextProps.subscribeToMessages();
      }
    }

    if (!this.groupSubscription && nextProps.user) {
      this.groupSubscription = nextProps.subscribeToGroups();
    }
  }

  render() {
    return (
      <AppNavigator navigation={addNavigationHelpers({
        dispatch: this.props.dispatch,
        state: this.props.nav,
        addListener,
      })} />
    );
  }
}

AppWithNavigationState.propTypes = {
  dispatch: PropTypes.func.isRequired,
  nav: PropTypes.object.isRequired,
  refetch: PropTypes.func,
  subscribeToGroups: PropTypes.func,
  subscribeToMessages: PropTypes.func,
  user: PropTypes.shape({
    id: PropTypes.number.isRequired,
    email: PropTypes.string.isRequired,
    groups: PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.number.isRequired,
        name: PropTypes.string.isRequired,
      }),
    ),
  }),
};

const mapStateToProps = state => ({
  nav: state.nav,
});

const userQuery = graphql(USER_QUERY, {
  skip: ownProps => true, // fake it -- we'll use ownProps with auth
  options: () => ({ variables: { id: 1 } }), // fake the user for now
  props: ({ data: { loading, user, refetch, subscribeToMore } }) => ({
    loading,
    user,
    refetch,
    subscribeToMessages() {
      return subscribeToMore({
        document: MESSAGE_ADDED_SUBSCRIPTION,
        variables: {
          userId: 1, // fake the user for now
          groupIds: map(user.groups, 'id'),
        },
        updateQuery: (previousResult, { subscriptionData }) => {
          const previousGroups = previousResult.user.groups;
          const newMessage = subscriptionData.data.messageAdded;

          const groupIndex = map(previousGroups, 'id').indexOf(newMessage.to.id);

          return update(previousResult, {
            user: {
              groups: {
                [groupIndex]: {
                  messages: {
                    edges: {
                      $set: [{
                        __typename: 'MessageEdge',
                        node: newMessage,
                        cursor: Buffer.from(newMessage.id.toString()).toString('base64'),
                      }],
                    },
                  },
                },
              },
            },
          });
        },
      });
    },
    subscribeToGroups() {
      return subscribeToMore({
        document: GROUP_ADDED_SUBSCRIPTION,
        variables: { userId: user.id },
        updateQuery: (previousResult, { subscriptionData }) => {
          const newGroup = subscriptionData.data.groupAdded;

          return update(previousResult, {
            user: {
              groups: { $push: [newGroup] },
            },
          });
        },
      });
    },
  }),
});

export default compose(
  connect(mapStateToProps),
  userQuery,
)(AppWithNavigationState);
<commit_msg>Step 7.29: Add Settings screen and auth logic to Navigation<commit_after>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { NavigationActions, addNavigationHelpers, StackNavigator, TabNavigator } from 'react-navigation';
import {
  createReduxBoundAddListener,
  createReactNavigationReduxMiddleware,
} from 'react-navigation-redux-helpers';
import { Text, View, StyleSheet } from 'react-native';
import { connect } from 'react-redux';
import { graphql, compose } from 'react-apollo';
import update from 'immutability-helper';
import { map } from 'lodash';
import { Buffer } from 'buffer';
import { REHYDRATE } from 'redux-persist';

import Groups from './screens/groups.screen';
import Messages from './screens/messages.screen';
import FinalizeGroup from './screens/finalize-group.screen';
import GroupDetails from './screens/group-details.screen';
import NewGroup from './screens/new-group.screen';
import Signin from './screens/signin.screen';
import Settings from './screens/settings.screen';

import { USER_QUERY } from './graphql/user.query';
import MESSAGE_ADDED_SUBSCRIPTION from './graphql/message-added.subscription';
import GROUP_ADDED_SUBSCRIPTION from './graphql/group-added.subscription';

import { wsClient } from './app';

import { LOGOUT } from './constants/constants';

// tabs in main screen
const MainScreenNavigator = TabNavigator({
  Chats: { screen: Groups },
  Settings: { screen: Settings },
}, {
  initialRouteName: 'Chats',
});

const AppNavigator = StackNavigator({
  Main: { screen: MainScreenNavigator },
  Signin: { screen: Signin },
  Messages: { screen: Messages },
  GroupDetails: { screen: GroupDetails },
  NewGroup: { screen: NewGroup },
  FinalizeGroup: { screen: FinalizeGroup },
}, {
  mode: 'modal',
});

// reducer initialization code
const initialState=AppNavigator.router.getStateForAction(NavigationActions.reset({
	index: 0,
	actions: [
	  NavigationActions.navigate({
		  routeName: 'Main',
	  }),
	],
}));

// reducer code
export const navigationReducer = (state = initialState, action) => {
  let nextState = AppNavigator.router.getStateForAction(action, state);
  switch (action.type) {
    case REHYDRATE:
      // convert persisted data to Immutable and confirm rehydration
      if (!action.payload || !action.payload.auth || !action.payload.auth.jwt) {
        const { routes, index } = state;
        if (routes[index].routeName !== 'Signin') {
          nextState = AppNavigator.router.getStateForAction(
            NavigationActions.navigate({ routeName: 'Signin' }),
            state,
          );
        }
      }
      break;
    case LOGOUT:
      const { routes, index } = state;
      if (routes[index].routeName !== 'Signin') {
        nextState = AppNavigator.router.getStateForAction(
          NavigationActions.navigate({ routeName: 'Signin' }),
          state,
        );
      }
      break;
    default:
      nextState = AppNavigator.router.getStateForAction(action, state);
      break;
  }

  // Simply return the original `state` if `nextState` is null or undefined.
  return nextState || state;
};

// Note: createReactNavigationReduxMiddleware must be run before createReduxBoundAddListener
export const navigationMiddleware = createReactNavigationReduxMiddleware(
  "root",
  state => state.nav,
);
const addListener = createReduxBoundAddListener("root");

class AppWithNavigationState extends Component {
  componentWillReceiveProps(nextProps) {
    if (!nextProps.user) {
      if (this.groupSubscription) {
        this.groupSubscription();
      }

      if (this.messagesSubscription) {
        this.messagesSubscription();
      }

      // clear the event subscription
      if (this.reconnected) {
        this.reconnected();
      }
    } else if (!this.reconnected) {
      this.reconnected = wsClient.onReconnected(() => {
        this.props.refetch(); // check for any data lost during disconnect
      }, this);
    }

    if (nextProps.user &&
      (!this.props.user || nextProps.user.groups.length !== this.props.user.groups.length)) {
      // unsubscribe from old

      if (typeof this.messagesSubscription === 'function') {
        this.messagesSubscription();
      }
      // subscribe to new
      if (nextProps.user.groups.length) {
        this.messagesSubscription = nextProps.subscribeToMessages();
      }
    }

    if (!this.groupSubscription && nextProps.user) {
      this.groupSubscription = nextProps.subscribeToGroups();
    }
  }

  render() {
    return (
      <AppNavigator navigation={addNavigationHelpers({
        dispatch: this.props.dispatch,
        state: this.props.nav,
        addListener,
      })} />
    );
  }
}

AppWithNavigationState.propTypes = {
  dispatch: PropTypes.func.isRequired,
  nav: PropTypes.object.isRequired,
  refetch: PropTypes.func,
  subscribeToGroups: PropTypes.func,
  subscribeToMessages: PropTypes.func,
  user: PropTypes.shape({
    id: PropTypes.number.isRequired,
    email: PropTypes.string.isRequired,
    groups: PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.number.isRequired,
        name: PropTypes.string.isRequired,
      }),
    ),
  }),
};

const mapStateToProps = state => ({
  nav: state.nav,
});

const userQuery = graphql(USER_QUERY, {
  skip: ownProps => true, // fake it -- we'll use ownProps with auth
  options: () => ({ variables: { id: 1 } }), // fake the user for now
  props: ({ data: { loading, user, refetch, subscribeToMore } }) => ({
    loading,
    user,
    refetch,
    subscribeToMessages() {
      return subscribeToMore({
        document: MESSAGE_ADDED_SUBSCRIPTION,
        variables: {
          userId: 1, // fake the user for now
          groupIds: map(user.groups, 'id'),
        },
        updateQuery: (previousResult, { subscriptionData }) => {
          const previousGroups = previousResult.user.groups;
          const newMessage = subscriptionData.data.messageAdded;

          const groupIndex = map(previousGroups, 'id').indexOf(newMessage.to.id);

          return update(previousResult, {
            user: {
              groups: {
                [groupIndex]: {
                  messages: {
                    edges: {
                      $set: [{
                        __typename: 'MessageEdge',
                        node: newMessage,
                        cursor: Buffer.from(newMessage.id.toString()).toString('base64'),
                      }],
                    },
                  },
                },
              },
            },
          });
        },
      });
    },
    subscribeToGroups() {
      return subscribeToMore({
        document: GROUP_ADDED_SUBSCRIPTION,
        variables: { userId: user.id },
        updateQuery: (previousResult, { subscriptionData }) => {
          const newGroup = subscriptionData.data.groupAdded;

          return update(previousResult, {
            user: {
              groups: { $push: [newGroup] },
            },
          });
        },
      });
    },
  }),
});

export default compose(
  connect(mapStateToProps),
  userQuery,
)(AppWithNavigationState);
<|endoftext|>


<commit_before>var webpack = require("webpack")
var path = require("path")
var ExtractTextPlugin = require("extract-text-webpack-plugin")
var HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: {
        app: "./app/scripts/main.js",
        vendor: ["jquery", "lodash", "handlebars/runtime", "metrics-graphics", "moment", "modernizr"],
        bootstrap: ['bootstrap-loader/extractStyles']
    },
    output: {
        path: path.join(__dirname, 'dist'),
        publicPath: '/',
        filename: "scripts/app.[chunkhash].js"
    },
    module: {
        loaders: [
            { test: /\.handlebars$/, loader: "handlebars-loader" },
            { test: /\.modernizrrc$/, loader: "modernizr" },
            { test: /\.css$/, loader: ExtractTextPlugin.extract("style", ["css"]) },
            { test: /\.scss$/, loader: ExtractTextPlugin.extract("style", ["css", "sass"]) },
            { test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/, loader: 'url-loader?limit=8196&name=fonts/[hash].[ext]' }
        ]
    },
    resolve: {
      alias: {
        modernizr$: __dirname + "/.modernizrrc"
      }
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({ names: ["bootstrap", "vendor"], filename: "scripts/[name].[chunkhash].js" }),
        new ExtractTextPlugin('styles/[name].[chunkhash].css'),
        new HtmlWebpackPlugin({
            template: 'app/index.html.handlebars'
        })
    ]
};
<commit_msg>Add webpack for health.html<commit_after>var webpack = require("webpack")
var path = require("path")
var ExtractTextPlugin = require("extract-text-webpack-plugin")
var HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: {
        app: "./app/scripts/main.js",
        vendor: ["jquery", "lodash", "handlebars/runtime", "metrics-graphics", "moment", "modernizr"],
        bootstrap: ['bootstrap-loader/extractStyles']
    },
    output: {
        path: path.join(__dirname, 'dist'),
        publicPath: '/',
        filename: "scripts/app.[chunkhash].js"
    },
    module: {
        loaders: [
            { test: /\.handlebars$/, loader: "handlebars-loader" },
            { test: /\.modernizrrc$/, loader: "modernizr" },
            { test: /\.css$/, loader: ExtractTextPlugin.extract("style", ["css"]) },
            { test: /\.scss$/, loader: ExtractTextPlugin.extract("style", ["css", "sass"]) },
            { test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/, loader: "url-loader?limit=8196&name=fonts/[hash].[ext]" }
        ]
    },
    resolve: {
      alias: {
        modernizr$: __dirname + "/.modernizrrc"
      }
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({ names: ["bootstrap", "vendor"], filename: "scripts/[name].[chunkhash].js" }),
        new ExtractTextPlugin("styles/[name].[chunkhash].css"),
        new HtmlWebpackPlugin({
            template: "app/index.html.handlebars"
        }),
        new HtmlWebpackPlugin({
            filename: "health.html",
            template: "app/health.html",
            inject: false
        })
    ]
};
<|endoftext|>