<commit_before>function userManagementPage() {
  var $page = $('#user-management-page')
  var $userList = $page.find('.user-list')
  var $userNameQuery = $page.find('#user-name-query')

  var $newUserType = $page.find('.new-user input[name="new-user-type"]')
  $newUserType.select2({
    data: _.map(enums.userRoles, function(roleValue, roleKey) {
      return { id: roleKey, text: roleValue.name }
    }),
    minimumResultsForSearch: -1
  }).select2('val', 'user')

  $page.on('show', function(event, userId) {
    updateLocationHash(userId || '')
    $userList.empty()
    var active = $page.find('.filters input[name=active]').prop('checked')
    $.get('/users?' + $.param({ active: active, roles: roleFilters() }), function(users) {
      renderUsers(users)

      // Apply username search
      $userNameQuery.trigger('input')

      if (userId) {
        var $selected = $userList.find('.result[data-id=' + userId + ']')
        openDetails($selected)
        var top = $selected.offset().top - 25
        $('body,html').animate({ scrollTop: top })
      }
    })
  })

  $userList.on('click', '.result', function() {
    var $this = $(this)
    if ($this.hasClass('selected')) {
      closeDetails()
    } else {
      closeDetails()
      openDetails($this)
    }
  })

  $page.find('.new-user button').on('click', function() {
    var $newUserForm = renderNewUserForm($newUserType.select2('val'))

    closeDetails()
    $userList.addClass('selected').prepend($newUserForm)
    $newUserForm.slideDown()
  })

  $userNameQuery.on('input', function() {
    var searchString = $(this).val().toLowerCase()

    $userList.find('.result').each(function() {
      var name = $(this).children('.name').text().toLowerCase()
      if (_.contains(name, searchString)) {
        $(this).show()
      } else {
        $(this).hide()
      }
    })
    closeDetails()
  })

  $page.find('.filters').change(function() { $page.trigger('show') })

  function updateLocationHash(userId) {
    setLocation('#kayttajat/' + userId)
  }

  function renderUsers(users) {
    _(users).sortBy('name').map(renderUser).forEach(function(u) { $userList.append(u) })
  }

  function renderUser(user) {
   return $('
', { class: 'result', 'data-id': user._id })
     .data('user', user).data('id', user._id)
     .append($('', { class: 'name' }).text(user.name))
     .append($('', { class: 'username' }).text(user.username))
     .append($('', { class: 'role' }).html(enums.util.userRoleName(user.role) || ''))
     .append($('', { class: 'cert-end' }).html(renderCertEnd(user)))
     .toggleClass('inactive', !user.active)
  }

  function renderCertEnd(user) {
    if (!enums.util.isClassifier(user.role)) return ''

    if (user.certificateEndDate) {
      var certEnd = moment(user.certificateEndDate)
      return $('').text(certEnd.format(utils.dateFormat))
        .toggleClass('expires-soon', certEnd.isBefore(moment().add(3, 'months')))
    } else {
      return ''
    }
  }

  function openDetails($row) {
    var user = $row.data('user')
    var $userDetails = renderExistingUserDetails(user)
    $row.addClass('selected').after($userDetails)
    updateLocationHash(user._id)
    $userDetails.slideDown()
  }

  function closeDetails() {
    $userList.find('.result.selected').removeClass('selected')
    $userList.find('.user-details').slideUp(function() { $(this).remove() })
    updateLocationHash('')
  }

  function renderNewUserForm(role) {
    var $detailTemplate = renderUserDetails(null, role)

    $detailTemplate.submit(function(event) {
      event.preventDefault()

      var $this = $(this)
      var userData = getUserData($this)
      userData.role = role
      userData.active = true

      if (enums.util.isClassifier(role)) {
        userData = _.merge(userData, getClassifierData($this))
      }

      $.post('/users/new', JSON.stringify(userData), function(newUser) {
        $userList.find('.result.selected').data('user', newUser)
        var $user = renderUser(newUser).css('display', 'none')
        $userList.prepend($user)
        $user.slideToggle()
        closeDetails()
      })
    })

    return $detailTemplate
  }

  function renderExistingUserDetails(selectedUser) {
    var $detailTemplate = renderUserDetails(selectedUser)

    $detailTemplate.find('input[name=active]').prop('disabled', selectedUser.username === user.username)

    $detailTemplate.submit(function(event) {
      event.preventDefault()

      var $this = $(this)
      var userData = getUserData($this)

      if (enums.util.isClassifier(selectedUser.role)) {
        userData = _.merge(userData, getClassifierData($this))
      }

      $.post('/users/' + selectedUser._id, JSON.stringify(userData), function(updatedUser) {
        $userList.find('.result.selected').replaceWith(renderUser(updatedUser))
        closeDetails()
      })
    })

    return $detailTemplate
  }

  function renderUserDetails(user, role) {
    var $detailTemplate = $('#templates').find('.user-details').clone()
    var isNewUser = user == null
    var isClassifier = enums.util.isClassifier(role) || user && enums.util.isClassifier(user.role)

    if (isClassifier) {
      $detailTemplate.find('form .classifier').append($('#templates').find('.classifier-details').clone())

      var $endDate = $detailTemplate.find('input[name=certificateEndDate]')
        .pikaday(_.defaults({ defaultDate: moment().add('years', 5).toDate() }, pikadayDefaults))

      $detailTemplate.find('input[name=certificateStartDate]')
        .pikaday(_.defaults({ onSelect: function(date) {
          $endDate.pikaday('setMoment', moment(date).add('years', 5))
      }}, pikadayDefaults))

      select2Autocomplete({
        $el: $detailTemplate.find('input[name=employers]'),
        path: employersSearch,
        multiple: true,
        toOption: idNamePairToSelect2Option,
        fromOption: select2OptionToIdNamePair
      })
    }

    if (isNewUser) {
      $detailTemplate.find('.modify-only').remove()
      $detailTemplate.find('input:required:disabled').prop('disabled', false)
    } else {
      populate($detailTemplate, user)

      if (hasRole('root')) $detailTemplate.append(changeLog(user).render())
    }

    $detailTemplate.find('.active-toggle').on('click', function() {
      var $selected = $userList.find('.result.selected')
      var active = $selected.next().find('.active-toggle').hasClass('inactive')
      $.post('/users/' + user._id, JSON.stringify({active: active}), function(updatedUser) {
        $selected.toggleClass('inactive', !updatedUser.active)
        toggleActiveButton($selected.next(), updatedUser.active)
        $selected.data('user', updatedUser)
        closeDetails()
      })
    })

    $detailTemplate.find('form').on('input change', _.debounce(function() { $(this).trigger('validate') }, 200))

    $detailTemplate.find('form').on('validate', function() {
      $(this).find('button[type=submit]').prop('disabled', !this.checkValidity())
    })

    $detailTemplate.find('input').on('blur select2-blur', function() {
      $(this).addClass('touched')
    })

    $detailTemplate.find('input[name=username]').on('input', function() {
      var $username = $(this)
      validateUsername($username, $detailTemplate)
    })

    $detailTemplate.find('input[name=employers]').change(toggleInvalid).each(toggleInvalid)

    return $detailTemplate.css('display', 'none')

    function employersSearch(term) {
      return '/accounts/search?q=' + encodeURIComponent(term) + '&roles=Classifier' // todo: only classifier?
    }

    function populate($element, user) {
      var cStartDate = user.certificateStartDate ? moment(user.certificateStartDate).format(utils.dateFormat) : ''
      var cEndDate = user.certificateEndDate ? moment(user.certificateEndDate).format(utils.dateFormat) : ''

      $element.find('input[name=name]').val(user.name).end()
        .find('input[name=email]').val(user.emails[0]).end()
        .find('input[name=username]').val(user.username).end()
        .find('input[name=phoneNumber]').val(user.phoneNumber).end()
        .find('input[name=certificateStartDate]').val(cStartDate).end()
        .find('input[name=certificateEndDate]').val(cEndDate).end()
        .find('textarea[name=comment]').val(user.comment).end()
        .find('input[name=employers]').trigger('setVal', user.employers).end()
      toggleActiveButton($element, user.active)
    }

    function toggleInvalid() {
      $(this).toggleClass('invalid', !this.checkValidity())
    }

    function toggleActiveButton($details, active) {
      $details
        .find('.active-toggle')
        .text(active ? "Käyttäjä aktiivinen" : "Käyttäjä ei aktiivinen")
        .toggleClass('inactive', !active)
    }
  }

  function getUserData($details) {
    return {
      name: $details.find('input[name=name]').val(),
      emails: [ $details.find('input[name=email]').val() ],
      username: $details.find('input[name=username]').val(),
      active: $details.find('input[name=active]').prop('checked'),
      phoneNumber: $details.find('input[name=phoneNumber]').val()
    }
  }

  function getClassifierData($details) {
    return {
      certificateStartDate: moment($details.find('input[name=certificateStartDate]').val(), utils.dateFormat),
      certificateEndDate: moment($details.find('input[name=certificateEndDate]').val(), utils.dateFormat),
      employers: $details.find('input[name=employers]').select2('data').map(select2OptionToIdNamePair),
      comment: $details.find('textarea[name=comment]').val()
    }
  }

  var usernameValidator = _.debounce((function() {
    var getLatestAjax = switchLatestDeferred()
    return function(username, $username, $detailTemplate) {
      getLatestAjax($.get('/users/exists/' + encodeURIComponent(username)), $username.siblings('i.fa-spinner'))
        .done(function(data) {
          $username.get(0).setCustomValidity(data.exists ? 'Username taken' : '')
          $username.removeClass('pending')
          $detailTemplate.find('form').trigger('validate')
        })
      }
  })(), 300)

  function validateUsername($username, $detailTemplate) {
    $username.get(0).setCustomValidity('Checking username')
    $username.addClass('touched')
    var username = $username.val().trim()
    if (username) {
      $username.addClass('pending')
      usernameValidator(username, $username, $detailTemplate)
    }
  }

  function roleFilters() {
    return $page.find('.filters input.role').filter(':checked').map(function() { return $(this).attr('name') }).toArray()
  }
}
<commit_msg>Only allow creating trainees in the "training" environment<commit_after>function userManagementPage() {
  var $page = $('#user-management-page')
  var $userList = $page.find('.user-list')
  var $userNameQuery = $page.find('#user-name-query')

  var $newUserType = $page.find('.new-user input[name="new-user-type"]')

  $.get('/environment', function(data) {
    var userRoles = data.environment != 'training' ? _.omit(enums.userRoles, 'trainee') : enums.userRoles
    $newUserType.select2({
      data: _.map(userRoles, function(roleValue, roleKey) {
        return { id: roleKey, text: roleValue.name }
      }),
      minimumResultsForSearch: -1
    }).select2('val', 'user')
  })

  $page.on('show', function(event, userId) {
    updateLocationHash(userId || '')
    $userList.empty()
    var active = $page.find('.filters input[name=active]').prop('checked')
    $.get('/users?' + $.param({ active: active, roles: roleFilters() }), function(users) {
      renderUsers(users)

      // Apply username search
      $userNameQuery.trigger('input')

      if (userId) {
        var $selected = $userList.find('.result[data-id=' + userId + ']')
        openDetails($selected)
        var top = $selected.offset().top - 25
        $('body,html').animate({ scrollTop: top })
      }
    })
  })

  $userList.on('click', '.result', function() {
    var $this = $(this)
    if ($this.hasClass('selected')) {
      closeDetails()
    } else {
      closeDetails()
      openDetails($this)
    }
  })

  $page.find('.new-user button').on('click', function() {
    var $newUserForm = renderNewUserForm($newUserType.select2('val'))

    closeDetails()
    $userList.addClass('selected').prepend($newUserForm)
    $newUserForm.slideDown()
  })

  $userNameQuery.on('input', function() {
    var searchString = $(this).val().toLowerCase()

    $userList.find('.result').each(function() {
      var name = $(this).children('.name').text().toLowerCase()
      if (_.contains(name, searchString)) {
        $(this).show()
      } else {
        $(this).hide()
      }
    })
    closeDetails()
  })

  $page.find('.filters').change(function() { $page.trigger('show') })

  function updateLocationHash(userId) {
    setLocation('#kayttajat/' + userId)
  }

  function renderUsers(users) {
    _(users).sortBy('name').map(renderUser).forEach(function(u) { $userList.append(u) })
  }

  function renderUser(user) {
   return $('
', { class: 'result', 'data-id': user._id })
     .data('user', user).data('id', user._id)
     .append($('', { class: 'name' }).text(user.name))
     .append($('', { class: 'username' }).text(user.username))
     .append($('', { class: 'role' }).html(enums.util.userRoleName(user.role) || ''))
     .append($('', { class: 'cert-end' }).html(renderCertEnd(user)))
     .toggleClass('inactive', !user.active)
  }

  function renderCertEnd(user) {
    if (!enums.util.isClassifier(user.role)) return ''

    if (user.certificateEndDate) {
      var certEnd = moment(user.certificateEndDate)
      return $('').text(certEnd.format(utils.dateFormat))
        .toggleClass('expires-soon', certEnd.isBefore(moment().add(3, 'months')))
    } else {
      return ''
    }
  }

  function openDetails($row) {
    var user = $row.data('user')
    var $userDetails = renderExistingUserDetails(user)
    $row.addClass('selected').after($userDetails)
    updateLocationHash(user._id)
    $userDetails.slideDown()
  }

  function closeDetails() {
    $userList.find('.result.selected').removeClass('selected')
    $userList.find('.user-details').slideUp(function() { $(this).remove() })
    updateLocationHash('')
  }

  function renderNewUserForm(role) {
    var $detailTemplate = renderUserDetails(null, role)

    $detailTemplate.submit(function(event) {
      event.preventDefault()

      var $this = $(this)
      var userData = getUserData($this)
      userData.role = role
      userData.active = true

      if (enums.util.isClassifier(role)) {
        userData = _.merge(userData, getClassifierData($this))
      }

      $.post('/users/new', JSON.stringify(userData), function(newUser) {
        $userList.find('.result.selected').data('user', newUser)
        var $user = renderUser(newUser).css('display', 'none')
        $userList.prepend($user)
        $user.slideToggle()
        closeDetails()
      })
    })

    return $detailTemplate
  }

  function renderExistingUserDetails(selectedUser) {
    var $detailTemplate = renderUserDetails(selectedUser)

    $detailTemplate.find('input[name=active]').prop('disabled', selectedUser.username === user.username)

    $detailTemplate.submit(function(event) {
      event.preventDefault()

      var $this = $(this)
      var userData = getUserData($this)

      if (enums.util.isClassifier(selectedUser.role)) {
        userData = _.merge(userData, getClassifierData($this))
      }

      $.post('/users/' + selectedUser._id, JSON.stringify(userData), function(updatedUser) {
        $userList.find('.result.selected').replaceWith(renderUser(updatedUser))
        closeDetails()
      })
    })

    return $detailTemplate
  }

  function renderUserDetails(user, role) {
    var $detailTemplate = $('#templates').find('.user-details').clone()
    var isNewUser = user == null
    var isClassifier = enums.util.isClassifier(role) || user && enums.util.isClassifier(user.role)

    if (isClassifier) {
      $detailTemplate.find('form .classifier').append($('#templates').find('.classifier-details').clone())

      var $endDate = $detailTemplate.find('input[name=certificateEndDate]')
        .pikaday(_.defaults({ defaultDate: moment().add('years', 5).toDate() }, pikadayDefaults))

      $detailTemplate.find('input[name=certificateStartDate]')
        .pikaday(_.defaults({ onSelect: function(date) {
          $endDate.pikaday('setMoment', moment(date).add('years', 5))
      }}, pikadayDefaults))

      select2Autocomplete({
        $el: $detailTemplate.find('input[name=employers]'),
        path: employersSearch,
        multiple: true,
        toOption: idNamePairToSelect2Option,
        fromOption: select2OptionToIdNamePair
      })
    }

    if (isNewUser) {
      $detailTemplate.find('.modify-only').remove()
      $detailTemplate.find('input:required:disabled').prop('disabled', false)
    } else {
      populate($detailTemplate, user)

      if (hasRole('root')) $detailTemplate.append(changeLog(user).render())
    }

    $detailTemplate.find('.active-toggle').on('click', function() {
      var $selected = $userList.find('.result.selected')
      var active = $selected.next().find('.active-toggle').hasClass('inactive')
      $.post('/users/' + user._id, JSON.stringify({active: active}), function(updatedUser) {
        $selected.toggleClass('inactive', !updatedUser.active)
        toggleActiveButton($selected.next(), updatedUser.active)
        $selected.data('user', updatedUser)
        closeDetails()
      })
    })

    $detailTemplate.find('form').on('input change', _.debounce(function() { $(this).trigger('validate') }, 200))

    $detailTemplate.find('form').on('validate', function() {
      $(this).find('button[type=submit]').prop('disabled', !this.checkValidity())
    })

    $detailTemplate.find('input').on('blur select2-blur', function() {
      $(this).addClass('touched')
    })

    $detailTemplate.find('input[name=username]').on('input', function() {
      var $username = $(this)
      validateUsername($username, $detailTemplate)
    })

    $detailTemplate.find('input[name=employers]').change(toggleInvalid).each(toggleInvalid)

    return $detailTemplate.css('display', 'none')

    function employersSearch(term) {
      return '/accounts/search?q=' + encodeURIComponent(term) + '&roles=Classifier' // todo: only classifier?
    }

    function populate($element, user) {
      var cStartDate = user.certificateStartDate ? moment(user.certificateStartDate).format(utils.dateFormat) : ''
      var cEndDate = user.certificateEndDate ? moment(user.certificateEndDate).format(utils.dateFormat) : ''

      $element.find('input[name=name]').val(user.name).end()
        .find('input[name=email]').val(user.emails[0]).end()
        .find('input[name=username]').val(user.username).end()
        .find('input[name=phoneNumber]').val(user.phoneNumber).end()
        .find('input[name=certificateStartDate]').val(cStartDate).end()
        .find('input[name=certificateEndDate]').val(cEndDate).end()
        .find('textarea[name=comment]').val(user.comment).end()
        .find('input[name=employers]').trigger('setVal', user.employers).end()
      toggleActiveButton($element, user.active)
    }

    function toggleInvalid() {
      $(this).toggleClass('invalid', !this.checkValidity())
    }

    function toggleActiveButton($details, active) {
      $details
        .find('.active-toggle')
        .text(active ? "Käyttäjä aktiivinen" : "Käyttäjä ei aktiivinen")
        .toggleClass('inactive', !active)
    }
  }

  function getUserData($details) {
    return {
      name: $details.find('input[name=name]').val(),
      emails: [ $details.find('input[name=email]').val() ],
      username: $details.find('input[name=username]').val(),
      active: $details.find('input[name=active]').prop('checked'),
      phoneNumber: $details.find('input[name=phoneNumber]').val()
    }
  }

  function getClassifierData($details) {
    return {
      certificateStartDate: moment($details.find('input[name=certificateStartDate]').val(), utils.dateFormat),
      certificateEndDate: moment($details.find('input[name=certificateEndDate]').val(), utils.dateFormat),
      employers: $details.find('input[name=employers]').select2('data').map(select2OptionToIdNamePair),
      comment: $details.find('textarea[name=comment]').val()
    }
  }

  var usernameValidator = _.debounce((function() {
    var getLatestAjax = switchLatestDeferred()
    return function(username, $username, $detailTemplate) {
      getLatestAjax($.get('/users/exists/' + encodeURIComponent(username)), $username.siblings('i.fa-spinner'))
        .done(function(data) {
          $username.get(0).setCustomValidity(data.exists ? 'Username taken' : '')
          $username.removeClass('pending')
          $detailTemplate.find('form').trigger('validate')
        })
      }
  })(), 300)

  function validateUsername($username, $detailTemplate) {
    $username.get(0).setCustomValidity('Checking username')
    $username.addClass('touched')
    var username = $username.val().trim()
    if (username) {
      $username.addClass('pending')
      usernameValidator(username, $username, $detailTemplate)
    }
  }

  function roleFilters() {
    return $page.find('.filters input.role').filter(':checked').map(function() { return $(this).attr('name') }).toArray()
  }
}
<|endoftext|>


<commit_before>var Leap = require('leapjs');

var controller = new Leap.Controller({ inNode: true });

var eventemitter;
var drone_state = 'landed';

var leap = function(emitter) {
	eventemitter = emitter;

	eventemitter.on('state', function(state) {
		drone_state = state;
	});
};

controller.on("frame", function(frame) {
	if (!drone_state !== 'inflight') {
		return;
	}

	if (frame.hands.length == 1) {
		var up_down_speed = frame.hands[0].palmVelocity[1];
		if (up_down_speed > 20) {
			eventemitter.emit('up', up_down_speed);
		} else if (up_down_speed < -20) {
			eventemitter.emit('down', -1 * up_down_speed);
		}

		var right_left_speed = frame.hands[0].palmNormal[0];
		if (right_left_speed > 0.15) {
			eventemitter.emit('left', right_left_speed);
		} else if (right_left_speed < -0.15) {
			eventemitter.emit('right', -1 * right_left_speed);
		}

		var forward_backward_speed = frame.hands[0].palmNormal[2];
		if (forward_backward_speed > 0.15) {
			eventemitter.emit('forward', forward_backward_speed);
		} else if (forward_backward_speed < -0.15) {
			eventemitter.emit('backward', -1 * forward_backward_speed);
		}

		eventemitter.emit('altitude', frame.hands[0].palmPosition[1]);

	} else if (frame.hands.length == 2) {
		eventemitter.emit('land');
	}
});

controller.on('ready', function() {
	console.log("ready");
});
controller.on('connect', function() {
	console.log("connect");
});

controller.on('disconnect', function() {
	console.log("disconnect -> land");
	eventemitter.emit('land');
});
controller.on('focus', function() {
	if (drone_ready) {
		console.log("focus -> takeoff");
		eventemitter.emit('takeoff');
	}
});
controller.on('blur', function() {
	console.log("blur");
});
controller.on('deviceConnected', function() {
	console.log("deviceConnected");
	eventemitter.emit('takeoff');
});
controller.on('deviceDisconnected', function() {
	console.log("deviceDisconnected -> land");
	eventemitter.emit('land');
});

controller.connect();

module.exports = leap;
<commit_msg>added takeoff after land if there is again one hand available<commit_after>var Leap = require('leapjs');

var controller = new Leap.Controller({ inNode: true });

var eventemitter;
var drone_state = 'none';

var leap = function(emitter) {
	eventemitter = emitter;

	eventemitter.on('state', function(state) {
		drone_state = state;
	});
};

controller.on("frame", function(frame) {
	if (drone_state === 'landed' && frame.hands.length == 1) {
		eventemitter.emit('takeoff');
		console.log("hand in -> takeoff");
	}

	if (!drone_state !== 'inflight') {
		return;
	}

	if (frame.hands.length == 1) {
		var up_down_speed = frame.hands[0].palmVelocity[1];
		if (up_down_speed > 20) {
			eventemitter.emit('up', up_down_speed);
		} else if (up_down_speed < -20) {
			eventemitter.emit('down', -1 * up_down_speed);
		}

		var right_left_speed = frame.hands[0].palmNormal[0];
		if (right_left_speed > 0.15) {
			eventemitter.emit('left', right_left_speed);
		} else if (right_left_speed < -0.15) {
			eventemitter.emit('right', -1 * right_left_speed);
		}

		var forward_backward_speed = frame.hands[0].palmNormal[2];
		if (forward_backward_speed > 0.15) {
			eventemitter.emit('forward', forward_backward_speed);
		} else if (forward_backward_speed < -0.15) {
			eventemitter.emit('backward', -1 * forward_backward_speed);
		}

		eventemitter.emit('altitude', frame.hands[0].palmPosition[1]);

	} else if (frame.hands.length == 2) {
		eventemitter.emit('land');
	}
});

controller.on('ready', function() {
	console.log("ready");
});
controller.on('connect', function() {
	console.log("connect");
});

controller.on('disconnect', function() {
	console.log("disconnect -> land");
	eventemitter.emit('land');
});
controller.on('focus', function() {
	if (drone_ready) {
		console.log("focus -> takeoff");
		eventemitter.emit('takeoff');
	}
});
controller.on('blur', function() {
	console.log("blur");
});
controller.on('deviceConnected', function() {
	console.log("deviceConnected");
	eventemitter.emit('takeoff');
});
controller.on('deviceDisconnected', function() {
	console.log("deviceDisconnected -> land");
	eventemitter.emit('land');
});

controller.connect();

module.exports = leap;
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

// @ts-check

const testWebLocation = require.resolve('@vscode/test-web');

const fs = require('fs');
const path = require('path');
const cp = require('child_process');

const minimist = require('minimist');
const fancyLog = require('fancy-log');
const ansiColors = require('ansi-colors');
const remote = require('gulp-remote-retry-src');
const vfs = require('vinyl-fs');
const opn = require('opn');

const APP_ROOT = path.join(__dirname, '..');
const WEB_DEV_EXTENSIONS_ROOT = path.join(APP_ROOT, '.build', 'builtInWebDevExtensions');

const WEB_PLAYGROUND_VERSION = '0.0.13';

async function main() {

	const args = minimist(process.argv.slice(2), {
		boolean: [
			'help',
			'playground'
		],
		string: [
			'host',
			'port',
			'extensionPath',
			'browser',
			'browserType'
		],
	});

	if (args.help) {
		console.log(
			'./scripts/code-web.sh|bat [options]\n' +
			' --playground             Include the vscode-web-playground extension (added by default if no folderPath is provided)\n'
		);
		startServer(['--help']);
		return;
	}

	const serverArgs = [];

	const HOST = args['host'] ?? 'localhost';
	const PORT = args['port'] ?? '8080';

	if (args['host'] === undefined) {
		serverArgs.push('--host', HOST);
	}
	if (args['port'] === undefined) {
		serverArgs.push('--port', PORT);
	}

	if (args['playground'] === true || (args['playground'] === undefined && args['_'].length === 0 && !args['--folder-uri'])) {
		serverArgs.push('--extensionPath', WEB_DEV_EXTENSIONS_ROOT);
		serverArgs.push('--folder-uri', 'memfs:///sample-folder');
		await ensureWebDevExtensions(args['verbose']);
	}

	let openSystemBrowser = false;
	if (!args['browser'] && !args['browserType']) {
		serverArgs.push('--browserType', 'none');
		openSystemBrowser = true;
	}

	serverArgs.push('--sourcesPath', APP_ROOT);

	serverArgs.push(...process.argv.slice(2).filter(v => !v.startsWith('--playground') && v !== '--no-playground'));

	startServer(serverArgs);
	if (openSystemBrowser) {
		opn(`http://${HOST}:${PORT}/`);
	}
}

function startServer(runnerArguments) {
	const env = { ...process.env };

	console.log(`Starting @vscode/test-web: ${testWebLocation} ${runnerArguments.join(' ')}`);
	const proc = cp.spawn(process.execPath, [testWebLocation, ...runnerArguments], { env, stdio: 'inherit' });

	proc.on('exit', (code) => process.exit(code));

	process.on('exit', () => proc.kill());
	process.on('SIGINT', () => {
		proc.kill();
		process.exit(128 + 2); // https://nodejs.org/docs/v14.16.0/api/process.html#process_signal_events
	});
	process.on('SIGTERM', () => {
		proc.kill();
		process.exit(128 + 15); // https://nodejs.org/docs/v14.16.0/api/process.html#process_signal_events
	});
}

async function directoryExists(path) {
	try {
		return (await fs.promises.stat(path)).isDirectory();
	} catch {
		return false;
	}
}

async function ensureWebDevExtensions(verbose) {

	// Playground (https://github.com/microsoft/vscode-web-playground)
	const webDevPlaygroundRoot = path.join(WEB_DEV_EXTENSIONS_ROOT, 'vscode-web-playground');
	const webDevPlaygroundExists = await directoryExists(webDevPlaygroundRoot);

	let downloadPlayground = false;
	if (webDevPlaygroundExists) {
		try {
			const webDevPlaygroundPackageJson = JSON.parse(((await fs.promises.readFile(path.join(webDevPlaygroundRoot, 'package.json'))).toString()));
			if (webDevPlaygroundPackageJson.version !== WEB_PLAYGROUND_VERSION) {
				downloadPlayground = true;
			}
		} catch (error) {
			downloadPlayground = true;
		}
	} else {
		downloadPlayground = true;
	}

	if (downloadPlayground) {
		if (verbose) {
			fancyLog(`${ansiColors.magenta('Web Development extensions')}: Downloading vscode-web-playground to ${webDevPlaygroundRoot}`);
		}
		await new Promise((resolve, reject) => {
			remote(['package.json', 'dist/extension.js', 'dist/extension.js.map'], {
				base: 'https://raw.githubusercontent.com/microsoft/vscode-web-playground/main/'
			}).pipe(vfs.dest(webDevPlaygroundRoot)).on('end', resolve).on('error', reject);
		});
	} else {
		if (verbose) {
			fancyLog(`${ansiColors.magenta('Web Development extensions')}: Using existing vscode-web-playground in ${webDevPlaygroundRoot}`);
		}
	}
}

main();
<commit_msg>code web script fix<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

// @ts-check

const testWebLocation = require.resolve('@vscode/test-web');

const fs = require('fs');
const path = require('path');
const cp = require('child_process');

const minimist = require('minimist');
const fancyLog = require('fancy-log');
const ansiColors = require('ansi-colors');
const remote = require('gulp-remote-retry-src');
const vfs = require('vinyl-fs');
const opn = require('opn');

const APP_ROOT = path.join(__dirname, '..');
const WEB_DEV_EXTENSIONS_ROOT = path.join(APP_ROOT, '.build', 'builtInWebDevExtensions');

const WEB_PLAYGROUND_VERSION = '0.0.13';

async function main() {

	const args = minimist(process.argv.slice(2), {
		boolean: [
			'help',
			'playground'
		],
		string: [
			'host',
			'port',
			'extensionPath',
			'browser',
			'browserType'
		],
	});

	if (args.help) {
		console.log(
			'./scripts/code-web.sh|bat [options]\n' +
			' --playground             Include the vscode-web-playground extension (added by default if no folderPath is provided)\n'
		);
		startServer(['--help']);
		return;
	}

	const serverArgs = [];

	const HOST = args['host'] ?? 'localhost';
	const PORT = args['port'] ?? '8080';

	if (args['host'] === undefined) {
		serverArgs.push('--host', HOST);
	}
	if (args['port'] === undefined) {
		serverArgs.push('--port', PORT);
	}
	if (args['playground'] === true || (args['_'].length === 0 && !args['--folder-uri'])) {
		serverArgs.push('--extensionPath', WEB_DEV_EXTENSIONS_ROOT);
		serverArgs.push('--folder-uri', 'memfs:///sample-folder');
		await ensureWebDevExtensions(args['verbose']);
	}

	let openSystemBrowser = false;
	if (!args['browser'] && !args['browserType']) {
		serverArgs.push('--browserType', 'none');
		openSystemBrowser = true;
	}

	serverArgs.push('--sourcesPath', APP_ROOT);

	serverArgs.push(...process.argv.slice(2).filter(v => !v.startsWith('--playground') && v !== '--no-playground'));

	startServer(serverArgs);
	if (openSystemBrowser) {
		opn(`http://${HOST}:${PORT}/`);
	}
}

function startServer(runnerArguments) {
	const env = { ...process.env };

	console.log(`Starting @vscode/test-web: ${testWebLocation} ${runnerArguments.join(' ')}`);
	const proc = cp.spawn(process.execPath, [testWebLocation, ...runnerArguments], { env, stdio: 'inherit' });

	proc.on('exit', (code) => process.exit(code));

	process.on('exit', () => proc.kill());
	process.on('SIGINT', () => {
		proc.kill();
		process.exit(128 + 2); // https://nodejs.org/docs/v14.16.0/api/process.html#process_signal_events
	});
	process.on('SIGTERM', () => {
		proc.kill();
		process.exit(128 + 15); // https://nodejs.org/docs/v14.16.0/api/process.html#process_signal_events
	});
}

async function directoryExists(path) {
	try {
		return (await fs.promises.stat(path)).isDirectory();
	} catch {
		return false;
	}
}

async function ensureWebDevExtensions(verbose) {

	// Playground (https://github.com/microsoft/vscode-web-playground)
	const webDevPlaygroundRoot = path.join(WEB_DEV_EXTENSIONS_ROOT, 'vscode-web-playground');
	const webDevPlaygroundExists = await directoryExists(webDevPlaygroundRoot);

	let downloadPlayground = false;
	if (webDevPlaygroundExists) {
		try {
			const webDevPlaygroundPackageJson = JSON.parse(((await fs.promises.readFile(path.join(webDevPlaygroundRoot, 'package.json'))).toString()));
			if (webDevPlaygroundPackageJson.version !== WEB_PLAYGROUND_VERSION) {
				downloadPlayground = true;
			}
		} catch (error) {
			downloadPlayground = true;
		}
	} else {
		downloadPlayground = true;
	}

	if (downloadPlayground) {
		if (verbose) {
			fancyLog(`${ansiColors.magenta('Web Development extensions')}: Downloading vscode-web-playground to ${webDevPlaygroundRoot}`);
		}
		await new Promise((resolve, reject) => {
			remote(['package.json', 'dist/extension.js', 'dist/extension.js.map'], {
				base: 'https://raw.githubusercontent.com/microsoft/vscode-web-playground/main/'
			}).pipe(vfs.dest(webDevPlaygroundRoot)).on('end', resolve).on('error', reject);
		});
	} else {
		if (verbose) {
			fancyLog(`${ansiColors.magenta('Web Development extensions')}: Using existing vscode-web-playground in ${webDevPlaygroundRoot}`);
		}
	}
}

main();
<|endoftext|>


<commit_before>var url = require('url');
var fs = require('fs');
var _ = require('lodash');
var async = require('async');
var Docker = require('dockerode');
var DockerUtils = require('./DockerUtils');

function Runner() {
}

Runner.prototype.init = function(bosco, next) {
  this.bosco = bosco;

  function readCert(certPath, certFile) {
    return fs.readFileSync(certPath + '/' + certFile, {encoding: 'utf-8'});
  }

  if (process.env.DOCKER_HOST) {
    // We are likely on OSX and Boot2docker
    var dockerUrl = url.parse(process.env.DOCKER_HOST || 'tcp://127.0.0.1:3000');
    var dockerOpts = {
      host: dockerUrl.hostname,
      port: dockerUrl.port,
    };

    var dockerCertPath = process.env.DOCKER_CERT_PATH;
    if (dockerCertPath) {
      dockerOpts = _.extend(dockerOpts, {
        protocol: 'https',
        ca: readCert(dockerCertPath, 'ca.pem'),
        cert: readCert(dockerCertPath, 'cert.pem'),
        key: readCert(dockerCertPath, 'key.pem'),
      });
    }

    this.docker = new Docker(dockerOpts);
  } else {
    // Assume we are on linux and so connect on a socket
    this.docker = new Docker({socketPath: '/var/run/docker.sock'});
  }
  next();
};

Runner.prototype.disconnect = function(next) {
  return next();
};

Runner.prototype.list = function(detailed, next) {
  var self = this;
  var docker = self.docker;
  docker.listContainers({
    all: false,
  }, function(err, containers) {
    if (!detailed) return next(err, _.map(containers, 'Names'));
    next(err, containers);
  });
};

Runner.prototype.stop = function(options, next) {
  var self = this;
  var docker = self.docker;
  docker.listContainers({
    all: false,
  }, function(err, containers) {
    var toStop = [];
    containers.forEach(function(container) {
      if (self.containerNameMatches(container, options.service.name)) {
        var cnt = docker.getContainer(container.Id);
        self.bosco.log('Stopping ' + options.service.name.green);
        toStop.push(cnt);
      }
    });
    async.map(toStop, function(container, cb) {
      container.stop(cb);
    }, next);
  });
};

Runner.prototype.start = function(options, next) {
  var self = this;
  var docker = self.docker;
  var dockerFqn = self.getFqn(options);

  DockerUtils.prepareImage(self.bosco, docker, dockerFqn, options, function(err) {
    if (err) return next(err);

    DockerUtils.createContainer(docker, dockerFqn, options, function(err, container) {
      if (err) return next(err);
      DockerUtils.startContainer(self.bosco, docker, dockerFqn, options, container, next);
    });
  });
};

Runner.prototype.update = function(options, next) {
  var self = this;
  var docker = self.docker;

  if (options.service.docker && options.service.docker.build) return next();

  var dockerFqn = self.getFqn(options);
  DockerUtils.pullImage(self.bosco, docker, dockerFqn, next);
};

Runner.prototype.getFqn = function(options) {
  var dockerFqn = '';
  var service = options.service;
  if (service.docker) {
    if (service.docker.image) {
      dockerFqn = service.docker.image;
    }
    if (!dockerFqn && service.docker.build) {
      dockerFqn = 'local/' + service.name;
    }
    if (dockerFqn && dockerFqn.indexOf(':') === -1) {
      dockerFqn += ':latest';
    }
    if (dockerFqn) {
      return dockerFqn;
    }
  }

  if (service.registry) dockerFqn += service.registry + '/';
  if (service.username) dockerFqn += service.username + '/';
  return dockerFqn + service.name + ':' + (service.version || 'latest');
};

Runner.prototype.matchWithoutVersion = function(a, b) {
  var realA = a.slice(0, a.lastIndexOf(':'));
  var realB = b.slice(0, b.lastIndexOf(':'));
  return realA === realB;
};

Runner.prototype.containerNameMatches = function(container, name) {
  return _.some(container.Names, function(val) {
    return val === '/' + name;
  });
};

module.exports = new Runner();
<commit_msg>Pass through local.tescloud.com to refer to host to all docker containers by default<commit_after>var url = require('url');
var fs = require('fs');
var _ = require('lodash');
var async = require('async');
var Docker = require('dockerode');
var DockerUtils = require('./DockerUtils');

function Runner() {
}

Runner.prototype.init = function(bosco, next) {
  this.bosco = bosco;

  function readCert(certPath, certFile) {
    return fs.readFileSync(certPath + '/' + certFile, {encoding: 'utf-8'});
  }

  if (process.env.DOCKER_HOST) {
    // We are likely on OSX and Boot2docker
    var dockerUrl = url.parse(process.env.DOCKER_HOST || 'tcp://127.0.0.1:3000');
    var dockerOpts = {
      host: dockerUrl.hostname,
      port: dockerUrl.port,
    };

    var dockerCertPath = process.env.DOCKER_CERT_PATH;
    if (dockerCertPath) {
      dockerOpts = _.extend(dockerOpts, {
        protocol: 'https',
        ca: readCert(dockerCertPath, 'ca.pem'),
        cert: readCert(dockerCertPath, 'cert.pem'),
        key: readCert(dockerCertPath, 'key.pem'),
      });
    }

    this.docker = new Docker(dockerOpts);
  } else {
    // Assume we are on linux and so connect on a socket
    this.docker = new Docker({socketPath: '/var/run/docker.sock'});
  }
  next();
};

Runner.prototype.disconnect = function(next) {
  return next();
};

Runner.prototype.list = function(detailed, next) {
  var self = this;
  var docker = self.docker;
  docker.listContainers({
    all: false,
  }, function(err, containers) {
    if (!detailed) return next(err, _.map(containers, 'Names'));
    next(err, containers);
  });
};

Runner.prototype.stop = function(options, next) {
  var self = this;
  var docker = self.docker;
  docker.listContainers({
    all: false,
  }, function(err, containers) {
    var toStop = [];
    containers.forEach(function(container) {
      if (self.containerNameMatches(container, options.service.name)) {
        var cnt = docker.getContainer(container.Id);
        self.bosco.log('Stopping ' + options.service.name.green);
        toStop.push(cnt);
      }
    });
    async.map(toStop, function(container, cb) {
      container.stop(cb);
    }, next);
  });
};

Runner.prototype.start = function(options, next) {
  var self = this;
  var docker = self.docker;
  var dockerFqn = self.getFqn(options);

  var defaultLocalHost = self.bosco.config.get('docker:localhost') || 'local.tescloud.com';
  if (options.service.docker.HostConfig) {
    options.service.docker.HostConfig.ExtraHosts = options.service.docker.HostConfig.ExtraHosts || [];
    options.service.docker.HostConfig.ExtraHosts.push(defaultLocalHost + ':' + self.bosco.options.ip);
  }

  DockerUtils.prepareImage(self.bosco, docker, dockerFqn, options, function(err) {
    if (err) return next(err);

    DockerUtils.createContainer(docker, dockerFqn, options, function(err, container) {
      if (err) return next(err);
      DockerUtils.startContainer(self.bosco, docker, dockerFqn, options, container, next);
    });
  });
};

Runner.prototype.update = function(options, next) {
  var self = this;
  var docker = self.docker;

  if (options.service.docker && options.service.docker.build) return next();

  var dockerFqn = self.getFqn(options);
  DockerUtils.pullImage(self.bosco, docker, dockerFqn, next);
};

Runner.prototype.getFqn = function(options) {
  var dockerFqn = '';
  var service = options.service;
  if (service.docker) {
    if (service.docker.image) {
      dockerFqn = service.docker.image;
    }
    if (!dockerFqn && service.docker.build) {
      dockerFqn = 'local/' + service.name;
    }
    if (dockerFqn && dockerFqn.indexOf(':') === -1) {
      dockerFqn += ':latest';
    }
    if (dockerFqn) {
      return dockerFqn;
    }
  }

  if (service.registry) dockerFqn += service.registry + '/';
  if (service.username) dockerFqn += service.username + '/';
  return dockerFqn + service.name + ':' + (service.version || 'latest');
};

Runner.prototype.matchWithoutVersion = function(a, b) {
  var realA = a.slice(0, a.lastIndexOf(':'));
  var realB = b.slice(0, b.lastIndexOf(':'));
  return realA === realB;
};

Runner.prototype.containerNameMatches = function(container, name) {
  return _.some(container.Names, function(val) {
    return val === '/' + name;
  });
};

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


<commit_before>import { createAction, createThunkAction } from 'redux-tools';

// Actions
import { setContextActiveLayers } from 'pages/app/pulse/layer-pill/actions';

// Components
import LayerGlobeManager from 'utils/layers/LayerGlobeManager';

export const resetLayerPoints = createAction('layer-menu-dropdown/resetLayerPoints');
export const setActiveLayer = createAction('layer-menu-dropdown/setActiveLayer');
export const setActiveLayerLoading = createAction('layer-menu-dropdown/setActiveLayerLoading');
export const setActiveLayerError = createAction('layer-menu-dropdown/setActiveLayerError');

export const toggleActiveLayer = createThunkAction('layer-menu-dropdown/toggleActiveLayer', ({
  id,
  threedimensional,
  markerType,
  basemap,
  contextLayers,
  descriptionPulse,
  contextLayersOnTop
}) =>
  (dispatch) => {
    if (id) {
      // Clear the possible active layers from the previous layer selection
      dispatch(setContextActiveLayers([]));
      dispatch(setActiveLayerLoading(true));

      fetch(new Request(`${process.env.WRI_API_URL}/layer/${id}`))
        .then((response) => {
          if (response.ok) return response.json();
          throw new Error(response.statusText);
        })
        .then(async (response) => {
          const layer = response.data;
          layer.threedimensional = threedimensional;
          layer.markerType = markerType;
          layer.contextLayersOnTop = contextLayersOnTop;
          layer.basemap = basemap;
          layer.contextLayers = [];
          layer.descriptionPulse = descriptionPulse;

          if (contextLayers.length > 0) {
            let layersLoaded = 0;
            const urlSt = `${process.env.WRI_API_URL}/layer/?ids=${contextLayers.join()}&env=production,preproduction`;
            fetch(new Request(urlSt))
              .then((resp) => {
                return resp.json();
              })
              .then((res) => {
                const layerGlobeManager = new LayerGlobeManager();
                res.data.forEach((l) => {
                  layerGlobeManager.addLayer(
                    { ...l.attributes, id: l.id },
                    {
                      onLayerAddedSuccess: function success(result) {
                        layer.contextLayers.push(result);
                        layersLoaded++;
                        if (contextLayers.length === layersLoaded) {
                          dispatch(setActiveLayer(layer));
                        }
                      }
                    },
                    true
                  );
                });
              });
          } else {
            dispatch(setActiveLayer(layer));
          }
        })
        .catch((error) => {
          // Fetch from server ko -> Dispatch error
          dispatch(setActiveLayerError(error));
        });
    } else {
      dispatch(setActiveLayer(null));
    }
  });
<commit_msg>some progress to get rid of the state in the pulse page<commit_after>import { createAction, createThunkAction } from 'redux-tools';

// Actions
import { setContextActiveLayers } from 'pages/app/pulse/layer-pill/actions';

// Components
import LayerGlobeManager from 'utils/layers/LayerGlobeManager';

export const resetLayerPoints = createAction('layer-menu-dropdown/resetLayerPoints');
export const setActiveLayer = createAction('layer-menu-dropdown/setActiveLayer');
export const setActiveLayerLoading = createAction('layer-menu-dropdown/setActiveLayerLoading');
export const setActiveLayerError = createAction('layer-menu-dropdown/setActiveLayerError');

export const toggleActiveLayer = createThunkAction('layer-menu-dropdown/toggleActiveLayer', ({
  id,
  threedimensional,
  markerType,
  basemap,
  contextLayers,
  descriptionPulse,
  contextLayersOnTop
}) =>
  (dispatch) => {
    if (id) {
      // Clear the possible active layers from the previous layer selection
      dispatch(setContextActiveLayers([]));
      dispatch(setActiveLayerLoading(true));

      const layerGlobeManager = new LayerGlobeManager();

      fetch(new Request(`${process.env.WRI_API_URL}/layer/${id}`))
        .then((response) => {
          if (response.ok) return response.json();
          throw new Error(response.statusText);
        })
        .then(async (response) => {
          const layer = response.data;
          layer.threedimensional = threedimensional;
          layer.markerType = markerType;
          layer.contextLayersOnTop = contextLayersOnTop;
          layer.basemap = basemap;
          layer.contextLayers = [];
          layer.descriptionPulse = descriptionPulse;

          layerGlobeManager.addLayer(
            layer.attributes,
            {
              onLayerAddedSuccess: function success(result) {
                layer.url = result.url;
              }
            },
            true
          );

          if (contextLayers.length > 0) {
            let layersLoaded = 0;
            const urlSt = `${process.env.WRI_API_URL}/layer/?ids=${contextLayers.join()}&env=production,preproduction`;
            fetch(new Request(urlSt))
              .then((resp) => {
                return resp.json();
              })
              .then((res) => {
                res.data.forEach((l) => {
                  layerGlobeManager.addLayer(
                    { ...l.attributes, id: l.id },
                    {
                      onLayerAddedSuccess: function success(result) {
                        layer.contextLayers.push(result);
                        layersLoaded++;
                        if (contextLayers.length === layersLoaded) {
                          dispatch(setActiveLayer(layer));
                        }
                      }
                    },
                    true
                  );
                });
              });
          } else {
            dispatch(setActiveLayer(layer));
          }
        })
        .catch((error) => {
          // Fetch from server ko -> Dispatch error
          dispatch(setActiveLayerError(error));
        });
    } else {
      dispatch(setActiveLayer(null));
    }
  });
<|endoftext|>


<commit_before>
zeit.cms.declare_namespace('zeit.content.cp');

zeit.cms.in_cp_editor = function() {
    return Boolean(jQuery('.cp-editor-inner').length);
};

zeit.content.cp.BlockHover = gocept.Class.extend({

    construct: function() {
        var self = this;
        MochiKit.Signal.connect('cp-content', 'onmouseover', self, self.over);
        MochiKit.Signal.connect('cp-content', 'onmouseout', self, self.out);
    },

    over: function(event) {
        var self = this;
        var block = self.get_block(event.target());
        if (!isNull(block)) {
            MochiKit.DOM.addElementClass(block, 'hover');
        }
    },

    out: function(event) {
        var self = this;
        var block = self.get_block(event.target());
        if (!isNull(block)) {
            MochiKit.DOM.removeElementClass(block, 'hover');
        }
    },

    get_block: function(element) {
        var css_class = 'block';
        if (MochiKit.DOM.hasElementClass(element, css_class)) {
            return element;
        }
        return MochiKit.DOM.getFirstParentByTagAndClassName(
            element, null, css_class);
    }
});

MochiKit.Signal.connect(window, 'script-loading-finished', function() {
    if (! zeit.cms.in_cp_editor()) {
        return;
    }
    zeit.content.cp.block_hover = new zeit.content.cp.BlockHover();
});

zeit.content.cp.ContainerSorter = gocept.Class.extend({

    construct: function(container_type) {
        var self = this;
        self.sorters = [];
        self.container_type = container_type;
        self.selector = '.type-' + container_type;
        self.__name__ = ('zeit.content.cp.ContainerSorter('
            + self.container_type + ')');
        new zeit.edit.context.Editor(self);
    },

    connect: function() {
        var self = this;
        jQuery(self.selector).each(function() {
            var sorter = new zeit.edit.sortable.BlockSorter(
                this.id, '#' + this.id + ' > div.block-inner');
            sorter.__name__ = ('zeit.content.cp.BlockSorter('
                + self.container_type + ', id=' + this.id + ')');
            self.sorters.push(sorter);
        });
    },

    disconnect: function() {
        var self = this;
        while (self.sorters.length) {
            var sorter = self.sorters.pop();
            log("Destroying sorter " + sorter.container);
            sorter.__context__.deactivate();
            sorter.__context__.destroy();
        }
    }

});

MochiKit.Signal.connect(window, 'script-loading-finished', function() {
    if (! zeit.cms.in_cp_editor()) {
        return;
    }

    zeit.content.cp.body_sorter = new zeit.edit.sortable.BlockSorter(
        'body', '#body > div.block-inner');
    zeit.content.cp.body_sorter.__name__ = (
        'zeit.content.cp.ContainerSorter(body)');

    zeit.content.cp.region_sorter = new zeit.content.cp.ContainerSorter(
        'region');
    zeit.content.cp.area_sorter = new zeit.content.cp.ContainerSorter('area');
});

(function() {

    var added = function(id) {
        log('added');
        log('added ' + id);
        if (isNull($(id))) {
            log("Added but not found: " + id);
            return;
        }
        log('Added ' + id + $(id));
        MochiKit.Style.setOpacity($(id), 0.0);
        MochiKit.Visual.appear(id);
        MochiKit.Async.callLater(2, function() {
            $(id).style['opacity'] = 1;
        });
    };

    var deleted  = function(id) {
        log('Deleted ' + id + $(id));
        MochiKit.Visual.fade(id, {duration: 0.5,
                                  to: 0.01});
    };

    var ident = MochiKit.Signal.connect(
        window, 'script-loading-finished', function() {
            MochiKit.Signal.disconnect(ident);
            if (! zeit.cms.in_cp_editor()) {
                return;
            }
            MochiKit.Signal.connect(zeit.edit.editor, 'added', added);
            MochiKit.Signal.connect(zeit.edit.editor, 'deleted', deleted);
    });
}());

zeit.content.cp.makeBoxesEquallyHigh = function(container) {
    // check for unloaded images:

    log("fixing box heights.", container.id);
    var images = MochiKit.DOM.getElementsByTagAndClassName(
        'img', null, container);
    var exit = false;
    forEach(images, function(image) {
        if (!image.height) {
            exit = true;
            throw MochiKit.Iter.StopIteration;
        }
    });
    if (exit) {
        MochiKit.Async.callLater(
            0.25, zeit.content.cp.makeBoxesEquallyHigh, container);
        return;
    }

    var max_height = 0;
    var blocks = [];
    forEach($(container).childNodes, function(block) {
        if (block.nodeType != block.ELEMENT_NODE) {
            return;
        }
        if (!MochiKit.DOM.hasElementClass(block, 'block')) {
            return;
        }
        var block_inner = MochiKit.DOM.getFirstElementByTagAndClassName(
            'div', 'block-inner', block);
        if (isNull(block)) {
            return;
        }
        blocks.push(block_inner);
        var height = MochiKit.Style.getStyle(block_inner, 'height');
        MochiKit.Style.setStyle(block_inner, {'height': 'auto'});
        var dim = MochiKit.Style.getElementDimensions(block_inner, true);
        MochiKit.Style.setStyle(block_inner, {'height': height});
        max_height = Math.max(max_height, dim.h);
    });

    forEach(blocks, function(block) {
        var new_dim = new MochiKit.Style.Dimensions(null, max_height);
        MochiKit.Style.setElementDimensions(block, new_dim);
    });
};

(function() {

    var fix_box_heights = function() {
        log('fixing box heights');
        forEach($$('#teaser-mosaic > .block.type-teaser-bar > .block-inner'),
            function(bar) {
                if (MochiKit.DOM.hasElementClass(bar.parentNode, 'parquet')) {
                    return;
                }
                log('fixing box heights for', bar.id);
                try {
                    zeit.content.cp.makeBoxesEquallyHigh(bar);
                } catch (e) {
                    log("Error", e);
                }
        });
    };

    var ident = MochiKit.Signal.connect(
        window, 'script-loading-finished', function() {
            MochiKit.Signal.disconnect(ident);
            if (! zeit.cms.in_cp_editor()) {
                return;
            }
            MochiKit.Signal.connect(
                zeit.edit.editor, 'after-reload', fix_box_heights);
        });
}());
<commit_msg>Re VIV-621: Remove unneeded styling code that was only used for horizontal blocks in teaser bars<commit_after>
zeit.cms.declare_namespace('zeit.content.cp');

zeit.cms.in_cp_editor = function() {
    return Boolean(jQuery('.cp-editor-inner').length);
};

zeit.content.cp.BlockHover = gocept.Class.extend({

    construct: function() {
        var self = this;
        MochiKit.Signal.connect('cp-content', 'onmouseover', self, self.over);
        MochiKit.Signal.connect('cp-content', 'onmouseout', self, self.out);
    },

    over: function(event) {
        var self = this;
        var block = self.get_block(event.target());
        if (!isNull(block)) {
            MochiKit.DOM.addElementClass(block, 'hover');
        }
    },

    out: function(event) {
        var self = this;
        var block = self.get_block(event.target());
        if (!isNull(block)) {
            MochiKit.DOM.removeElementClass(block, 'hover');
        }
    },

    get_block: function(element) {
        var css_class = 'block';
        if (MochiKit.DOM.hasElementClass(element, css_class)) {
            return element;
        }
        return MochiKit.DOM.getFirstParentByTagAndClassName(
            element, null, css_class);
    }
});

MochiKit.Signal.connect(window, 'script-loading-finished', function() {
    if (! zeit.cms.in_cp_editor()) {
        return;
    }
    zeit.content.cp.block_hover = new zeit.content.cp.BlockHover();
});

zeit.content.cp.ContainerSorter = gocept.Class.extend({

    construct: function(container_type) {
        var self = this;
        self.sorters = [];
        self.container_type = container_type;
        self.selector = '.type-' + container_type;
        self.__name__ = ('zeit.content.cp.ContainerSorter('
            + self.container_type + ')');
        new zeit.edit.context.Editor(self);
    },

    connect: function() {
        var self = this;
        jQuery(self.selector).each(function() {
            var sorter = new zeit.edit.sortable.BlockSorter(
                this.id, '#' + this.id + ' > div.block-inner');
            sorter.__name__ = ('zeit.content.cp.BlockSorter('
                + self.container_type + ', id=' + this.id + ')');
            self.sorters.push(sorter);
        });
    },

    disconnect: function() {
        var self = this;
        while (self.sorters.length) {
            var sorter = self.sorters.pop();
            log("Destroying sorter " + sorter.container);
            sorter.__context__.deactivate();
            sorter.__context__.destroy();
        }
    }

});

MochiKit.Signal.connect(window, 'script-loading-finished', function() {
    if (! zeit.cms.in_cp_editor()) {
        return;
    }

    zeit.content.cp.body_sorter = new zeit.edit.sortable.BlockSorter(
        'body', '#body > div.block-inner');
    zeit.content.cp.body_sorter.__name__ = (
        'zeit.content.cp.ContainerSorter(body)');

    zeit.content.cp.region_sorter = new zeit.content.cp.ContainerSorter(
        'region');
    zeit.content.cp.area_sorter = new zeit.content.cp.ContainerSorter('area');
});

(function() {

    var added = function(id) {
        log('added');
        log('added ' + id);
        if (isNull($(id))) {
            log("Added but not found: " + id);
            return;
        }
        log('Added ' + id + $(id));
        MochiKit.Style.setOpacity($(id), 0.0);
        MochiKit.Visual.appear(id);
        MochiKit.Async.callLater(2, function() {
            $(id).style['opacity'] = 1;
        });
    };

    var deleted  = function(id) {
        log('Deleted ' + id + $(id));
        MochiKit.Visual.fade(id, {duration: 0.5,
                                  to: 0.01});
    };

    var ident = MochiKit.Signal.connect(
        window, 'script-loading-finished', function() {
            MochiKit.Signal.disconnect(ident);
            if (! zeit.cms.in_cp_editor()) {
                return;
            }
            MochiKit.Signal.connect(zeit.edit.editor, 'added', added);
            MochiKit.Signal.connect(zeit.edit.editor, 'deleted', deleted);
    });
}());
<|endoftext|>


<commit_before>var config = require('config');
var FeedbackModal = require('feedback-modal');
var FilterView = require('filter-view');
var HelpMeChoose = require('help-me-choose-view');
var LeafletTransitiveLayer = require('Leaflet.TransitiveLayer');
var LocationsView = require('locations-view');
var log = require('./client/log')('planner-page');
var showMapView = require('map-view');
var OptionsView = require('options-view');
var PlannerNav = require('planner-nav');
var querystring = require('querystring');
var scrollbarSize = require('scrollbar-size');
var scrolling = require('scrolling');
var session = require('session');
var textModal = require('text-modal');
//var transitive = require('transitive');
var ua = require('user-agent');
var view = require('view');
var showWelcomeWizard = require('welcome-flow');
var showPlannerWalkthrough = require('planner-walkthrough');
var geocode = require('geocode');

var FROM = config.geocode().start_address;
var TO = config.geocode().end_address;
var isMobile = window.innerWidth <= 480;
var center = config.geocode().center.split(',').map(parseFloat);

var View = view(require('./template.html'), function(view, model) {
  view.scrollable = view.find('.scrollable');
  view.panelFooter = view.find('.footer');

  if (scrollbarSize > 0) {
    if (ua.os.name === 'Windows' || ua.browser.name !== 'Chrome')
      view.scrollable.style.marginRight = -scrollbarSize + 'px';

    // Scrollbars are fun and implemented the same on every OS/Browser...right
    if (ua.os.name === 'Windows' && ua.browser.name === 'Chrome')
      view.scrollable.style.paddingRight = scrollbarSize + 'px';
  }
});

/**
 * Expose `render`
 */

module.exports = function(ctx, next) {
  log('render');

  var plan = ctx.plan;
  var query = querystring.parse(window.location.search);

  // Set up the views
  var views = {
    'filter-view': new FilterView(plan),
    'locations-view': new LocationsView(plan),
    'options-view': new OptionsView(plan),
    'planner-nav': new PlannerNav(session)
  };

  ctx.view = new View(views);
  ctx.view.on('rendered', function() {
    // Set plan to loading
    plan.loading(true);

    for (var key in views) {
      views[key].emit('rendered', views[key]);
    }

    // Show the map
    var map = showMapView(ctx.view.find('.MapView'));

    console.log("map ->", map);

    // Create the transitive layer
    //var transitiveLayer = new LeafletTransitiveLayer(transitive);

    // Set the transitive layer
    //map.addLayer(transitiveLayer);

    // Update map on plan change
    updateMapOnPlanChange(plan, map);

    //map.on('click', function (e) {
    //      var from = plan.from_ll();
    //      var to = plan.to_ll();
    //      if (!plan.coordinateIsValid(from)) {
    //        plan.journey({
    //      places: [
    //        {
    //          place_id: 'from',
    //          place_lat: e.latlng.lat,
    //          place_lon: e.latlng.lng,
    //          place_name: 'From'
    //        },
    //        {
    //          place_id: 'to',
    //          place_lat: (plan.to_ll() ? plan.to_ll().lat : 0),
    //          place_lon: (plan.to_ll() ? plan.to_ll().lng : 0),
    //          place_name: 'To'
    //        }
    //      ]
    //    });
    //    plan.setAddress('from', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
    //        plan.updateRoutes();
    //    });
    //      } else if (!plan.coordinateIsValid(to)) {
    //    plan.journey({
    //      places: [
    //        {
    //          place_id: 'from',
    //          place_lat: plan.from_ll().lat,
    //          place_lon: plan.from_ll().lng,
    //          place_name: 'From'
    //        },
    //        {
    //          place_id: 'to',
    //          place_lat: e.latlng.lat,
    //          place_lon: e.latlng.lng,
    //          place_name: 'To'
    //        }
    //      ]
    //    });
    //    plan.setAddress('to', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
    //        plan.updateRoutes();
    //    });
    //      }
    //});

    // Clear plan & cookies for now, plan will re-save automatically on save
      var from = plan.from_ll();
      var to = plan.to_ll();
      //plan.clearStore();

    // If it's a shared URL or welcome is complete skip the welcome screen
    console.log("query ->", query);
    if ((query.from && query.to)) {
      showQuery(query);
    } else {
      console.log("plan.coordinateIsValid(from)", plan.coordinateIsValid(from));
      console.log("plan.coordinateIsValid(to)", plan.coordinateIsValid(to));

      if (plan.coordinateIsValid(from) && plan.coordinateIsValid(to)) {
          plan.setAddresses(
            from.lng + ',' + from.lat, // from
            to.lng + ',' + to.lat, // to
            function (err, res) {
              plan.updateRoutes();
              console.log("aqui la data del plan 4 ->", plan.dataplan);
            }
          );
          plan.updateRoutes();
          console.log("aqui la data del plan 3 ->", plan.dataplan);
      } else {
          console.log(from);
          console.log(to);
          plan.loading(false);
      }
    }
  });

  plan.on('updating options', function() {
    ctx.view.panelFooter.classList.add('hidden');
  });

  plan.on('updating options complete', function(res) {
    if (res && !res.err) ctx.view.panelFooter.classList.remove('hidden');
  });

  next();
};

/**
 * Reverse Commute
 */

View.prototype.reverseCommute = function(e) {
  e.preventDefault();
  var plan = session.plan();
  plan.set({
    from: plan.to(),
    from_id: plan.to_id(),
    from_ll: plan.to_ll(),
    to: plan.from(),
    to_id: plan.from_id(),
    to_ll: plan.from_ll()
  });

  plan.updateRoutes();

  console.log("aqui la data del plan 5 ->", plan.dataplan);
};

/**
 * Scroll
 */

View.prototype.scroll = function(e) {
  e.preventDefault();
  this.scrollable.scrollTop += (this.scrollable.scrollHeight / 5);
};

/**
 * On submit
 */

View.prototype.onsubmit = function(e) {
  e.preventDefault();
};

/**
 * Help Me Choose
 */

View.prototype.helpMeChoose = function(e) {
  HelpMeChoose(session.plan().options()).show();
};

/**
 * Show feedback modal
 */
View.prototype.feedback = function(e) {
  e.preventDefault();
  FeedbackModal().show();
};

/**
 * Hide Side Panel
 */

View.prototype.hideSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(' + width + 'px, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding': '0'
  });

  setTimeout(function () {
    map.invalidateSize();
  }, 2100)
};

