<commit_before>//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require twitter/bootstrap/rails/confirm
//= require underscore
//= require_tree .

/* global $, skrollr, alert, Hogan */

// whether or not the homepage map should be loaded
window.enableMap = document.querySelectorAll && Modernizr.svg;

$(document).ready(function($){
  //////
  // Rails support
  //

  // 'use strict';

  // Display when an remote form failed
  $(document).on('ajax:error', 'form[data-remote-error-message]', function(){
    var message = $(this).data('remote-error-message'),
        $target = $('.form-errors', this);

    if($target.size()){
      // create a div to show the message in
      $('
', {'class':'alert alert-box alert-alert'})
        .append($('
',{text:message}))
        .appendTo($target);
    } else {
      alert(message);
    }

  }).on('ajax:beforeSend.rails', 'form[data-remote-error-message]', function(){
    $('.form-errors', this).empty();
  });

  // Skrollr data settings
  var bleed = $('body.odi-bleed').attr({
    'data-0':'background-position:center -480px',
    'data-2500':'background-position:center 1000px'
  });

  // don't enable on touch devices, fix at:
  // https://github.com/Prinzhorn/skrollr#what-you-need-in-order-to-support-mobile-browsers
  // though primary concern is for it not to break for now
  var touch = 'ontouchstart' in window;
  if (bleed.size() && !touch) skrollr.init({forceHeight: false});

  // Event to close menus when clicking away off them
  var openMenu = false;
  $(document).on('click', function() {
    if (openMenu) {
      openMenu.removeClass('active');
      openMenu.data('target').removeClass('active');
      openMenu = false;
    }
  });

  // Bind related elements for each toggle button
  $('[data-dropdown=toggle]').each(function() {
    var self = $(this);
    self.data('target', $(self.data('target')));
    self.data('parent', $(self.data('parent')));

    // Event to prevent menus being closed when clicked on them
    self.data('target').click(function(e) { e.stopPropagation(); });
  });

  // Trigger dropdown buttons
  $(document).on('click', '[data-dropdown=toggle]', function() {
    var self = $(this);
    var active = !self.data('target').hasClass('active');

    self.data('parent').find('[data-dropdown=toggle]').each(function() {
      var self = $(this);
      self.removeClass('active');
      self.data('target').removeClass('active');
    });

    self.toggleClass('active', active);
    self.data('target').toggleClass('active', active);
    openMenu = active && self;

    return false;
  });

  // Toggles content based on a button
  $('[data-content=toggle]').each(function() {
    var self = $(this);
    self.data('target', self.find(self.data('target')));
    self.data('button', self.find(self.data('button')));

    self.data('button').click(function() {
      self.data('target').animate({opacity: 'toggle'}, 250);
    });
  });

  $('.embed-code textarea').click(function() {
    this.select();
  });

  // display confirmation of clicking certain buttons
  $(document).on('click', '[data-btn-confirmable]', function(){
    var $this = $(this),
        message = $this.data('btn-confirmable');

    if(message) $this.is('input') ? $this.val(message) : $this.text(message);

    $this.addClass('btn-confirmed disabled');

  });

  //////
  // Questionnaire

  // a map from reference_id to the relevant fieldset (DOM, not $wrapped)
  var reference_id_els = {};
  var $surveyElements = $('[data-reference-identifier]');
  $surveyElements.each(function(){
    reference_id_els[$(this).data('reference-identifier')] = this;
  });

  // The fieldset surrounding an input is the base of a question being 'active', it will
  // - have an 'active' class added
  // - emit 'odc.focus' & 'odc.blur' events (?)
  $surveyElements.on('mouseenter', function(){
    $(this).addClass('active').data('mouseover', true).trigger('_focus');
  }).on('mouseleave', function(){;
    $(this).removeClass('active').data('mouseover', false).trigger('_blur');
  });

  // trigger the highlighting of fieldsets
  $('#surveyor')
    .on('focus', 'fieldset', function(){
      $(this).addClass('active').trigger('_focus');
    })
    .on('blur', 'fieldset', function(){
      if (!$(this).data('mouseover')) {
        $(this).removeClass('active').trigger('_blur');
      }
    });

  // binding the text of this to the value of a
  // particular input, keyed by data-reference-identifier
  // (this is for the the title to show the questionnaire title)
  $('[data-bind-to-input]').each(function(){
    var $bound = $(this),
        original = $bound.text(),
        el = reference_id_els[$bound.data('bind-to-input')];

    $(el).find('input').on('keyup', function(){
      $bound.text($(this).val() || original);
    });
  });

  // elements that have to be shown along with the fieldsets
  $('[data-meta-for]').each(function() {
    var ref_id = $(this).data('meta-for'),
        $el = $(reference_id_els[ref_id]),
        $row = $(this).closest('.question-row'),
        metas = $el.data('metas') || [];

    metas.push(this);
    $el.data('metas', metas);

    if ($el.hasClass('input')) {
      $row.data('input-metas', $row.data('input-metas') || []);
      $row.data('input-metas').push(this);
    }
  });

  $surveyElements.filter('.question-row').on('_focus', function() {
    $($(this).data('metas')).show();
  }).on('_blur', function(){
    $($(this).data('metas')).hide();
    $($(this).data('input-metas')).hide();
    return false;
  });

  $surveyElements.filter('.input').on('_focus', function() {
    $($(this).closest('.question-row').data('input-metas')).hide();
    $($(this).data('metas')).show();
    return false;
  }).on('_blur', function(){
    return false;
  });

  // deal with accordion section changes
  $('.survey-section .collapse').on('show', function(){
    $(this).prev().removeClass('inactive');
  }).on('hidden', function(){
    $(this).prev().addClass('inactive');
  });

  $('.affixed').each(function(){
    var $this = $(this),
        h = $this.height();

    // lock the height and affix the child node
    $this.height(h).children().affix({ offset: $this.position() });

    $('#status_panel').affix({offset:$this.position(), top:10});

  });

  // major massive massive hack
  //
  // This collects all the sections that are requirements, and
  // bundles them into the aside of the previous question (that
  // they hopefully pertain to)
  var $current;
  $('.survey-section > ul > li > fieldset').each(function(){
    var $this = $(this),
        ref_id = $this.data('reference-identifier');
    if(ref_id){
      $current = $this;
    } else if($current && !($this.hasClass('g_repeater'))){
      $this
        .closest('li.container')
        .remove()
        .end()
        .appendTo($current.closest('li.container'));
    }
  });

  // Old ie only supports :hover on anchors
  $('#status_panel').hover(function(){
    $(this).addClass('hover');
  }, function(){
    $(this).removeClass('hover');
  });

  $('#status_panel').click(function(){
    $(this).toggleClass('stick');
  });

  // scroll to question / repeated section
  var $question = $(document.location.hash);
  if ($question.length !== 0) {
    // open up survey section
    $question
      .parents('.survey-section')
      .find('ul')
      .on('shown', function () {
        // scroll to the question (taking into account header)
        $('html').scrollTop($question.offset().top - 130);
      })
      .collapse('show');
  }

  // Open sections that contain incomplete mandatory questions
  if ($('#surveyor').hasClass('highlight-mandatory')) {
    $('.survey-section:has(.mandatory.no-response:not(.q_hidden))')
      .find('ul')
      .collapse('show');
  }

  // Questionnaire status panel

  // test if a fieldset has been filled out of not
  $.fn.is_completed = function(){
    var $inputs = $('li:not(.quiet)', this).find('input, select');
    return (($inputs.length === 1 && $inputs.val() !== '') || $inputs.is(':checked'));
  };

  $('#status_panel').on('update', function(){
    var levels = ['basic', 'pilot', 'standard', 'exemplar'];
    var requirements = {};
    $.each(levels, function(i, level){
      requirements[level] = { required: 0, complete: 0 };
    });

    var $questions = $('fieldset.question-row:not(.q_hidden)');

    // mandatory fields count as a basic requirement
    var $mandatory = $questions.filter('.mandatory'),
        $mandatoryComplete = $mandatory.filter($.fn.is_completed);

    requirements.basic.required += $mandatory.size();
    requirements.basic.complete += $mandatoryComplete.size();

    $questions.each(function(){
      var $this = $(this);
      var $requirement = $this.closest('li.container').find('fieldset.q_label');
      var completed = $this.is_completed();

      $.each(levels,function(i, level){
        if($requirement.is('.requirement_' + level)){
          requirements[level].required ++;
          if(completed && $requirement.is('.q_hidden.requirement_' + level)) {
            requirements[level].complete ++;
          }
        }
      });
    });

    // previously based on requirements (keeping this because it
    // might be useful for collecting items for the ui)
    // $.each(levels,function(i, level){
    //   $('.requirement_' + level).each(function(){
    //     requirements[level].required += $(this).size();
    //     requirements[level].complete += $(this).filter('.q_hidden').size();
    //   });
    // });

    // update the bars
    $.each(requirements, function(level, totals) {
      var required = totals.required,
          complete = totals.complete;
      if (level !== 'basic') {
        required += requirements.basic.required;
        complete += requirements.basic.complete;
      }
      if (level === 'standard' || level === 'exemplar') {
        required += requirements.pilot.required;
        complete += requirements.pilot.complete;
      }
      if (level === 'exemplar') {
        required += requirements.standard.required;
        complete += requirements.standard.complete;
      }
      //if(window.console) console.log('setting ' + level + ': ' + complete + ' / ' + required);
      //$('#bar-' + level).width((required === 0 ? '0' : 100*(complete/required)) + '%');
    });

    // first incomplete is our target
    var completed = 'none';
    for (var i = 0; i < levels.length; i++) {
      var level = levels[i], r = requirements[level];
      if(r.required === r.complete){
        completed = level;
      } else {
        break;
      }
    }

    $('.status_texts dt').filter(function(){return $(this).text() == completed;})
      // display the dd
      .next().addClass('active')

      // hide any others
      .siblings().removeClass('active');

    // update the handle image
    var $handle = $('#panel_handle');
    $.each(levels, function(i, l){
      $handle.toggleClass('attained-' + l, l == completed);
    });

  });

  $('#status_panel').on('update', function(){
    // render from cert progress
    var url = $(this).data('progress-url');

    $.getJSON(url)
    .then(function(data){
      // console.log("url:", url)

      // global debug
      debug_data = data;

      var levels = ['basic', 'pilot', 'standard', 'exemplar'];

      var pending = data.mandatory,
          complete = data.mandatory_completed,
          percentage;

      _.each(levels, function(level){

        // rolling values
        pending  += _.filter(data.outstanding, has_level(level)).length;
        complete += _.filter(data.entered,     has_level(level)).length;

        percentage = ((complete / (pending + complete))*100)

        $('#bar-' + level).width(percentage + '%');

        // console.log("Level: %s, pending: %d, complete: %d, percentage: %f", level, pending, complete, percentage)
      });

      function has_level(name){
        return function(item){
          return item.indexOf(name+'_') === 0
        }
      }

    });
  });

  // when surveyor has displayed/hidden elements
  $(document).on('surveyor-update', function(){
    $('#status_panel').trigger('update');
  });

  // also on load
  $('#status_panel').trigger('update');

  // Placeholders for <= IE9 - https://github.com/mathiasbynens/jquery-placeholder

  // If the browser supports HTML5 placeholder, it won't do anything

  $('input, textarea').placeholder();

  // ## dashboard

  // initialise some of the popover
  $('.popdown').popover({
    placement:'bottom',
    trigger:'hover'
  });

  // search typeahead
  $('.typeahead-search').typeahead([{
      name:'datasets',
      header: '
Datasets
',
      template: '
{{value}}
',
      engine: Hogan,
      remote: {
        url:'/datasets/typeahead?mode=dataset&q=%QUERY'
      }
    },
    {
      name:'publisher',
      header: '
Publisher
',
      remote: {
        url:'/datasets/typeahead?mode=publisher&q=%QUERY'
      }
    },
    {
      name:'jurisdiction',
      header: '
Jurisdiction
',
      remote: {
        url:'/datasets/typeahead?mode=country&q=%QUERY'
      }
    }
  ])
  .on('typeahead:selected typeahead:autocompleted', function(e, datum){
    if(datum.path){ document.location = datum.path; }
  });

  // Stop the jump to the top of the page when the delete dialog is confirmed.
  // placeholder till bluerail/twitter-bootstrap-rails-confirm#9 gets published
  $(document).on('click', "#confirmation_dialog [href='#']", function(e){
    e.preventDefault();
  })

  .on('click', '.dataset .show-more, .dataset .hide-more', function(){
    $(this).parents('.dataset').toggleClass('expanded', $(this).hasClass('show-more'));
  })

  .on('click', '.join-discussion a', function(e){
    e.preventDefault();
    var top = $('.juvia-add-comment-form').prev().offset().top;
    $('body').animate({scrollTop:top})
  });

  $('.certificate-data').popover({
    selector:'.odc-popover',
    trigger:'click',
    html:true,
    content: function(){
      // pull out the content from the child element (hidden with css)
      return $('.odc-popover-content', this).html()
    },
    template: '

'+
              '

'
  })
  .on('mouseover', '.answer', function(){$(this).toggleClass('odc-popover-active', true)})
  .on('mouseout',  '.answer', function(){$(this).toggleClass('odc-popover-active', false)})

});
<commit_msg>display the attained level<commit_after>//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require twitter/bootstrap/rails/confirm
//= require underscore
//= require_tree .

/* global $, skrollr, alert, Hogan */

// whether or not the homepage map should be loaded
window.enableMap = document.querySelectorAll && Modernizr.svg;

$(document).ready(function($){
  //////
  // Rails support
  //

  // 'use strict';

  // Display when an remote form failed
  $(document).on('ajax:error', 'form[data-remote-error-message]', function(){
    var message = $(this).data('remote-error-message'),
        $target = $('.form-errors', this);

    if($target.size()){
      // create a div to show the message in
      $('
', {'class':'alert alert-box alert-alert'})
        .append($('
',{text:message}))
        .appendTo($target);
    } else {
      alert(message);
    }

  }).on('ajax:beforeSend.rails', 'form[data-remote-error-message]', function(){
    $('.form-errors', this).empty();
  });

  // Skrollr data settings
  var bleed = $('body.odi-bleed').attr({
    'data-0':'background-position:center -480px',
    'data-2500':'background-position:center 1000px'
  });

  // don't enable on touch devices, fix at:
  // https://github.com/Prinzhorn/skrollr#what-you-need-in-order-to-support-mobile-browsers
  // though primary concern is for it not to break for now
  var touch = 'ontouchstart' in window;
  if (bleed.size() && !touch) skrollr.init({forceHeight: false});

  // Event to close menus when clicking away off them
  var openMenu = false;
  $(document).on('click', function() {
    if (openMenu) {
      openMenu.removeClass('active');
      openMenu.data('target').removeClass('active');
      openMenu = false;
    }
  });

  // Bind related elements for each toggle button
  $('[data-dropdown=toggle]').each(function() {
    var self = $(this);
    self.data('target', $(self.data('target')));
    self.data('parent', $(self.data('parent')));

    // Event to prevent menus being closed when clicked on them
    self.data('target').click(function(e) { e.stopPropagation(); });
  });

  // Trigger dropdown buttons
  $(document).on('click', '[data-dropdown=toggle]', function() {
    var self = $(this);
    var active = !self.data('target').hasClass('active');

    self.data('parent').find('[data-dropdown=toggle]').each(function() {
      var self = $(this);
      self.removeClass('active');
      self.data('target').removeClass('active');
    });

    self.toggleClass('active', active);
    self.data('target').toggleClass('active', active);
    openMenu = active && self;

    return false;
  });

  // Toggles content based on a button
  $('[data-content=toggle]').each(function() {
    var self = $(this);
    self.data('target', self.find(self.data('target')));
    self.data('button', self.find(self.data('button')));

    self.data('button').click(function() {
      self.data('target').animate({opacity: 'toggle'}, 250);
    });
  });

  $('.embed-code textarea').click(function() {
    this.select();
  });

  // display confirmation of clicking certain buttons
  $(document).on('click', '[data-btn-confirmable]', function(){
    var $this = $(this),
        message = $this.data('btn-confirmable');

    if(message) $this.is('input') ? $this.val(message) : $this.text(message);

    $this.addClass('btn-confirmed disabled');

  });

  //////
  // Questionnaire

  // a map from reference_id to the relevant fieldset (DOM, not $wrapped)
  var reference_id_els = {};
  var $surveyElements = $('[data-reference-identifier]');
  $surveyElements.each(function(){
    reference_id_els[$(this).data('reference-identifier')] = this;
  });

  // The fieldset surrounding an input is the base of a question being 'active', it will
  // - have an 'active' class added
  // - emit 'odc.focus' & 'odc.blur' events (?)
  $surveyElements.on('mouseenter', function(){
    $(this).addClass('active').data('mouseover', true).trigger('_focus');
  }).on('mouseleave', function(){;
    $(this).removeClass('active').data('mouseover', false).trigger('_blur');
  });

  // trigger the highlighting of fieldsets
  $('#surveyor')
    .on('focus', 'fieldset', function(){
      $(this).addClass('active').trigger('_focus');
    })
    .on('blur', 'fieldset', function(){
      if (!$(this).data('mouseover')) {
        $(this).removeClass('active').trigger('_blur');
      }
    });

  // binding the text of this to the value of a
  // particular input, keyed by data-reference-identifier
  // (this is for the the title to show the questionnaire title)
  $('[data-bind-to-input]').each(function(){
    var $bound = $(this),
        original = $bound.text(),
        el = reference_id_els[$bound.data('bind-to-input')];

    $(el).find('input').on('keyup', function(){
      $bound.text($(this).val() || original);
    });
  });

  // elements that have to be shown along with the fieldsets
  $('[data-meta-for]').each(function() {
    var ref_id = $(this).data('meta-for'),
        $el = $(reference_id_els[ref_id]),
        $row = $(this).closest('.question-row'),
        metas = $el.data('metas') || [];

    metas.push(this);
    $el.data('metas', metas);

    if ($el.hasClass('input')) {
      $row.data('input-metas', $row.data('input-metas') || []);
      $row.data('input-metas').push(this);
    }
  });

  $surveyElements.filter('.question-row').on('_focus', function() {
    $($(this).data('metas')).show();
  }).on('_blur', function(){
    $($(this).data('metas')).hide();
    $($(this).data('input-metas')).hide();
    return false;
  });

  $surveyElements.filter('.input').on('_focus', function() {
    $($(this).closest('.question-row').data('input-metas')).hide();
    $($(this).data('metas')).show();
    return false;
  }).on('_blur', function(){
    return false;
  });

  // deal with accordion section changes
  $('.survey-section .collapse').on('show', function(){
    $(this).prev().removeClass('inactive');
  }).on('hidden', function(){
    $(this).prev().addClass('inactive');
  });

  $('.affixed').each(function(){
    var $this = $(this),
        h = $this.height();

    // lock the height and affix the child node
    $this.height(h).children().affix({ offset: $this.position() });

    $('#status_panel').affix({offset:$this.position(), top:10});

  });

  // major massive massive hack
  //
  // This collects all the sections that are requirements, and
  // bundles them into the aside of the previous question (that
  // they hopefully pertain to)
  var $current;
  $('.survey-section > ul > li > fieldset').each(function(){
    var $this = $(this),
        ref_id = $this.data('reference-identifier');
    if(ref_id){
      $current = $this;
    } else if($current && !($this.hasClass('g_repeater'))){
      $this
        .closest('li.container')
        .remove()
        .end()
        .appendTo($current.closest('li.container'));
    }
  });

  // Old ie only supports :hover on anchors
  $('#status_panel').hover(function(){
    $(this).addClass('hover');
  }, function(){
    $(this).removeClass('hover');
  });

  $('#status_panel').click(function(){
    $(this).toggleClass('stick');
  });

  // scroll to question / repeated section
  var $question = $(document.location.hash);
  if ($question.length !== 0) {
    // open up survey section
    $question
      .parents('.survey-section')
      .find('ul')
      .on('shown', function () {
        // scroll to the question (taking into account header)
        $('html').scrollTop($question.offset().top - 130);
      })
      .collapse('show');
  }

  // Open sections that contain incomplete mandatory questions
  if ($('#surveyor').hasClass('highlight-mandatory')) {
    $('.survey-section:has(.mandatory.no-response:not(.q_hidden))')
      .find('ul')
      .collapse('show');
  }

  // Questionnaire status panel

  // test if a fieldset has been filled out of not
  $.fn.is_completed = function(){
    var $inputs = $('li:not(.quiet)', this).find('input, select');
    return (($inputs.length === 1 && $inputs.val() !== '') || $inputs.is(':checked'));
  };

  $('#status_panel').on('update', function(){
    var levels = ['basic', 'pilot', 'standard', 'exemplar'];
    var requirements = {};
    $.each(levels, function(i, level){
      requirements[level] = { required: 0, complete: 0 };
    });

    var $questions = $('fieldset.question-row:not(.q_hidden)');

    // mandatory fields count as a basic requirement
    var $mandatory = $questions.filter('.mandatory'),
        $mandatoryComplete = $mandatory.filter($.fn.is_completed);

    requirements.basic.required += $mandatory.size();
    requirements.basic.complete += $mandatoryComplete.size();

    $questions.each(function(){
      var $this = $(this);
      var $requirement = $this.closest('li.container').find('fieldset.q_label');
      var completed = $this.is_completed();

      $.each(levels,function(i, level){
        if($requirement.is('.requirement_' + level)){
          requirements[level].required ++;
          if(completed && $requirement.is('.q_hidden.requirement_' + level)) {
            requirements[level].complete ++;
          }
        }
      });
    });

    // previously based on requirements (keeping this because it
    // might be useful for collecting items for the ui)
    // $.each(levels,function(i, level){
    //   $('.requirement_' + level).each(function(){
    //     requirements[level].required += $(this).size();
    //     requirements[level].complete += $(this).filter('.q_hidden').size();
    //   });
    // });

    // update the bars
    $.each(requirements, function(level, totals) {
      var required = totals.required,
          complete = totals.complete;
      if (level !== 'basic') {
        required += requirements.basic.required;
        complete += requirements.basic.complete;
      }
      if (level === 'standard' || level === 'exemplar') {
        required += requirements.pilot.required;
        complete += requirements.pilot.complete;
      }
      if (level === 'exemplar') {
        required += requirements.standard.required;
        complete += requirements.standard.complete;
      }
      //if(window.console) console.log('setting ' + level + ': ' + complete + ' / ' + required);
      //$('#bar-' + level).width((required === 0 ? '0' : 100*(complete/required)) + '%');
    });

    // first incomplete is our target
    var completed = 'none';
    for (var i = 0; i < levels.length; i++) {
      var level = levels[i], r = requirements[level];
      if(r.required === r.complete){
        completed = level;
      } else {
        break;
      }
    }

    return;

    $('.status_texts dt').filter(function(){return $(this).text() == completed;})
      // display the dd
      .next().addClass('active')

      // hide any others
      .siblings().removeClass('active');

    // update the handle image
    var $handle = $('#panel_handle');
    $.each(levels, function(i, l){
      $handle.toggleClass('attained-' + l, l == completed);
    });

  });

  $('#status_panel').on('update', function(){
    // render from cert progress
    var url = $(this).data('progress-url');

    $.getJSON(url)
    .then(function(data){
      // console.log("url:", url)

      // global debug
      debug_data = data;

      var levels = ['basic', 'pilot', 'standard', 'exemplar'];

      var pending = data.mandatory,
          complete = data.mandatory_completed,
          percentage, attained = 'none';

      _.each(levels, function(level){

        // rolling values
        pending  += _.filter(data.outstanding, has_level(level)).length;
        complete += _.filter(data.entered,     has_level(level)).length;

        percentage = ((complete / (pending + complete))*100)

        $('#bar-' + level).width(percentage + '%');

        if(percentage === 100){attained = level}

        // debug
        // console.log("Level: %s, pending: %d, complete: %d, percentage: %f", level, pending, complete, percentage)
      });

      // update the overal attainment

      $('.status_texts dt')
        // display the active dd
        .filter(function(){return $(this).text() == attained;})
        .next().addClass('active')

        // hide any others
        .siblings().removeClass('active');

      $('#panel_handle')
        // removed any 'attained-' classes
        .toggleClass(function(i, name){return name.indexOf('attained-') === -1})
        // set to the correct level
        .addClass('attained-' + attained);

      function has_level(name){
        return function(item){
          return item.indexOf(name+'_') === 0
        }
      }

    });
  });

  // when surveyor has displayed/hidden elements
  $(document).on('surveyor-update', function(){
    $('#status_panel').trigger('update');
  });

  // also on load
  $('#status_panel').trigger('update');

  // Placeholders for <= IE9 - https://github.com/mathiasbynens/jquery-placeholder

  // If the browser supports HTML5 placeholder, it won't do anything

  $('input, textarea').placeholder();

  // ## dashboard

  // initialise some of the popover
  $('.popdown').popover({
    placement:'bottom',
    trigger:'hover'
  });

  // search typeahead
  $('.typeahead-search').typeahead([{
      name:'datasets',
      header: '
Datasets
',
      template: '
{{value}}
',
      engine: Hogan,
      remote: {
        url:'/datasets/typeahead?mode=dataset&q=%QUERY'
      }
    },
    {
      name:'publisher',
      header: '
Publisher
',
      remote: {
        url:'/datasets/typeahead?mode=publisher&q=%QUERY'
      }
    },
    {
      name:'jurisdiction',
      header: '
Jurisdiction
',
      remote: {
        url:'/datasets/typeahead?mode=country&q=%QUERY'
      }
    }
  ])
  .on('typeahead:selected typeahead:autocompleted', function(e, datum){
    if(datum.path){ document.location = datum.path; }
  });

  // Stop the jump to the top of the page when the delete dialog is confirmed.
  // placeholder till bluerail/twitter-bootstrap-rails-confirm#9 gets published
  $(document).on('click', "#confirmation_dialog [href='#']", function(e){
    e.preventDefault();
  })

  .on('click', '.dataset .show-more, .dataset .hide-more', function(){
    $(this).parents('.dataset').toggleClass('expanded', $(this).hasClass('show-more'));
  })

  .on('click', '.join-discussion a', function(e){
    e.preventDefault();
    var top = $('.juvia-add-comment-form').prev().offset().top;
    $('body').animate({scrollTop:top})
  });

  $('.certificate-data').popover({
    selector:'.odc-popover',
    trigger:'click',
    html:true,
    content: function(){
      // pull out the content from the child element (hidden with css)
      return $('.odc-popover-content', this).html()
    },
    template: '

'+
              '

'
  })
  .on('mouseover', '.answer', function(){$(this).toggleClass('odc-popover-active', true)})
  .on('mouseout',  '.answer', function(){$(this).toggleClass('odc-popover-active', false)})

});
<|endoftext|>


<commit_before>var userObjGlobalVar;

//------------------------------------ DOCUMENT READY

$(function() {
  var userId = $("#articlesLink").attr("data-id");
  submitForm();
  loadAllCurrentlUserArticles(userId);
  loadArticleOnClick();
  loadAllArticlesOnClick();
  loadArticleDetails();
  initMap();
});

function loadArticleOnClick(){
  $(".js-read-more").on('click', function() {
     let id = $(this).data("id");
     loadArticle(id);
   });
 }

function loadAllArticlesOnClick() {
  $("#articlesLink").on('click', function() {
    // define new instance of constructor
    let id = $(this).data("id");
    var userArticles = new ToggleAllCurrentUserArticles(userObjGlobalVar);
    // call prototype
    userArticles.renderUserArticles();
  });
}

function loadArticleDetails(){
  $(".article-info").each(function (i, element){
    let id = $(this).data("id");
    $.get("/articles/" + id + ".json", function(articles){
      content = articles["content"];
      // console.log(articles);
      let total_credits = (articles["total_credits"]);
      let author = (articles["user"]["name"]);

      $(element).html("Arthor: "+author+"
" + "
Total Credits: "+total_credits)
    })
    .done(function(content){
      // console.log("request completed");
    })
    .fail(function(jqXHR, textStatus, errorThrown){
      // console.log(errorThrown);
    });
  });
}

//  ---------------------------------LOAD ARTICLE VIA GET REQUEST

function loadArticle(id){
  $.get("/articles/" + id + ".json", function(articles){
    let content = articles["content"];
    // define new instance of constructor
    var userArticleBody = new ToggleArticleBody(id, content);
    // call the prototype method of this instance
    userArticleBody.renderArticleBody();
  })
  .done(function(content){
    // console.log("request completed");
  })
  .fail(function(jqXHR, textStatus, errorThrown){
    // console.log(errorThrown);
  });
}

//  ---------------------------------------LOAD ALL CURRENT USER ARTICLES VIA GET REQUEST

function loadAllCurrentlUserArticles(userId) {
  $.get("/users/" + userId + ".json", function(userObj){
    userObjGlobalVar = userObj;
  })
    .done(function(content){
      // console.log("request completed");
    })
    .fail(function(jqXHR, textStatus, errorThrown){
      // console.log(errorThrown);
    });
  }

// -------------------------------------- FORM FOR ADDING A CREDIT TO ARTICLE

function submitForm(){
   $('form.new_credit').submit(function(event) {
      event.preventDefault();

      let artId = $(this).find("span").data("id");
      let values = $(this).serialize();
      let crediting = $.post('/credits', values);

      crediting.done(function(creditObj, textStatus, jqXHR ){

        $('input[type="submit"]').prop("disabled", false);
        loadArticleDetails();

        let articleId = $("#notify-"+artId);

        articleId.css("color", "red");

        if(jqXHR.status === 200){
          if((articleId).html("")){
            articleId.prepend("
You have already credited this article
").show().fadeOut(5000);
          }
        }
        else if(jqXHR.status === 201){
          if((articleId).html("")){
              articleId.prepend("
You have now added a new credit to the article
").show().fadeOut(5000);
          }
        }
      });
  });
}

//  ---------------------------------- OBJECT CONSTRUCTOR FUNCTIONS

// constructor function for articles of user show page
function ToggleAllCurrentUserArticles(userObj){
    // return the articles of object from ajax get response
    this.articles = userObj.articles;
}

//  -------------------------------------------TOGGLE CURRENT USER ARTICLES
// Prototype
ToggleAllCurrentUserArticles.prototype.renderUserArticles = function(){
  let button = $("#articlesLink");
  let container =  $(".index-container ");
  container.html("");
  $.each(this.articles, function(i, article){
    container.prepend("
" + article["title"] +""  + " Credits: " + article.total_credits + "
" + article["content"] + "
" + "
" );
  });
  // Call other constructor for toggle action
  var toggleUserArticles = new Togglefunction(button, container, "See Your Articles", "Hide Your Articles" );
  toggleUserArticles.makeToggle();
}

// ----------------------------------------------TOGGLE BODY OF INDIVIDUAL ARTICLE ON INDEX PAGE
function ToggleArticleBody(artBodyId, content){
  // return the id and content of object from ajax get response
  this.artBodyId = artBodyId;
  this.content = content;
}

// Prototype
ToggleArticleBody.prototype.renderArticleBody = function(){
  let addText = $("#body-" + this.artBodyId);
  let button = $("button#"+this.artBodyId);
  let article_details = $("#article-details");
  addText.html("
" + this.content + "
");

  // Call other constructor for toggle action
  var toggleUserArticles = new Togglefunction(button, addText, "Read More", "Read Less" );
  toggleUserArticles.makeToggle();
}

// Constructor function for toggle functionality
function Togglefunction(button, element, stringOne, stringTwo){
  this.button = button;
  this.element = element;
  this.stringOne = stringOne;
  this.stringTwo = stringTwo;

  this.makeToggle = function() {
    if(button.html() === stringOne){
      element.show();
      button.html(stringTwo);
    }
    else{
      element.hide();
      button.html(stringOne);
    }
  }
}

// ----------------------------------------------- GOOGLE MAPS API
// function initMap() {
//         var uluru = {lat: -25.363, lng: 131.044};
//         var map = new google.maps.Map(document.getElementById('map'), {
//           zoom: 3,
//           center: uluru
//         });
//         var marker = new google.maps.Marker({
//           position: uluru,
//           map: map
//         });
//         codeAddress(map);
// }

// ---------------------------------------- GEOCODING
var geocoder;
 var map;
 function initMap() {
   geocoder = new google.maps.Geocoder();
   var latlng = new google.maps.LatLng(-34.397, 150.644);
   var mapOptions = {
     zoom: 3,
     center: latlng
   }
   map = new google.maps.Map(document.getElementById('map'), mapOptions);
   codeAddress(map);
 }

 function loadArticleAddress(){
   $.get("/articles.json", function(){
   }).done(function(articles){
       var addresses = articles.map(function(art, i){
              return art.address.city + ", "+ art.address.country.title;
       })
       console.log(addresses);
    })
  }

  function codeAddress(map) {
    loadArticleAddress()
    // var address = document.getElementById('address').value;
    var address = "New York, United States";
    // Constructor module change address to longitude latitude coordinates tp place markers
    geocoder.geocode(
      {
        'address': address
      },
      function(results, status) { // success callback function for results and status as parameters
      if (status == 'OK') {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }
<commit_msg>Returning article city and country from the server successfully in javascript<commit_after>var userObjGlobalVar;

//------------------------------------ DOCUMENT READY

$(function() {
  var userId = $("#articlesLink").attr("data-id");
  submitForm();
  loadAllCurrentlUserArticles(userId);
  loadArticleOnClick();
  loadAllArticlesOnClick();
  loadArticleDetails();
  // loadArticleAddress();
});

function loadArticleOnClick(){
  $(".js-read-more").on('click', function() {
     let id = $(this).data("id");
     loadArticle(id);
   });
 }

function loadAllArticlesOnClick() {
  $("#articlesLink").on('click', function() {
    // define new instance of constructor
    let id = $(this).data("id");
    var userArticles = new ToggleAllCurrentUserArticles(userObjGlobalVar);
    // call prototype
    userArticles.renderUserArticles();
  });
}

function loadArticleDetails(){
  $(".article-info").each(function (i, element){
    let id = $(this).data("id");
    $.get("/articles/" + id + ".json", function(articles){
      content = articles["content"];
      // console.log(articles);
      let total_credits = (articles["total_credits"]);
      let author = (articles["user"]["name"]);

      $(element).html("Arthor: "+author+"
" + "
Total Credits: "+total_credits)
    })
    .done(function(content){
      // console.log("request completed");
    })
    .fail(function(jqXHR, textStatus, errorThrown){
      // console.log(errorThrown);
    });
  });
}

//  ---------------------------------LOAD ARTICLE VIA GET REQUEST

function loadArticle(id){
  $.get("/articles/" + id + ".json", function(articles){
    let content = articles["content"];
    // define new instance of constructor
    var userArticleBody = new ToggleArticleBody(id, content);
    userArticleBody.renderArticleBody();
  })
  .done(function(content){
  })
  .fail(function(jqXHR, textStatus, errorThrown){
  });
}

//  ---------------------------------------LOAD ALL CURRENT USER ARTICLES VIA GET REQUEST

function loadAllCurrentlUserArticles(userId) {
  $.get("/users/" + userId + ".json", function(userObj){
    userObjGlobalVar = userObj;
  })
  .done(function(content){
  })
  .fail(function(jqXHR, textStatus, errorThrown){
  });
  }

// -------------------------------------- FORM FOR ADDING A CREDIT TO ARTICLE

function submitForm(){
   $('form.new_credit').submit(function(event) {
      event.preventDefault();

      let artId = $(this).find("span").data("id");
      let values = $(this).serialize();
      let crediting = $.post('/credits', values);

      crediting.done(function(creditObj, textStatus, jqXHR ){

        $('input[type="submit"]').prop("disabled", false);
        loadArticleDetails();

        let articleId = $("#notify-"+artId);

        articleId.css("color", "red");

        if(jqXHR.status === 200){
          if((articleId).html("")){
            articleId.prepend("
You have already credited this article
").show().fadeOut(5000);
          }
        }
        else if(jqXHR.status === 201){
          if((articleId).html("")){
              articleId.prepend("
You have now added a new credit to the article
").show().fadeOut(5000);
          }
        }
      });
  });
}

//  ---------------------------------- OBJECT CONSTRUCTOR FUNCTIONS

// constructor function for articles of user show page
function ToggleAllCurrentUserArticles(userObj){
    // return the articles of object from ajax get response
    this.articles = userObj.articles;
}

//  -------------------------------------------TOGGLE CURRENT USER ARTICLES

ToggleAllCurrentUserArticles.prototype.renderUserArticles = function(){
  let button = $("#articlesLink");
  let container =  $(".index-container ");
  container.html("");
  $.each(this.articles, function(i, article){
    container.prepend("
" + article["title"] +""  + " Credits: " + article.total_credits + "
" + article["content"] + "
" + "
" );
  });
  // Call other constructor for toggle action
  var toggleUserArticles = new Togglefunction(button, container, "See Your Articles", "Hide Your Articles" );
  toggleUserArticles.makeToggle();
}

// ----------------------------------------------TOGGLE BODY OF INDIVIDUAL ARTICLE ON INDEX PAGE

function ToggleArticleBody(artBodyId, content){
  // return the id and content of object from ajax get response
  this.artBodyId = artBodyId;
  this.content = content;
}

// Prototype
ToggleArticleBody.prototype.renderArticleBody = function(){
  let addText = $("#body-" + this.artBodyId);
  let button = $("button#"+this.artBodyId);
  let article_details = $("#article-details");
  addText.html("
" + this.content + "
");

  // Call other constructor for toggle action
  var toggleUserArticles = new Togglefunction(button, addText, "Read More", "Read Less" );
  toggleUserArticles.makeToggle();
}

// Constructor function for toggle functionality
function Togglefunction(button, element, stringOne, stringTwo){
  this.button = button;
  this.element = element;
  this.stringOne = stringOne;
  this.stringTwo = stringTwo;

  this.makeToggle = function() {
    if(button.html() === stringOne){
      element.show();
      button.html(stringTwo);
    }
    else{
      element.hide();
      button.html(stringOne);
    }
  }
}

 // ----------------------------------------------- GOOGLE MAPS API

 // ---------------------------------------- GEOCODING

 var geocoder;
 var map;
 // Initialize map
 function initMap() {
   geocoder = new google.maps.Geocoder();
   var latlng = new google.maps.LatLng(-34.397, 150.644);
   var mapOptions = {
     zoom: 3,
     center: latlng
   }
   map = new google.maps.Map(document.getElementById('map'), mapOptions);
   codeAddress(map);
 }

 // Get all article adresses
 // function loadArticleAddress(){
 //
 //  }

  //  Set all markers
  function codeAddress(map){
    var addresses=[];
    $.get("/articles.json", function(){
    }).done(function(articles){
         addresses.push(articles.map(function(art, i){
           return art.address.city + ", "+ art.address.country.title;
        }))
        // callback
        returnAddresses(addresses);
     });
     function returnAddresses(addressArray){
        console.log(addressArray);
        // Constructor module change address to longitude latitude coordinates tp place markers
        geocoder.geocode(
          {
            'address': obj[0][1]
          },
          function(results, status) { // success callback function for results and status as parameters
          if (status == 'OK') {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
          } else {
            alert('Geocode was not successful for the following reason: ' + status);
          }
        });
      }
  }
<|endoftext|>


<commit_before>bhlApp.controller('MapCtrl', function ($scope, GoogleMap) {

	var googleMapObject;
    $scope.updatePins = function(pinCategory)
    {
    	var field = "check_" + pinCategory;
    	if ($scope[field]) {
    		googleMapObject.fillMapWithMarkers(pinCategory);
    	}
    	else
    	{
    		googleMapObject.removeSelectedPins(pinCategory);
    	}

    };

    $scope.setSelectPins = function()
	{
		$scope.check_100 = true;
    	$scope.check_200 = true;
    	$scope.check_300 = true;
    	$scope.check_400 = true;
    	$scope.check_500 = true;
    	googleMapObject = new GoogleMap(document.getElementById('map'));
    	googleMapObject.fillMapWithMarkers();
	};
});

bhlApp.factory("GoogleMap", function($http)
{
	var GoogleMap = function(element)
	{
    	var map;
	    var infoWindow;
	    var markers;

		this.initialize = function(ele)
		{
			var mapOptions = {
        		zoom: 2,
        		center: {lat: 30.064742, lng: 31.249509},
        		mapTypeId: google.maps.MapTypeId.TERRAIN
    		};
	    	map = new google.maps.Map(ele, mapOptions);
	    	infoWindow = new google.maps.InfoWindow();
	    	markers = [];
		};

		this.removeSelectedPins = function(pinCategory)
	    {
	    	angular.forEach(markers, function(marker)
	    	{
	    		if (marker.category == pinCategory) {
	    			marker.setMap(null);
	    		};
	    	});
	    };

		this.fillMapWithMarkers = function(pinCategory)
	    {
	    	var url;
	    	if (pinCategory)
	    	{
	    		url = "/geographics/load_books/" + pinCategory;
	    	}
	    	else
	    	{
	    		url = "/geographics/load_books";
	    	}
	    	$http.get(url).success( function(response) {
	    		angular.forEach(response, function(bookInfo)
	    		{
	    			createMarker(bookInfo);
	    		});
	        });
	    };

	    function createMarker(info){
	    	var marker = new google.maps.Marker({
	            map: map,
	            position: new google.maps.LatLng(info.latitude, info.longitude),
	            icon: info.icon,
	            category: info.category
	        });

	        google.maps.event.addListener(marker, 'click', function(){
	        	$http.get("/geographics/show/" + info.address).success( function(response) {
	        		infoWindow.setContent(response);
	            	infoWindow.open(map, marker);
	        	});
	        });
	        markers.push(marker);
	    }
	    this.initialize(element);
	};
	return GoogleMap;
});
<commit_msg>Updating angular code for geographics<commit_after>bhlApp.factory("GoogleMap",['$http', function($http)
{
	var GoogleMap = function(element)
	{
    	var map;
	    var infoWindow;
	    var markers;

		this.initialize = function(ele)
		{
			var mapOptions = {
        		zoom: 2,
        		center: {lat: 30.064742, lng: 31.249509},
        		mapTypeId: google.maps.MapTypeId.TERRAIN
    		};
	    	map = new google.maps.Map(ele, mapOptions);
	    	infoWindow = new google.maps.InfoWindow();
	    	markers = [];
		};

		this.removeSelectedPins = function(pinCategory)
	    {
	    	angular.forEach(markers, function(marker)
	    	{
	    		if (marker.category == pinCategory) {
	    			marker.setMap(null);
	    		};
	    	});
	    };

		this.fillMapWithMarkers = function(pinCategory)
	    {
	    	var url;
	    	if (pinCategory)
	    	{
	    		url = "/geographics/load_books/" + pinCategory;
	    	}
	    	else
	    	{
	    		url = "/geographics/load_books";
	    	}
	    	$http.get(url).success( function(response) {
	    		angular.forEach(response, function(bookInfo)
	    		{
	    			createMarker(bookInfo);
	    		});
	        });
	    };

	    function createMarker(info){
	    	var marker = new google.maps.Marker({
	            map: map,
	            position: new google.maps.LatLng(info.latitude, info.longitude),
	            icon: info.icon,
	            category: info.category
	        });

	        google.maps.event.addListener(marker, 'click', function(){
	        	$http.get("/geographics/show/" + info.address).success( function(response) {
	        		infoWindow.setContent(response);
	            	infoWindow.open(map, marker);
	        	});
	        });
	        markers.push(marker);
	    }
	    this.initialize(element);
	};
	return GoogleMap;
}]);

bhlApp.controller('MapCtrl',['$scope','GoogleMap', function ($scope, GoogleMap) {

	var googleMapObject;
    $scope.updatePins = function(pinCategory)
    {
    	var field = "check_" + pinCategory;
    	if ($scope[field]) {
    		googleMapObject.fillMapWithMarkers(pinCategory);
    	}
    	else
    	{
    		googleMapObject.removeSelectedPins(pinCategory);
    	}

    };

    $scope.setSelectPins = function()
	{
		$scope.check_100 = true;
    	$scope.check_200 = true;
    	$scope.check_300 = true;
    	$scope.check_400 = true;
    	$scope.check_500 = true;
    	googleMapObject = new GoogleMap(document.getElementById('map'));
    	googleMapObject.fillMapWithMarkers();
	};
}]);

<|endoftext|>


<commit_before>var map; // マップ
var routeMap; // マップ
var infowindow; // マーカーの詳細表示
var latlng;
var markerList;

var tokyoPosition = {
  latitude:  35.681382,
  longitude: 139.766084
};

function mapInitialize(){
  var lat;
  var lng;

  if (typeof lat == 'undefined'){
    lat        = tokyoPosition['latitude'];
    lng        = tokyoPosition['longitude'];
    markerList = new google.maps.MVCArray();
  }

  myLatLng = new google.maps.LatLng(lat, lng);
  var mapOptions = {
    center:    myLatLng,
    zoom:      5,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  $("#travel-map-tab a").attr('onclick', '');
}

function routeInitialize(){
  var myRouteLatLng   = new google.maps.LatLng(35.681382, 139.766084);
  var mapRouteOptions = {
    center:    myRouteLatLng,
    zoom:      5,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  routeMap = new google.maps.Map(document.getElementById("route-map"), mapRouteOptions);
  $("#route-tab a").attr('onclick', '');
}

function putMarker(data) {
  var main      = 'main';
  var latitude  = data[main]['latitude'];
  var longitude = data[main]['longitude'];
  var name      = data[main]['name'];
  var latlng = new google.maps.LatLng(latitude, longitude);
  var marker = new google.maps.Marker({
    position: latlng,
    map:      map
  });
  markerList.push(marker);

  // マーカーをクリックするとタイトル表示
  var infoWindow = new google.maps.InfoWindow();
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(name);
    infoWindow.open(map, this);
  });
}

function clearMarkers() {
  markerList.forEach(function(mkr, idx){
    mkr.setMap(null);
  });
  markerList = new google.maps.MVCArray();
}

function zoomMap(latitude, longitude) {
  var latlng = new google.maps.LatLng(latitude, longitude);
  map.setCenter(latlng);
  map.setZoom(15);
}

function getRoute(cards){
  var directionsDisplay = new google.maps.DirectionsRenderer();
  var directionsService = new google.maps.DirectionsService();
  directionsDisplay.setMap(routeMap);
  var from;
  var to;
  var points = [];
  var request;

  points = $.map(cards, function(data) {
    if ((data['latitude'] != "") && (data['longitude'] != "")){
      return {
        location: new google.maps.LatLng(data['latitude'], data['longitude']),
        stopover: true
      };
    }
  });

  var length = points.length;
  if (length == 0){ return; }
  if (length > 10) {
    alert("Way points are up to 10 positions");
    return;
  }

  if (length == 1){
    from = points.shift()
    to = from;
    request = {
      origin:      from,
      destination: to,
      travelMode:  google.maps.DirectionsTravelMode.DRIVING
    };
  } else { // google service is up to 10 Waypoint.
    from = points.shift();
    to = points.pop();
    request = {
      origin:      from['location'],
      waypoints:   points,
      destination: to['location'],
      travelMode:  google.maps.DirectionsTravelMode.DRIVING
    };
  }

  directionsService.route(request, function(response, status){
    if(status == google.maps.DirectionsStatus.OK){
      directionsDisplay.setDirections(response);
    }
  });
}
<commit_msg>ルートを表示したいとき、ポイントが1つしかない場合のエラー修正<commit_after>var map; // マップ
var routeMap; // マップ
var infowindow; // マーカーの詳細表示
var latlng;
var markerList;

var tokyoPosition = {
  latitude:  35.681382,
  longitude: 139.766084
};

function mapInitialize(){
  var lat;
  var lng;

  if (typeof lat == 'undefined'){
    lat        = tokyoPosition['latitude'];
    lng        = tokyoPosition['longitude'];
    markerList = new google.maps.MVCArray();
  }

  myLatLng = new google.maps.LatLng(lat, lng);
  var mapOptions = {
    center:    myLatLng,
    zoom:      5,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  $("#travel-map-tab a").attr('onclick', '');
}

function routeInitialize(){
  var myRouteLatLng   = new google.maps.LatLng(35.681382, 139.766084);
  var mapRouteOptions = {
    center:    myRouteLatLng,
    zoom:      5,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  routeMap = new google.maps.Map(document.getElementById("route-map"), mapRouteOptions);
  $("#route-tab a").attr('onclick', '');
}

function putMarker(data) {
  var main      = 'main';
  var latitude  = data[main]['latitude'];
  var longitude = data[main]['longitude'];
  var name      = data[main]['name'];
  var latlng = new google.maps.LatLng(latitude, longitude);
  var marker = new google.maps.Marker({
    position: latlng,
    map:      map
  });
  markerList.push(marker);

  // マーカーをクリックするとタイトル表示
  var infoWindow = new google.maps.InfoWindow();
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(name);
    infoWindow.open(map, this);
  });
}

function clearMarkers() {
  markerList.forEach(function(mkr, idx){
    mkr.setMap(null);
  });
  markerList = new google.maps.MVCArray();
}

function zoomMap(latitude, longitude) {
  var latlng = new google.maps.LatLng(latitude, longitude);
  map.setCenter(latlng);
  map.setZoom(15);
}

function getRoute(cards){
  var directionsDisplay = new google.maps.DirectionsRenderer();
  var directionsService = new google.maps.DirectionsService();
  directionsDisplay.setMap(routeMap);
  var from;
  var to;
  var request;

  var points = $.map(cards, function(data) {
    if ((data['latitude'] != "") && (data['longitude'] != "")){
      return {
        location: new google.maps.LatLng(+data['latitude'], +data['longitude']),
        stopover: true
      };
    }
  });

  var length = points.length;
  if (length == 0){ return; }
  if (length > 10) {
    alert("Way points are up to 10 positions");
    return;
  }

  if (length == 1){
    from = points.shift()
    to = from;
    request = {
      origin:      from['location'],
      destination: to['location'],
      travelMode:  google.maps.DirectionsTravelMode.DRIVING
    };
  } else { // google service is up to 10 Waypoint.
    from = points.shift();
    to = points.pop();
    request = {
      origin:      from['location'],
      waypoints:   points,
      destination: to['location'],
      travelMode:  google.maps.DirectionsTravelMode.DRIVING
    };
  }

  directionsService.route(request, function(response, status){
    if(status == google.maps.DirectionsStatus.OK){
      directionsDisplay.setDirections(response);
    }
  });
}
<|endoftext|>


<commit_before>function rickshawFitToWindow(graph) {
	if (window.innerWidth < 768) { r = 200 } else { r = 500 }
	graph.configure({ width: window.innerWidth - r });
	graph.render();
}

function dynamicWidth(graph) {
	rickshawFitToWindow(graph); // do it naow
	$(window).on('resize', function(){ rickshawFitToWindow(graph) });
}
function renderWaiting(element) {
	document.getElementById(element).innerHTML = ""
}

function unrenderWaiting() {
	$(".icon-spinner").hide()
}

function renderError(element, error, detail) {
	error_alert = "
"+error
	if (detail) { error_alert += "
"+detail }
	error_alert += "
"
	document.getElementById(element).innerHTML = error_alert
}

function metricURL(base, start, stop, step){
	return base+"&start="+start+"&stop="+stop+"&step="+step
}

function stopButtonClick() {
        stopUpdates()
	$("#autoplay_stop").hide()
	$("#autoplay_play").show()
}
function stopAll() {
        stopUpdates()
	stopButtonClick()
	unrenderWaiting()
}

function metric_sort() {

        $("#graphed_metrics").sortable({
                stop: function(event, ui) {
                        var metrics = [], params = []
                        $(".sortable").each(function(i,el){
                                metrics.push("metric="+$(el).find("span.metric")[0].dataset.metric)
                        })
                        $.each(location.search.split("&"), function(i, d) {
                                if(d.indexOf("metric") == -1) { params.push(d) }
                                } )
                        new_url = location.origin + location.pathname +"?"+ params.join("&").replace("?","") +"&"+metrics.join("&")
                        window.location.href= new_url
                }
        })
/}
<commit_msg>Errant character<commit_after>function rickshawFitToWindow(graph) {
	if (window.innerWidth < 768) { r = 200 } else { r = 500 }
	graph.configure({ width: window.innerWidth - r });
	graph.render();
}

function dynamicWidth(graph) {
	rickshawFitToWindow(graph); // do it naow
	$(window).on('resize', function(){ rickshawFitToWindow(graph) });
}
function renderWaiting(element) {
	document.getElementById(element).innerHTML = ""
}

function unrenderWaiting() {
	$(".icon-spinner").hide()
}

function renderError(element, error, detail) {
	error_alert = "
"+error
	if (detail) { error_alert += "
"+detail }
	error_alert += "
"
	document.getElementById(element).innerHTML = error_alert
}

function metricURL(base, start, stop, step){
	return base+"&start="+start+"&stop="+stop+"&step="+step
}

function stopButtonClick() {
        stopUpdates()
	$("#autoplay_stop").hide()
	$("#autoplay_play").show()
}
function stopAll() {
        stopUpdates()
	stopButtonClick()
	unrenderWaiting()
}

function metric_sort() {

        $("#graphed_metrics").sortable({
                stop: function(event, ui) {
                        var metrics = [], params = []
                        $(".sortable").each(function(i,el){
                                metrics.push("metric="+$(el).find("span.metric")[0].dataset.metric)
                        })
                        $.each(location.search.split("&"), function(i, d) {
                                if(d.indexOf("metric") == -1) { params.push(d) }
                                } )
                        new_url = location.origin + location.pathname +"?"+ params.join("&").replace("?","") +"&"+metrics.join("&")
                        window.location.href= new_url
                }
        })
}
<|endoftext|>


<commit_before>var live_update = function(){
  var live_update = $('#live-update');
  var update_fragment = document.createDocumentFragment();
  $.get( "live_update.js", function( data ) {
    console.log(data);
    // $("#live-update-contents").html(
    eval(data);
  });
};

$(function () {
  if ($('#live-update')[0] != undefined) {
    setInterval(live_update, 1000);
  };
});<commit_msg>disable eval<commit_after>var live_update = function(){
  var live_update = $('#live-update');
  var update_fragment = document.createDocumentFragment();
  $.get( "live_update.js", function( data ) {
    console.log(data);
    // $("#live-update-contents").html(
    // eval(data);
  });
};

$(function () {
  if ($('#live-update')[0] != undefined) {
    setInterval(live_update, 1000);
  };
});<|endoftext|>


<commit_before>#!/usr/bin/env node
var version = 12;

console.log("Octo-Node v" + version + " starting...");

console.log("Waking up...");

var cfg = require("./config");
cfg.version = version;
var tools = require("./tools");
var uuid = require("node-uuid");
var nodeid = uuid();
var os = require("os");
var dgram = require("dgram");
var ips = null;
var peers = [];

var s = dgram.createSocket("udp4");

function debug(msg) {
	if (cfg.debug) {
		console.log(msg);
	}
}

function sendToIP(ip, msg) {
	msg.octo = true;
	msg.from = nodeid;
	msg.version = cfg.version;
	var buf = new Buffer(JSON.stringify(msg));
	s.send(buf, 0, buf.length, 42042, ip);
}

function sendToID(id, msg) {
	var found = false;
	peers.forEach(function(v) {
		if (v.id == id) {
			sendToIP(v.ip, msg);
			found = true;
		}
	});
	if (!found) {
		debug("Failed to send message to " + id);
		debug(JSON.stringify(msg));
		console.log(peers);
	}
}

function registerPeer(addr, id) {
	sendToIP(addr, {
		cmd: "register",
		args: {
			ips: ips,
			from: nodeid,
			leech: cfg.leech
		},
		to: id
	});
}

function announcePeers(peer) {
	if (peer) {
		console.log(peer + " joined : " + peers.length + " total peers");
	} else {
		console.log("Taking over the world with " + peers.length + " friend(s)");
	}
}

function start() {
	console.log("Planning...");
	s.bind(42042, "0.0.0.0", function() {
		console.log("Writing letters...");
		cfg.seeds.forEach(function(v) {
			registerPeer(v);
		});
		console.log("Letters mailed to " + cfg.seeds.length + " friend(s)");
		console.log("Now accepting incoming connections");
	});
}

tools.ipList(function(iplist) {
	ips = iplist;
	start();
});

var commands = {};

commands.ping = function(args, peer) {
	sendToID(peer.id, {
		cmd: "pong"
	});
};

commands.pong = function(args, peer) {
	peer.ping = true;
};

commands.register = function(args, rinfo) {
	if (args.ips && args.from) {
		if (peers.length >= cfg.maxPeers) { return; }
		peers.push({
			ping: true,
			ip: rinfo.address,
			ips: args.ips,
			id: args.from,
			leech: args.leech
		});
		registerPeer(rinfo.address);
		announcePeers(args.from);
		console.log(peers);
	}
};

commands.peerlist = function(args, peer) {
	if (args.peers && !cfg.leech) {
		args.peers.forEach(function(v) {
			var found = false;
			peers.forEach(function(vpeer) {
				if (vpeer.id == v.id) {
					found = true;
				}
			});
			if (!found) {
				v.ips.forEach(function(vip) {
					registerPeer(vip, v.id);
				});
			}
		});
	}
};

commands.getpeerlist = function(args, peer) {
	var sendpeers = [];
	peers.forEach(function(v) {
		if (!v.leech && v.id != peer.id) {
			sendpeers.push(v);
		}
	});
	sendToID(peer.id, {
		cmd: "peerlist",
		args: sendpeers
	});
};

s.on("message", function(buf, rinfo) {
	var msg = JSON.parse(buf.toString());
	if (msg) {
		if (msg["octo"] && msg["cmd"] && msg["from"] && msg["version"]) {
			if (commands[msg["cmd"]] && msg["version"] == cfg.version) {
				if(msg["to"]) {
					if(msg["to"] != nodeid) {
						debug("Received message ment for someone else");
						return;
					}
				}
				if (msg["cmd"] != "register") {
					peers.forEach(function(v) {
						if (v.ip == rinfo.address && v.id == msg["from"]) {
							commands[msg["cmd"]](msg["args"], v);
						}
					});
				} else {
					var exit = false;
					peers.forEach(function(v) {
						if (v.ip == rinfo.address) {
							exit = true;
						}
					});
					if (exit) { return; }
					commands.register(msg["args"], rinfo);
				}
			}
		}
	}
});

setInterval(function() {
	var toRemove = [];
	peers.forEach(function(peer) {
		if (peer.ping) {
			peer.ping = false;
			sendToID(peer.id, {
				cmd: "ping"
			});
		} else {
			toRemove.push(peer.id);
		}
		if (toRemove.length > 0) {
			toRemove.forEach(function(id) {
				var newPeers = [];
				peers.forEach(function(peer) {
					if (peer.id != id) {
						newPeers.push(JSON.parse(JSON.stringify(peer)));
					}
				});
				peers = newPeers;
			});
			announcePeers();
		}
	});
}, 1000 * 5);

if (!cfg.leech) {
	setInterval(function() {
		peers.forEach(function(peer) {
			sendToID(peer.id, {
				cmd: "getpeerlist"
			});
		});
	}, 1000 * 60);
}
<commit_msg>Remove debug<commit_after>#!/usr/bin/env node
var version = 12;

console.log("Octo-Node v" + version + " starting...");

console.log("Waking up...");

var cfg = require("./config");
cfg.version = version;
var tools = require("./tools");
var uuid = require("node-uuid");
var nodeid = uuid();
var os = require("os");
var dgram = require("dgram");
var ips = null;
var peers = [];

var s = dgram.createSocket("udp4");

function debug(msg) {
	if (cfg.debug) {
		console.log(msg);
	}
}

function sendToIP(ip, msg) {
	msg.octo = true;
	msg.from = nodeid;
	msg.version = cfg.version;
	var buf = new Buffer(JSON.stringify(msg));
	s.send(buf, 0, buf.length, 42042, ip);
}

function sendToID(id, msg) {
	var found = false;
	peers.forEach(function(v) {
		if (v.id == id) {
			sendToIP(v.ip, msg);
			found = true;
		}
	});
	if (!found) {
		debug("Failed to send message to " + id);
		debug(JSON.stringify(msg));
		console.log(peers);
	}
}

function registerPeer(addr, id) {
	sendToIP(addr, {
		cmd: "register",
		args: {
			ips: ips,
			from: nodeid,
			leech: cfg.leech
		},
		to: id
	});
}

function announcePeers(peer) {
	if (peer) {
		console.log(peer + " joined : " + peers.length + " total peers");
	} else {
		console.log("Taking over the world with " + peers.length + " friend(s)");
	}
}

function start() {
	console.log("Planning...");
	s.bind(42042, "0.0.0.0", function() {
		console.log("Writing letters...");
		cfg.seeds.forEach(function(v) {
			registerPeer(v);
		});
		console.log("Letters mailed to " + cfg.seeds.length + " friend(s)");
		console.log("Now accepting incoming connections");
	});
}

tools.ipList(function(iplist) {
	ips = iplist;
	start();
});

var commands = {};

commands.ping = function(args, peer) {
	sendToID(peer.id, {
		cmd: "pong"
	});
};

commands.pong = function(args, peer) {
	peer.ping = true;
};

commands.register = function(args, rinfo) {
	if (args.ips && args.from) {
		if (peers.length >= cfg.maxPeers) { return; }
		peers.push({
			ping: true,
			ip: rinfo.address,
			ips: args.ips,
			id: args.from,
			leech: args.leech
		});
		registerPeer(rinfo.address);
		announcePeers(args.from);
	}
};

commands.peerlist = function(args, peer) {
	if (args.peers && !cfg.leech) {
		args.peers.forEach(function(v) {
			var found = false;
			peers.forEach(function(vpeer) {
				if (vpeer.id == v.id) {
					found = true;
				}
			});
			if (!found) {
				v.ips.forEach(function(vip) {
					registerPeer(vip, v.id);
				});
			}
		});
	}
};

commands.getpeerlist = function(args, peer) {
	var sendpeers = [];
	peers.forEach(function(v) {
		if (!v.leech && v.id != peer.id) {
			sendpeers.push(v);
		}
	});
	sendToID(peer.id, {
		cmd: "peerlist",
		args: sendpeers
	});
};

s.on("message", function(buf, rinfo) {
	var msg = JSON.parse(buf.toString());
	if (msg) {
		if (msg["octo"] && msg["cmd"] && msg["from"] && msg["version"]) {
			if (commands[msg["cmd"]] && msg["version"] == cfg.version) {
				if(msg["to"]) {
					if(msg["to"] != nodeid) {
						debug("Received message ment for someone else");
						return;
					}
				}
				if (msg["cmd"] != "register") {
					peers.forEach(function(v) {
						if (v.ip == rinfo.address && v.id == msg["from"]) {
							commands[msg["cmd"]](msg["args"], v);
						}
					});
				} else {
					var exit = false;
					peers.forEach(function(v) {
						if (v.ip == rinfo.address) {
							exit = true;
						}
					});
					if (exit) { return; }
					commands.register(msg["args"], rinfo);
				}
			}
		}
	}
});

setInterval(function() {
	var toRemove = [];
	peers.forEach(function(peer) {
		if (peer.ping) {
			peer.ping = false;
			sendToID(peer.id, {
				cmd: "ping"
			});
		} else {
			toRemove.push(peer.id);
		}
		if (toRemove.length > 0) {
			toRemove.forEach(function(id) {
				var newPeers = [];
				peers.forEach(function(peer) {
					if (peer.id != id) {
						newPeers.push(JSON.parse(JSON.stringify(peer)));
					}
				});
				peers = newPeers;
			});
			announcePeers();
		}
	});
}, 1000 * 5);

if (!cfg.leech) {
	setInterval(function() {
		peers.forEach(function(peer) {
			sendToID(peer.id, {
				cmd: "getpeerlist"
			});
		});
	}, 1000 * 60);
}
<|endoftext|>


<commit_before>'use strict';
const axios = require('axios');
const pkg = require('../../package.json');
const {
  helpers: {
    mergeData,
  },
  classes: {
    Response,
    ResponseError,
  },
} = require('@sendgrid/helpers');

const API_KEY_PREFIX = 'SG.';

class Client {
  constructor() {
    this.apiKey = '';

    this.defaultHeaders = {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'User-agent': 'sendgrid/' + pkg.version + ';nodejs',
    };

    this.defaultRequest = {
      baseUrl: 'https://api.sendgrid.com/',
      url: '',
      method: 'GET',
      headers: {},
    };
  }

  setApiKey(apiKey) {
    this.apiKey = apiKey;

    if (!this.isValidApiKey(apiKey)) {
      console.warn(`API key does not start with "${API_KEY_PREFIX}".`);
    }
  }

  isValidApiKey(apiKey) {
    return this.isString(apiKey) && apiKey.trim().startsWith(API_KEY_PREFIX);
  }

  isString(value) {
    return typeof value === 'string' || value instanceof String;
  }

  setDefaultHeader(key, value) {
    this.defaultHeaders[key] = value;
    return this;
  }

  setDefaultRequest(key, value) {
    this.defaultRequest[key] = value;
    return this;
  }

  createHeaders(data) {
    // Merge data with default headers.
    const headers = mergeData(this.defaultHeaders, data);

    // Add API key, but don't overwrite if header already set.
    if (typeof headers.Authorization === 'undefined' && this.apiKey) {
      headers.Authorization = 'Bearer ' + this.apiKey;
    }

    return headers;
  }

  createRequest(data) {
    let options = {
      url: data.uri || data.url,
      baseUrl: data.baseUrl,
      method: data.method,
      data: data.body,
      params: data.qs,
      headers: data.headers,
    };

    // Merge data with default request.
    options = mergeData(this.defaultRequest, options);
    options.headers = this.createHeaders(options.headers);
    options.baseURL = options.baseUrl;
    delete options.baseUrl;

    return options;
  }

  request(data, cb) {
    data = this.createRequest(data);

    const promise = new Promise((resolve, reject) => {
      axios(data)
        .then(response => {
          return resolve([
            new Response(response.status, response.data, response.headers),
            response.data,
          ]);
        })
        .catch(error => {
          if (error.response) {
            if (error.response.status >= 400) {
              return reject(new ResponseError(error.response));
            }
          }
          return reject(error);
        });
    });

    // Throw an error in case a callback function was not passed.
    if (cb && typeof cb !== 'function') {
      throw new Error('Callback passed is not a function.');
    }

    if (cb) {
      return promise
        .then(result => cb(null, result))
        .catch(error => cb(error, null));
    }

    return promise;
  }
}

module.exports = Client;
<commit_msg>fix: correct the User-Agent casing (#1084)<commit_after>'use strict';
const axios = require('axios');
const pkg = require('../../package.json');
const {
  helpers: {
    mergeData,
  },
  classes: {
    Response,
    ResponseError,
  },
} = require('@sendgrid/helpers');

const API_KEY_PREFIX = 'SG.';

class Client {
  constructor() {
    this.apiKey = '';

    this.defaultHeaders = {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'User-Agent': 'sendgrid/' + pkg.version + ';nodejs',
    };

    this.defaultRequest = {
      baseUrl: 'https://api.sendgrid.com/',
      url: '',
      method: 'GET',
      headers: {},
    };
  }

  setApiKey(apiKey) {
    this.apiKey = apiKey;

    if (!this.isValidApiKey(apiKey)) {
      console.warn(`API key does not start with "${API_KEY_PREFIX}".`);
    }
  }

  isValidApiKey(apiKey) {
    return this.isString(apiKey) && apiKey.trim().startsWith(API_KEY_PREFIX);
  }

  isString(value) {
    return typeof value === 'string' || value instanceof String;
  }

  setDefaultHeader(key, value) {
    this.defaultHeaders[key] = value;
    return this;
  }

  setDefaultRequest(key, value) {
    this.defaultRequest[key] = value;
    return this;
  }

  createHeaders(data) {
    // Merge data with default headers.
    const headers = mergeData(this.defaultHeaders, data);

    // Add API key, but don't overwrite if header already set.
    if (typeof headers.Authorization === 'undefined' && this.apiKey) {
      headers.Authorization = 'Bearer ' + this.apiKey;
    }

    return headers;
  }

  createRequest(data) {
    let options = {
      url: data.uri || data.url,
      baseUrl: data.baseUrl,
      method: data.method,
      data: data.body,
      params: data.qs,
      headers: data.headers,
    };

    // Merge data with default request.
    options = mergeData(this.defaultRequest, options);
    options.headers = this.createHeaders(options.headers);
    options.baseURL = options.baseUrl;
    delete options.baseUrl;

    return options;
  }

  request(data, cb) {
    data = this.createRequest(data);

    const promise = new Promise((resolve, reject) => {
      axios(data)
        .then(response => {
          return resolve([
            new Response(response.status, response.data, response.headers),
            response.data,
          ]);
        })
        .catch(error => {
          if (error.response) {
            if (error.response.status >= 400) {
              return reject(new ResponseError(error.response));
            }
          }
          return reject(error);
        });
    });

    // Throw an error in case a callback function was not passed.
    if (cb && typeof cb !== 'function') {
      throw new Error('Callback passed is not a function.');
    }

    if (cb) {
      return promise
        .then(result => cb(null, result))
        .catch(error => cb(error, null));
    }

    return promise;
  }
}

module.exports = Client;
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';

const { Component, computed, inject, RSVP, ObjectProxy } = Ember;
const { PromiseArray, PromiseObject } = DS;
const { service } = inject;
const { sort, not, alias, collect } = computed;
const { Promise } = RSVP;

const SessionProxy = ObjectProxy.extend({
  content: null,
  currentUser: null,
  expandOfferings: false,
  showRemoveConfirmation: false,
  userCanDelete: computed('content.course', 'currentUser.model.directedCourses.[]', function(){
    let defer = RSVP.defer();
    this.get('currentUser.userIsDeveloper').then(isDeveloper => {
      if(isDeveloper){
        defer.resolve(true);
      } else {
        this.get('content').get('course').then(course => {
          this.get('currentUser.model').then(user => {
            user.get('directedCourses').then(directedCourses => {
              defer.resolve(directedCourses.contains(course));
            });
          });
        });
      }
    });

    return PromiseObject.create({
      promise: defer.promise
    });
  })
});

export default Component.extend({
  classNames: ['detail-view', 'sessions-list'],

  store: service(),
  i18n: service(),
  currentUser: service(),

  editable: not('course.locked'),
  sessionsCount: alias('sessions.length'),
  sessions: alias('course.sessions'),
  offset: 0,
  limit: 25,

  filterBy: null,
  course: null,

  proxiedSessions: computed('sessions.[]', function() {
    return new Promise( resolve => {
      this.get('sessions').then(sessions => {
        return RSVP.map(sessions.toArray(), session => {
          return RSVP.hash({
            sessionType: session.get('sessionType'),
            firstOfferingDate: session.get('firstOfferingDate'),
            associatedOfferingLearnerGroups: session.get('associatedOfferingLearnerGroups'),
            offerings: session.hasMany('offerings').ids(),
          }).then(({sessionType, firstOfferingDate, associatedOfferingLearnerGroups, offerings})=> {
            return SessionProxy.create({
              content: session,
              currentUser: this.get('currentUser'),
              sessionType: sessionType.get('title'),
              firstOfferingDate,
              learnerGroupCount: associatedOfferingLearnerGroups.get('length'),
              offeringCount: offerings.get('length')
            });
          });
        }).then((proxiedSessions => {
          resolve(proxiedSessions);
        }));
      });
    });
  }),

  filteredContent: computed('proxiedSessions.[]', 'filterBy', function(){
    let defer = RSVP.defer();
    this.get('proxiedSessions').then(sessions => {
      let filter = this.get('filterBy');
      let filterExpressions = filter.split(' ').map(function(string){
        return new RegExp(string, 'gi');
      });
      let filtered = sessions.filter(session => {
        let searchString = session.get('searchString');
        if(searchString === null || searchString === undefined){
          return false;
        }
        let matchedSearchTerms = 0;
        for (let i = 0; i < filterExpressions.length; i++) {
          if(searchString.match(filterExpressions[i])){
            matchedSearchTerms++;
          }
        }
        //if the number of matching search terms is equal to the number searched, return true
        return (matchedSearchTerms === filterExpressions.length);
      });

      defer.resolve(filtered.sortBy('title'));
    });

    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  sortBy: 'title',
  sortSessionsBy: collect('sortBy'),
  sortedSessions: sort('filteredContent', 'sortSessionsBy'),
  sortedAscending: computed('sortBy', function(){
    const sortBy = this.get('sortBy');
    return sortBy.search(/desc/) === -1;
  }),
  displayedSessions: computed('sortedSessions.[]', 'sortBy', 'offset', 'limit', function(){
    const limit = this.get('limit');
    const offset = this.get('offset');
    const end = limit + offset;
    let sessions = this.get('sortedSessions');

    return sessions.slice(offset, end);
  }),

  editorOn: false,

  saved: false,
  savedSession: null,
  isSaving: null,

  sessionTypes: computed('course.school.sessionTypes.[]', function(){
    return new Promise( resolve => {
      const course = this.get('course');
      course.get('school').then(school => {
        school.get('sessionTypes').then(sessionTypes => {
          resolve(sessionTypes);
        });
      });
    });
  }),

  actions: {
    toggleEditor() {
      if (this.get('editorOn')) {
        this.set('editorOn', false);
      } else {
        this.setProperties({ editorOn: true, saved: false });
      }
    },

    cancel() {
      this.set('editorOn', false);
    },

    save(session) {
      this.set('isSaving', true);
      const course = this.get('course');
      session.set('course', course);

      return session.save().then((savedSession) => {
        this.setProperties({ saved: true, savedSession, isSaving: false });
      });
    },

    toggleExpandedOffering(sessionProxy){
      sessionProxy.set('expandOfferings', !sessionProxy.get('expandOfferings'));
    },
    confirmRemoval(sessionProxy){
      sessionProxy.set('showRemoveConfirmation', true);
    },
    remove(sessionProxy){
      let session = sessionProxy.get('content');
      session.deleteRecord();
      session.save();
    },
    cancelRemove(sessionProxy){
      sessionProxy.set('showRemoveConfirmation', false);
    },
    sortBy(what){
      const sortBy = this.get('sortBy');
      if(sortBy === what){
        what += ':desc';
      }
      this.get('setSortBy')(what);
    },
  }
});
<commit_msg>plugged aggregated learner group count into sessions table.<commit_after>import Ember from 'ember';
import DS from 'ember-data';

const { Component, computed, inject, RSVP, ObjectProxy } = Ember;
const { PromiseArray, PromiseObject } = DS;
const { service } = inject;
const { sort, not, alias, collect } = computed;
const { Promise } = RSVP;

const SessionProxy = ObjectProxy.extend({
  content: null,
  currentUser: null,
  expandOfferings: false,
  showRemoveConfirmation: false,
  userCanDelete: computed('content.course', 'currentUser.model.directedCourses.[]', function(){
    let defer = RSVP.defer();
    this.get('currentUser.userIsDeveloper').then(isDeveloper => {
      if(isDeveloper){
        defer.resolve(true);
      } else {
        this.get('content').get('course').then(course => {
          this.get('currentUser.model').then(user => {
            user.get('directedCourses').then(directedCourses => {
              defer.resolve(directedCourses.contains(course));
            });
          });
        });
      }
    });

    return PromiseObject.create({
      promise: defer.promise
    });
  })
});

export default Component.extend({
  classNames: ['detail-view', 'sessions-list'],

  store: service(),
  i18n: service(),
  currentUser: service(),

  editable: not('course.locked'),
  sessionsCount: alias('sessions.length'),
  sessions: alias('course.sessions'),
  offset: 0,
  limit: 25,

  filterBy: null,
  course: null,

  proxiedSessions: computed('sessions.[]', function() {
    return new Promise( resolve => {
      this.get('sessions').then(sessions => {
        return RSVP.map(sessions.toArray(), session => {
          return RSVP.hash({
            sessionType: session.get('sessionType'),
            firstOfferingDate: session.get('firstOfferingDate'),
            associatedLearnerGroups: session.get('associatedLearnerGroups'),
            offerings: session.hasMany('offerings').ids(),
          }).then(({sessionType, firstOfferingDate, associatedLearnerGroups, offerings})=> {
            return SessionProxy.create({
              content: session,
              currentUser: this.get('currentUser'),
              sessionType: sessionType.get('title'),
              firstOfferingDate,
              learnerGroupCount: associatedLearnerGroups.get('length'),
              offeringCount: offerings.get('length')
            });
          });
        }).then((proxiedSessions => {
          resolve(proxiedSessions);
        }));
      });
    });
  }),

  filteredContent: computed('proxiedSessions.[]', 'filterBy', function(){
    let defer = RSVP.defer();
    this.get('proxiedSessions').then(sessions => {
      let filter = this.get('filterBy');
      let filterExpressions = filter.split(' ').map(function(string){
        return new RegExp(string, 'gi');
      });
      let filtered = sessions.filter(session => {
        let searchString = session.get('searchString');
        if(searchString === null || searchString === undefined){
          return false;
        }
        let matchedSearchTerms = 0;
        for (let i = 0; i < filterExpressions.length; i++) {
          if(searchString.match(filterExpressions[i])){
            matchedSearchTerms++;
          }
        }
        //if the number of matching search terms is equal to the number searched, return true
        return (matchedSearchTerms === filterExpressions.length);
      });

      defer.resolve(filtered.sortBy('title'));
    });

    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  sortBy: 'title',
  sortSessionsBy: collect('sortBy'),
  sortedSessions: sort('filteredContent', 'sortSessionsBy'),
  sortedAscending: computed('sortBy', function(){
    const sortBy = this.get('sortBy');
    return sortBy.search(/desc/) === -1;
  }),
  displayedSessions: computed('sortedSessions.[]', 'sortBy', 'offset', 'limit', function(){
    const limit = this.get('limit');
    const offset = this.get('offset');
    const end = limit + offset;
    let sessions = this.get('sortedSessions');

    return sessions.slice(offset, end);
  }),

  editorOn: false,

  saved: false,
  savedSession: null,
  isSaving: null,

  sessionTypes: computed('course.school.sessionTypes.[]', function(){
    return new Promise( resolve => {
      const course = this.get('course');
      course.get('school').then(school => {
        school.get('sessionTypes').then(sessionTypes => {
          resolve(sessionTypes);
        });
      });
    });
  }),

  actions: {
    toggleEditor() {
      if (this.get('editorOn')) {
        this.set('editorOn', false);
      } else {
        this.setProperties({ editorOn: true, saved: false });
      }
    },

    cancel() {
      this.set('editorOn', false);
    },

    save(session) {
      this.set('isSaving', true);
      const course = this.get('course');
      session.set('course', course);

      return session.save().then((savedSession) => {
        this.setProperties({ saved: true, savedSession, isSaving: false });
      });
    },

    toggleExpandedOffering(sessionProxy){
      sessionProxy.set('expandOfferings', !sessionProxy.get('expandOfferings'));
    },
    confirmRemoval(sessionProxy){
      sessionProxy.set('showRemoveConfirmation', true);
    },
    remove(sessionProxy){
      let session = sessionProxy.get('content');
      session.deleteRecord();
      session.save();
    },
    cancelRemove(sessionProxy){
      sessionProxy.set('showRemoveConfirmation', false);
    },
    sortBy(what){
      const sortBy = this.get('sortBy');
      if(sortBy === what){
        what += ':desc';
      }
      this.get('setSortBy')(what);
    },
  }
});
<|endoftext|>


<commit_before>import './SearchBoxHelp.css';
import React, { Component } from 'react';
import MaterialIcon from 'shared/components/icon/MaterialIcon';
import Tooltip from 'shared/components/tooltip/Tooltip';

export default class SearchBoxHelp extends Component {
    shouldComponentUpdate() {
        return false;
    }

    render() {
        const overlay = (

You may use search qualifiers in any combination.

author:sindresorhus Show or filter results by author

maintainer:sindresorhus Show or filter results by maintainer

keywords:gulpplugin Show or filter results by keywords

not:deprecated Exclude packages that are deprecated, unstable or insecure

For the complete list of qualifiers, please read the Search API documentation.

        );

        return (

                <Tooltip overlayClassName="search-box-help-component-tooltip" placement="top" overlay={ overlay }>
                    <MaterialIcon id="help_outline" className="help" />
                </Tooltip>

        );
    }
}
<commit_msg>Tip is outside.<commit_after>import './SearchBoxHelp.css';
import React, { Component } from 'react';
import MaterialIcon from 'shared/components/icon/MaterialIcon';
import Tooltip from 'shared/components/tooltip/Tooltip';

export default class SearchBoxHelp extends Component {
    shouldComponentUpdate() {
        return false;
    }

    render() {
        const overlay = (

You may use search qualifiers in any combination.

author:sindresorhus Show or filter results by author

maintainer:sindresorhus Show or filter results by maintainer

keywords:gulpplugin Show or filter results by keywords

not:deprecated Exclude packages that are deprecated, unstable or insecure

For the complete list of qualifiers, please read the Search API documentation.

        );

        return (
            <Tooltip overlayClassName="search-box-help-component-tooltip" placement="bottom" overlay={ overlay }>

                    <MaterialIcon id="help_outline" className="help" />

            </Tooltip>
        );
    }
}
<|endoftext|>