/**
 * Show Side Panel
 */

View.prototype.showSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(0, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding-right': '320px'
  });

  setTimeout(function () {
    var plan = session.plan();
    map.invalidateSize();

    plan = session.plan();
    plan.updateRoutes();
    //transitive.updateData(plan.journey());

    plan.journey();

  }, 2100)
};

/**
 * Show Journey
 */

function showQuery(query) {
  var plan = session.plan();
  // If no querystring, see if we have them in the plan already
  var from = query.from || plan.from() || FROM;
  var to = query.to || plan.to() || TO;
  var sameAddresses = from === plan.from() && to === plan.to();

  // Set plan from querystring
  if (query.modes) plan.setModes(query.modes);
  if (query.start_time !== undefined) plan.start_time(parseInt(query.start_time, 10));
  if (query.end_time !== undefined) plan.end_time(parseInt(query.end_time, 10));
  if (query.days !== undefined) plan.days(query.days);

  // If has valid coordinates, load
  if (plan.validCoordinates() && sameAddresses) {
    plan.journey({
      places: plan.generatePlaces()
    });
    plan.updateRoutes();

    console.log("aqui la data del plan 1 ->", plan.dataplan);
  } else {
      if (!plan.validCoordinates()) {
	  plan.loading(false);
	  return;
      } else {
    // Set addresses and update the routes
    plan.setAddresses(from, to, function(err) {
      if (err) {
        log.error('%e', err);
      } else {
        plan.journey({
          places: plan.generatePlaces()
        });
        plan.updateRoutes();

        console.log("aqui la data del plan 2 ->", plan.dataplan);
      }
    });
}
  }
}

/**
 * Update Map on plan change
 */

function updateMapOnPlanChange(plan, map) {
  // Register plan update events
    /*
    for (i in map._layers) {
        if (map._layers[i].options.format == undefined) {
            try {
                map.removeLayer(map._layers[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }
        }
    }
    */

    //map.removeLayer(polyline);
/*

  for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }

  }
  */

  plan.on('change journey', function(journey) {

  var polyline_creadas = showMapView.getpolyline_creadas();
    //console.log("poliline credas ->", polyline_creadas);
    //console.log("llamamos sin evento ->", showMapView.polyline_creadas);

    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }

  }

    showMapView.polyline_creadas = [];
    if (journey && !isMobile) {
      try {

        log('updating data');

        var datajourney = journey;
        if (!(plan.dataplan === undefined)) {
            var itineraries = plan.dataplan.itineraries;
            console.log("numero de iteraciones ->", itineraries.length);
            console.log("grafica from ->",plan.dataplan.from);
            console.log("grafica to ->",plan.dataplan.to);
            console.log("itineraries", itineraries);
            showMapView.marker_map([plan.dataplan.from.lat,plan.dataplan.from.lon],[plan.dataplan.to.lat,plan.dataplan.to.lon], map);
            for (i = 0; i < itineraries.length; i++) {
                for (ii=0; ii < itineraries[i].legs.length; ii++) {
                  console.log("itineraries[i].legs[ii]", itineraries[i].legs[ii]);
                  var circle = [itineraries[i].legs[ii].to.lat, itineraries[i].legs[ii].to.lon, itineraries[i].legs[ii].to.name];
                  console.log("circle", circle);
                  showMapView.marker_map_point(circle, map);
                  //
                  //for (i = 0; i < itineraries[i].legs[ii].steps.length; i++) {
                  //     var circle2 = [itineraries[i].legs[ii].steps[i].lat, itineraries[i].legs[ii].steps[i].lon, ''];
                  //     showMapView.marker_map_point(circle2, map);
                  //}
                  showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                }
            }
          console.log("entre if ")
        }else{
            console.log("ejecuta storage");
            var sesion_plan = JSON.parse(localStorage.getItem('dataplan'));
            if(!(sesion_plan === null)) {
                var itineraries = sesion_plan.itineraries;

                showMapView.marker_map([sesion_plan.from.lat,sesion_plan.from.lon],[sesion_plan.to.lat,sesion_plan.to.lon], map);

                for (i = 0; i < itineraries.length; i++) {
                    for (ii=0; ii < itineraries[i].legs.length; ii++) {
                      var circle = [itineraries[i].legs[ii].to.lat, itineraries[i].legs[ii].to.lon, itineraries[i].legs[ii].to.name];
                      console.log("circle", circle);
                      showMapView.marker_map_point(circle, map);
                      showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                    }
                }
            }

        }
      } catch (e) {
        console.log("entre cath")
	    map.setView([center[1], center[0]], config.geocode().zoom);
      }

    }
  });
}
<commit_msg>add functions patterns<commit_after>var config = require('config');
var FeedbackModal = require('feedback-modal');
var FilterView = require('filter-view');
var HelpMeChoose = require('help-me-choose-view');
var LeafletTransitiveLayer = require('Leaflet.TransitiveLayer');
var LocationsView = require('locations-view');
var log = require('./client/log')('planner-page');
var showMapView = require('map-view');
var OptionsView = require('options-view');
var PlannerNav = require('planner-nav');
var querystring = require('querystring');
var scrollbarSize = require('scrollbar-size');
var scrolling = require('scrolling');
var session = require('session');
var textModal = require('text-modal');
//var transitive = require('transitive');
var ua = require('user-agent');
var view = require('view');
var showWelcomeWizard = require('welcome-flow');
var showPlannerWalkthrough = require('planner-walkthrough');
var geocode = require('geocode');

var FROM = config.geocode().start_address;
var TO = config.geocode().end_address;
var isMobile = window.innerWidth <= 480;
var center = config.geocode().center.split(',').map(parseFloat);

var View = view(require('./template.html'), function(view, model) {
  view.scrollable = view.find('.scrollable');
  view.panelFooter = view.find('.footer');

  if (scrollbarSize > 0) {
    if (ua.os.name === 'Windows' || ua.browser.name !== 'Chrome')
      view.scrollable.style.marginRight = -scrollbarSize + 'px';

    // Scrollbars are fun and implemented the same on every OS/Browser...right
    if (ua.os.name === 'Windows' && ua.browser.name === 'Chrome')
      view.scrollable.style.paddingRight = scrollbarSize + 'px';
  }
});

/**
 * Expose `render`
 */

module.exports = function(ctx, next) {
  log('render');

  var plan = ctx.plan;
  var query = querystring.parse(window.location.search);

  // Set up the views
  var views = {
    'filter-view': new FilterView(plan),
    'locations-view': new LocationsView(plan),
    'options-view': new OptionsView(plan),
    'planner-nav': new PlannerNav(session)
  };

  ctx.view = new View(views);
  ctx.view.on('rendered', function() {
    // Set plan to loading
    plan.loading(true);

    for (var key in views) {
      views[key].emit('rendered', views[key]);
    }

    // Show the map
    var map = showMapView(ctx.view.find('.MapView'));

    console.log("map ->", map);

    // Create the transitive layer
    //var transitiveLayer = new LeafletTransitiveLayer(transitive);

    // Set the transitive layer
    //map.addLayer(transitiveLayer);

    // Update map on plan change
    updateMapOnPlanChange(plan, map);

    //map.on('click', function (e) {
    //      var from = plan.from_ll();
    //      var to = plan.to_ll();
    //      if (!plan.coordinateIsValid(from)) {
    //        plan.journey({
    //      places: [
    //        {
    //          place_id: 'from',
    //          place_lat: e.latlng.lat,
    //          place_lon: e.latlng.lng,
    //          place_name: 'From'
    //        },
    //        {
    //          place_id: 'to',
    //          place_lat: (plan.to_ll() ? plan.to_ll().lat : 0),
    //          place_lon: (plan.to_ll() ? plan.to_ll().lng : 0),
    //          place_name: 'To'
    //        }
    //      ]
    //    });
    //    plan.setAddress('from', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
    //        plan.updateRoutes();
    //    });
    //      } else if (!plan.coordinateIsValid(to)) {
    //    plan.journey({
    //      places: [
    //        {
    //          place_id: 'from',
    //          place_lat: plan.from_ll().lat,
    //          place_lon: plan.from_ll().lng,
    //          place_name: 'From'
    //        },
    //        {
    //          place_id: 'to',
    //          place_lat: e.latlng.lat,
    //          place_lon: e.latlng.lng,
    //          place_name: 'To'
    //        }
    //      ]
    //    });
    //    plan.setAddress('to', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
    //        plan.updateRoutes();
    //    });
    //      }
    //});

    // Clear plan & cookies for now, plan will re-save automatically on save
      var from = plan.from_ll();
      var to = plan.to_ll();
      //plan.clearStore();

    // If it's a shared URL or welcome is complete skip the welcome screen
    console.log("query ->", query);
    if ((query.from && query.to)) {
      showQuery(query);
    } else {
      console.log("plan.coordinateIsValid(from)", plan.coordinateIsValid(from));
      console.log("plan.coordinateIsValid(to)", plan.coordinateIsValid(to));

      if (plan.coordinateIsValid(from) && plan.coordinateIsValid(to)) {
          plan.setAddresses(
            from.lng + ',' + from.lat, // from
            to.lng + ',' + to.lat, // to
            function (err, res) {
              plan.updateRoutes();
              console.log("aqui la data del plan 4 ->", plan.dataplan);
            }
          );
          plan.updateRoutes();
          console.log("aqui la data del plan 3 ->", plan.dataplan);
      } else {
          console.log(from);
          console.log(to);
          plan.loading(false);
      }
    }
  });

  plan.on('updating options', function() {
    ctx.view.panelFooter.classList.add('hidden');
  });

  plan.on('updating options complete', function(res) {
    if (res && !res.err) ctx.view.panelFooter.classList.remove('hidden');
  });

  next();
};

/**
 * Reverse Commute
 */

View.prototype.reverseCommute = function(e) {
  e.preventDefault();
  var plan = session.plan();
  plan.set({
    from: plan.to(),
    from_id: plan.to_id(),
    from_ll: plan.to_ll(),
    to: plan.from(),
    to_id: plan.from_id(),
    to_ll: plan.from_ll()
  });

  plan.updateRoutes();

  console.log("aqui la data del plan 5 ->", plan.dataplan);
};

/**
 * Scroll
 */

View.prototype.scroll = function(e) {
  e.preventDefault();
  this.scrollable.scrollTop += (this.scrollable.scrollHeight / 5);
};

/**
 * On submit
 */

View.prototype.onsubmit = function(e) {
  e.preventDefault();
};

/**
 * Help Me Choose
 */

View.prototype.helpMeChoose = function(e) {
  HelpMeChoose(session.plan().options()).show();
};

/**
 * Show feedback modal
 */
View.prototype.feedback = function(e) {
  e.preventDefault();
  FeedbackModal().show();
};

/**
 * Hide Side Panel
 */

View.prototype.hideSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(' + width + 'px, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding': '0'
  });

  setTimeout(function () {
    map.invalidateSize();
  }, 2100)
};

/**
 * Show Side Panel
 */

View.prototype.showSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(0, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding-right': '320px'
  });

  setTimeout(function () {
    var plan = session.plan();
    map.invalidateSize();

    plan = session.plan();
    plan.updateRoutes();
    //transitive.updateData(plan.journey());

    plan.journey();

  }, 2100)
};

/**
 * Show Journey
 */

function showQuery(query) {
  var plan = session.plan();
  // If no querystring, see if we have them in the plan already
  var from = query.from || plan.from() || FROM;
  var to = query.to || plan.to() || TO;
  var sameAddresses = from === plan.from() && to === plan.to();

  // Set plan from querystring
  if (query.modes) plan.setModes(query.modes);
  if (query.start_time !== undefined) plan.start_time(parseInt(query.start_time, 10));
  if (query.end_time !== undefined) plan.end_time(parseInt(query.end_time, 10));
  if (query.days !== undefined) plan.days(query.days);

  // If has valid coordinates, load
  if (plan.validCoordinates() && sameAddresses) {
    plan.journey({
      places: plan.generatePlaces()
    });
    plan.updateRoutes();

    console.log("aqui la data del plan 1 ->", plan.dataplan);
  } else {
      if (!plan.validCoordinates()) {
	  plan.loading(false);
	  return;
      } else {
    // Set addresses and update the routes
    plan.setAddresses(from, to, function(err) {
      if (err) {
        log.error('%e', err);
      } else {
        plan.journey({
          places: plan.generatePlaces()
        });
        plan.updateRoutes();

        console.log("aqui la data del plan 2 ->", plan.dataplan);
      }
    });
}
  }
}

/**
 * Update Map on plan change
 */

function updateMapOnPlanChange(plan, map) {
  // Register plan update events
    /*
    for (i in map._layers) {
        if (map._layers[i].options.format == undefined) {
            try {
                map.removeLayer(map._layers[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }
        }
    }
    */

    //map.removeLayer(polyline);
/*

  for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }

  }
  */

  plan.on('change journey', function(journey) {

  var polyline_creadas = showMapView.getpolyline_creadas();
    //console.log("poliline credas ->", polyline_creadas);
    //console.log("llamamos sin evento ->", showMapView.polyline_creadas);

    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }

  }

    showMapView.polyline_creadas = [];
    if (journey && !isMobile) {
      try {

        log('updating data');

        var datajourney = journey;
        if (!(plan.dataplan === undefined)) {
            var itineraries = plan.dataplan.itineraries;
            var patterns = plan.dataplan.patterns;
            console.log("numero de iteraciones ->", itineraries.length);
            console.log("grafica from ->",plan.dataplan.from);
            console.log("grafica to ->",plan.dataplan.to);
            console.log("itineraries", itineraries);
            showMapView.marker_map([plan.dataplan.from.lat,plan.dataplan.from.lon],[plan.dataplan.to.lat,plan.dataplan.to.lon], map);
            for (i = 0; i < itineraries.length; i++) {
                for (ii=0; ii < itineraries[i].legs.length; ii++) {
                  console.log("itineraries[i].legs[ii]", itineraries[i].legs[ii]);
                  var circle = [itineraries[i].legs[ii].to.lat, itineraries[i].legs[ii].to.lon, itineraries[i].legs[ii].to.name];
                  console.log("circle", circle);
                  showMapView.marker_map_point(circle, map);
                  //
                  //for (i = 0; i < itineraries[i].legs[ii].steps.length; i++) {
                  //     var circle2 = [itineraries[i].legs[ii].steps[i].lat, itineraries[i].legs[ii].steps[i].lon, ''];
                  //     showMapView.marker_map_point(circle2, map);
                  //}
                  showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                }
            }
          console.log("entre if ")
        }else{
            console.log("ejecuta storage");
            var sesion_plan = JSON.parse(localStorage.getItem('dataplan'));
            if(!(sesion_plan === null)) {
                var itineraries = sesion_plan.itineraries;

                showMapView.marker_map([sesion_plan.from.lat,sesion_plan.from.lon],[sesion_plan.to.lat,sesion_plan.to.lon], map);

                for (i = 0; i < itineraries.length; i++) {
                    for (ii=0; ii < itineraries[i].legs.length; ii++) {
                      var circle = [itineraries[i].legs[ii].to.lat, itineraries[i].legs[ii].to.lon, itineraries[i].legs[ii].to.name];
                      console.log("circle", circle);
                      showMapView.marker_map_point(circle, map);
                      showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                    }
                }
            }

        }
      } catch (e) {
        console.log("entre cath")
	    map.setView([center[1], center[0]], config.geocode().zoom);
      }

    }
  });
}

/////////////function test circle maps  ////

function getRouteId(patternId, patterns) {
  for (var i = 0; i < patterns.length; i++) {
    var pattern = patterns[i];
    if (pattern.pattern_id === patternId) return pattern.route_id;
  }
}

function getRoute(routeId, routes) {
  for (var i = 0; i < routes.length; i++) {
    var route = routes[i];
    if (route.route_id === routeId) return route;
  }
}

function getRouteShield(agency, route) {
  if (agency === 'dc' && route.route_type === 1) return 'M';
  return route.route_short_name || route.route_long_name.toUpperCase();
}
<|endoftext|>