<commit_before>/* global angular Firebase */

(function(){
  'use strict';

  angular.module('beautyMark', ['ngRoute'])

    .config(function($routeProvider){

      // routeProvider homepage
      $routeProvider.when('/homepage', {
        templateUrl: 'views/homepage.html'
      });
      // END $routeProvider homepage

      // NAILS routes
      // routeProvider nails
      $routeProvider.when('/nails', {
        templateUrl: 'views/nails/category.html'
      });
      // END $routeProvider nails

      // routeProvider nails/add
      $routeProvider.when('/nails/add', {
        templateUrl: 'views/nails/add.html'
      });
      // END $routeProvider nails/add

      // routeProvider nails/item
      $routeProvider.when('/nails/item', {
        templateUrl: 'views/nails/item.html'
      });
      // END $routeProvider nails/item
      // END NAILS routes

      // routeProvider eyes
      $routeProvider.when('/eyes', {
        templateUrl: 'views/eyes/category.html'
      });
      // END $routeProvider eyes

      // routeProvider face
      $routeProvider.when('/face', {
        templateUrl: 'views/face/category.html'
      });
      // END $routeProvider face

      // routeProvider lips
      $routeProvider.when('/lips', {
        templateUrl: 'views/lips/category.html'
      });
      // END $routeProvider lips

      // routeProvider hair
      $routeProvider.when('/hair', {
        templateUrl: 'views/hair/category.html'
      });
      // END $routeProvider hair

      // routeProvider tools
      $routeProvider.when('/tools', {
        templateUrl: 'views/tools/category.html'
      });
      // END $routeProvider tools
    });

})();
<commit_msg>removed Firebase from global statement... not used yet<commit_after>/* global angular */

(function(){
  'use strict';

  angular.module('beautyMark', ['ngRoute'])

    .config(function($routeProvider){

      // routeProvider homepage
      $routeProvider.when('/homepage', {
        templateUrl: 'views/homepage.html'
      });
      // END $routeProvider homepage

      // NAILS routes
      // routeProvider nails
      $routeProvider.when('/nails', {
        templateUrl: 'views/nails/category.html'
      });
      // END $routeProvider nails

      // routeProvider nails/add
      $routeProvider.when('/nails/add', {
        templateUrl: 'views/nails/add.html'
      });
      // END $routeProvider nails/add

      // routeProvider nails/item
      $routeProvider.when('/nails/item', {
        templateUrl: 'views/nails/item.html'
      });
      // END $routeProvider nails/item
      // END NAILS routes

      // routeProvider eyes
      $routeProvider.when('/eyes', {
        templateUrl: 'views/eyes/category.html'
      });
      // END $routeProvider eyes

      // routeProvider face
      $routeProvider.when('/face', {
        templateUrl: 'views/face/category.html'
      });
      // END $routeProvider face

      // routeProvider lips
      $routeProvider.when('/lips', {
        templateUrl: 'views/lips/category.html'
      });
      // END $routeProvider lips

      // routeProvider hair
      $routeProvider.when('/hair', {
        templateUrl: 'views/hair/category.html'
      });
      // END $routeProvider hair

      // routeProvider tools
      $routeProvider.when('/tools', {
        templateUrl: 'views/tools/category.html'
      });
      // END $routeProvider tools
    });

})();
<|endoftext|>


<commit_before>var resizeMap;
var map;
var marker;
var address;

(function($) {
  // Let's define a global function, to be called when initializing or when
  // the window resizes.
  resizeMap = function() {
    var assetImgHeight = $('.primary-asset img').height();
    $('#geotagging-map').height(assetImgHeight);
    google.maps.event.trigger(map, 'resize');
  }

  var showError = function(msg) {
    $error = $('
');
    $error.text(msg);
    $('.geotagging').append($error);
  };

  $('.call-to-action .btn').click(function() {
    $(this).hide();
    if(!window.localStorage.getItem('geotagging-overlay-closed')) {
      $('.geotagging .overlay').show();
    }
    $('.map-container').slideDown('slow', function() {
      // resize google map to match asset image on click and on window resize
      $( window ).bind('resize', resizeMap).trigger('resize');
      map.setCenter(marker.getPosition());
    });
  });

  $('.map-buttons .hide-map').click(function() {
    $('.map-container').slideUp('slow', function() {
      $('.call-to-action .btn').show();
      $( window ).unbind('resize', resizeMap);
    });
  });

  $('.overlay .close-overlay').click(function() {
    window.localStorage.setItem('geotagging-overlay-closed', true);
    $('.geotagging .overlay').hide();
  });

  $('.map-buttons .save-coordinates').click(function() {
    $(this).addClass('disabled');
    var data = {
      force: location.search.indexOf('forceGeotagging') !== -1
    };
    if(map.getStreetView().getVisible()){
      data.latitude = map.getStreetView().getPosition().lat();
      data.longitude = map.getStreetView().getPosition().lng();
      data.pov = map.getStreetView().getPov();
    } else{
      data.latitude = marker.getPosition().lat();
      data.longitude = marker.getPosition().lng();
    }
    var $item = $('.item');
    var catalogAlias = $item.data('catalog-alias');
    var itemId = $item.data('item-id');
    console.log('Saving geo-tag', catalogAlias, itemId, data);
    var url = '/' + catalogAlias + '/' + itemId + '/save-geotag';
    $.ajax({
      type: 'post',
      url: url,
      data: data,
      dataType: 'json',
      success: function(response) {
        if(response.success) {
          location.reload();
        } else {
          showError('Der skete en fejl - prøv igen');
        }
      },
      error: function(response) {
        var err = response.responseJSON;
        showError(err.message || 'Der skete en uventet fejl.');
      }
    });
  });
})(jQuery);

function initMap() {
  var initialPosition = new google.maps.LatLng(55.6747, 12.5747); // The National Museums coordinates
  var address = $('#address').text();

  geocoder = new google.maps.Geocoder();

  geocoder.geocode({ 'address': address }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var geocodeLocation = results[0].geometry.location;
        var geocodeLatLng = new google.maps.LatLng(geocodeLocation.lat(), geocodeLocation.lng());

        map.setCenter(geocodeLatLng);
        marker.setPosition(geocodeLatLng);
        google.maps.event.trigger(map, 'resize');
      }
  });

  map = new google.maps.Map(document.getElementById('geotagging-map'), {
    center: initialPosition,
    zoom: 12
  });

  marker = new google.maps.Marker({
    position: initialPosition,
    map: map,
    draggable:true
  });

  google.maps.event.addListener(map, 'click', function(event) {
    marker.setPosition(event.latLng);
  });

  resizeMap();
}
<commit_msg>Added more visual feedback when saving map coordinates<commit_after>var resizeMap;
var map;
var marker;
var address;

(function($) {
  // Let's define a global function, to be called when initializing or when
  // the window resizes.
  resizeMap = function() {
    var assetImgHeight = $('.primary-asset img').height();
    $('#geotagging-map').height(assetImgHeight);
    google.maps.event.trigger(map, 'resize');
  }

  var showError = function(msg) {
    $error = $('
');
    $error.text(msg);
    $('.geotagging').append($error);
  };

  $('.call-to-action .btn').click(function() {
    $(this).hide();
    if(!window.localStorage.getItem('geotagging-overlay-closed')) {
      $('.geotagging .overlay').show();
    }
    $('.map-container').slideDown('slow', function() {
      // resize google map to match asset image on click and on window resize
      $( window ).bind('resize', resizeMap).trigger('resize');
      map.setCenter(marker.getPosition());
    });
  });

  $('.map-buttons .hide-map').click(function() {
    $('.map-container').slideUp('slow', function() {
      $('.call-to-action .btn').show();
      $( window ).unbind('resize', resizeMap);
    });
  });

  $('.overlay .close-overlay').click(function() {
    window.localStorage.setItem('geotagging-overlay-closed', true);
    $('.geotagging .overlay').hide();
  });

  $('.map-buttons .save-coordinates').click(function() {
    $(this).addClass('disabled');
    $(this).text('Gemmer placering');
    $('.map-buttons .hide-map').hide();
    var data = {
      force: location.search.indexOf('forceGeotagging') !== -1
    };
    if(map.getStreetView().getVisible()){
      data.latitude = map.getStreetView().getPosition().lat();
      data.longitude = map.getStreetView().getPosition().lng();
      data.pov = map.getStreetView().getPov();
    } else{
      data.latitude = marker.getPosition().lat();
      data.longitude = marker.getPosition().lng();
    }
    var $item = $('.item');
    var catalogAlias = $item.data('catalog-alias');
    var itemId = $item.data('item-id');
    console.log('Saving geo-tag', catalogAlias, itemId, data);
    var url = '/' + catalogAlias + '/' + itemId + '/save-geotag';
    $.ajax({
      type: 'post',
      url: url,
      data: data,
      dataType: 'json',
      success: function(response) {
        if(response.success) {
          location.reload();
        } else {
          showError('Der skete en fejl - prøv igen');
        }
      },
      error: function(response) {
        var err = response.responseJSON;
        showError(err.message || 'Der skete en uventet fejl.');
      }
    });
  });
})(jQuery);

function initMap() {
  var initialPosition = new google.maps.LatLng(55.6747, 12.5747); // The National Museums coordinates
  var address = $('#address').text();

  geocoder = new google.maps.Geocoder();

  geocoder.geocode({ 'address': address }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var geocodeLocation = results[0].geometry.location;
        var geocodeLatLng = new google.maps.LatLng(geocodeLocation.lat(), geocodeLocation.lng());

        map.setCenter(geocodeLatLng);
        marker.setPosition(geocodeLatLng);
        google.maps.event.trigger(map, 'resize');
      }
  });

  map = new google.maps.Map(document.getElementById('geotagging-map'), {
    center: initialPosition,
    zoom: 12
  });

  marker = new google.maps.Marker({
    position: initialPosition,
    map: map,
    draggable:true
  });

  google.maps.event.addListener(map, 'click', function(event) {
    marker.setPosition(event.latLng);
  });

  resizeMap();
}
<|endoftext|>


<commit_before>var resizeMap;
var map;
var marker;
var headingMarker;

(function($) {
  // Let's define a global function, to be called when initializing or when
  // the window resizes.
  resizeMap = function() {
    var assetImgHeight = $('.primary-asset img').height();
    $('#geotagging-map').height(assetImgHeight);
    var center = map.getCenter();
    google.maps.event.trigger(map, 'resize');
    map.setCenter(center);
  }

  var showError = function(msg) {
    $error = $('
');
    $error.text(msg);
    $('.geotagging').append($error);
  };

  $('.call-to-action .btn').click(function() {
    $(this).hide();
    if(!window.localStorage.getItem('geotagging-overlay-closed')) {
      $('.geotagging .overlay').show();
    }
    $('.map-container').slideDown('slow', function() {
      // resize google map to match asset image on click and on window resize
      $( window ).bind('resize', resizeMap).trigger('resize');
    });
  });

  $('.map-buttons .hide-map').click(function() {
    $('.map-container').slideUp('slow', function() {
      $('.call-to-action .btn').show();
      $( window ).unbind('resize', resizeMap);
    });
  });

  $('.overlay .close-overlay').click(function() {
    window.localStorage.setItem('geotagging-overlay-closed', true);
    $('.geotagging .overlay').hide();
  });

  $('.map-buttons .save-coordinates').click(function() {
    $(this).addClass('disabled');
    $(this).text('Gemmer placering');
    $('.map-buttons .hide-map').hide();
    var data = {
      force: location.search.indexOf('forceGeotagging') !== -1
    };
    if(map.getStreetView().getVisible()){
      data.latitude = map.getStreetView().getPosition().lat();
      data.longitude = map.getStreetView().getPosition().lng();
      data.pov = map.getStreetView().getPov();
    } else{
      data.latitude = marker.getPosition().lat();
      data.longitude = marker.getPosition().lng();
    }
    var $item = $('.item');
    var catalogAlias = $item.data('catalog-alias');
    var itemId = $item.data('item-id');
    console.log('Saving geo-tag', catalogAlias, itemId, data);
    var url = '/' + catalogAlias + '/' + itemId + '/save-geotag';
    $.ajax({
      type: 'post',
      url: url,
      data: data,
      dataType: 'json',
      success: function(response) {
        if(response.success) {
          location.reload();
        } else {
          showError('Der skete en fejl - prøv igen');
        }
      },
      error: function(response) {
        var err = response.responseJSON;
        showError(err.message || 'Der skete en uventet fejl.');
      }
    });
  });
})(jQuery);

function initMap() {
  var initialPosition = new google.maps.LatLng(55.6747, 12.5747);
  var address = $('#address').text();

  if(address){
    geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'address': address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var geocodeLocation = results[0].geometry.location;
          var geocodeLatLng = new google.maps.LatLng(geocodeLocation.lat(), geocodeLocation.lng());

          map.setCenter(geocodeLatLng);
          resizeMap();
        }
    });
  }

  map = new google.maps.Map(document.getElementById('geotagging-map'), {
    center: initialPosition,
    zoom: 16
  });

  marker = new google.maps.Marker({
    map: map,
    draggable: true
  });

  headingMarker = new google.maps.Marker({
    map: map,
    icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
    draggable:true
  });

  var headingLine = new google.maps.Polyline({
    map: map,
    strokeColor: '#9E0B0F'
  });

  map.addListener('click', function(event) {
    // Ensure that the relative distance between markers is the same on every zoom level
    latIncrease = 100 * Math.pow(0.5, map.getZoom());
    headingMarkerPosition = new google.maps.LatLng(event.latLng.lat() + latIncrease, event.latLng.lng());

    marker.setPosition(event.latLng);
    headingMarker.setPosition(headingMarkerPosition);
    headingLine.setPath([event.latLng, headingMarkerPosition]);
  });

  marker.addListener('drag', function(event) {
    recalculateLine();
  });

  headingMarker.addListener('drag', function(event) {
    recalculateLine();
  });

  function recalculateLine(){
    headingLine.setPath([marker.getPosition(), headingMarker.getPosition()]);
  }

  resizeMap();
}
<commit_msg>Fix rebase conflict<commit_after>var resizeMap;
var map;
var marker;
var headingMarker;

(function($) {
  // Let's define a global function, to be called when initializing or when
  // the window resizes.
  resizeMap = function() {
    var assetImgHeight = $('.primary-asset img').height();
    $('#geotagging-map').height(assetImgHeight);
    var center = map.getCenter();
    google.maps.event.trigger(map, 'resize');
    map.setCenter(center);
  }

  var showError = function(msg) {
    $error = $('
');
    $error.text(msg);
    $('.geotagging').append($error);
  };

  $('.call-to-action .btn').click(function() {
    $(this).hide();
    if(!window.localStorage.getItem('geotagging-overlay-closed')) {
      $('.geotagging .overlay').show();
    }
    $('.map-container').slideDown('slow', function() {
      // resize google map to match asset image on click and on window resize
      $( window ).bind('resize', resizeMap).trigger('resize');
    });
  });

  $('.map-buttons .hide-map').click(function() {
    $('.map-container').slideUp('slow', function() {
      $('.call-to-action .btn').show();
      $( window ).unbind('resize', resizeMap);
    });
  });

  $('.overlay .close-overlay').click(function() {
    window.localStorage.setItem('geotagging-overlay-closed', true);
    $('.geotagging .overlay').hide();
  });

  $('.map-buttons .save-coordinates').click(function() {
    $(this).addClass('disabled');
    $(this).text('Gemmer placering');
    $('.map-buttons .hide-map').hide();
    var data = {
      force: location.search.indexOf('forceGeotagging') !== -1
    };
    if(map.getStreetView().getVisible()){
      data.latitude = map.getStreetView().getPosition().lat();
      data.longitude = map.getStreetView().getPosition().lng();
      data.pov = map.getStreetView().getPov();
    } else{
      data.latitude = marker.getPosition().lat();
      data.longitude = marker.getPosition().lng();
    }
    var $item = $('.item');
    var catalogAlias = $item.data('catalog-alias');
    var itemId = $item.data('item-id');
    console.log('Saving geo-tag', catalogAlias, itemId, data);
    var url = '/' + catalogAlias + '/' + itemId + '/save-geotag';
    $.ajax({
      type: 'post',
      url: url,
      data: data,
      dataType: 'json',
      success: function(response) {
        if(response.success) {
          location.reload();
        } else {
          showError('Der skete en fejl - prøv igen');
        }
      },
      error: function(response) {
        var err = response.responseJSON;
        showError(err.message || 'Der skete en uventet fejl.');
      }
    });
  });
})(jQuery);

function initMap() {
  var initialPosition = new google.maps.LatLng(55.6747, 12.5747);
  var address = $('#address').text();

  if(address){
    geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'address': address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var geocodeLocation = results[0].geometry.location;
          var geocodeLatLng = new google.maps.LatLng(geocodeLocation.lat(), geocodeLocation.lng());

          map.setCenter(geocodeLatLng);
          resizeMap();
        }
    });
  }

  map = new google.maps.Map(document.getElementById('geotagging-map'), {
    center: initialPosition,
    zoom: 16
  });

  marker = new google.maps.Marker({
    map: map,
    draggable: true
  });

  headingMarker = new google.maps.Marker({
    map: map,
    icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
    draggable:true
  });

  var headingLine = new google.maps.Polyline({
    map: map,
    strokeColor: '#9E0B0F'
  });

  map.addListener('click', function(event) {
    // Ensure that the relative distance between markers is the same on every zoom level
    latIncrease = 100 * Math.pow(0.5, map.getZoom());
    headingMarkerPosition = new google.maps.LatLng(event.latLng.lat() + latIncrease, event.latLng.lng());

    marker.setPosition(event.latLng);
    headingMarker.setPosition(headingMarkerPosition);
    headingLine.setPath([event.latLng, headingMarkerPosition]);
  });

  marker.addListener('drag', function(event) {
    recalculateLine();
  });

  headingMarker.addListener('drag', function(event) {
    recalculateLine();
  });

  function recalculateLine(){
    headingLine.setPath([marker.getPosition(), headingMarker.getPosition()]);
  }

  resizeMap();
}
<|endoftext|>


<commit_before>var resizeMap;
var map;
var marker;
var address;

(function($) {
  // Let's define a global function, to be called when initializing or when
  // the window resizes.
  resizeMap = function() {
    var assetImgHeight = $('.primary-asset img').height();
    $('#geotagging-map').height(assetImgHeight);
    google.maps.event.trigger(map, 'resize');
  }

  var showError = function(msg) {
    $error = $('
');
    $error.text(msg);
    $('.geotagging').append($error);
  };

  $('.call-to-action .btn').click(function() {
    $(this).hide();
    if(!window.localStorage.getItem('geotagging-overlay-closed')) {
      $('.geotagging .overlay').show();
    }
    $('.map-container').slideDown('slow', function() {
      // resize google map to match asset image on click and on window resize
      $( window ).bind('resize', resizeMap).trigger('resize');
      map.setCenter(marker.getPosition());
    });
  });

  $('.map-buttons .hide-map').click(function() {
    $('.map-container').slideUp('slow', function() {
      $('.call-to-action .btn').show();
      $( window ).unbind('resize', resizeMap);
    });
  });

  $('.overlay .close-overlay').click(function() {
    window.localStorage.setItem('geotagging-overlay-closed', true);
    $('.geotagging .overlay').hide();
  });

  $('.map-buttons .save-coordinates').click(function() {
    $(this).addClass('disabled');
    $(this).text('Gemmer placering');
    $('.map-buttons .hide-map').hide();
    var data = {
      force: location.search.indexOf('forceGeotagging') !== -1
    };
    if(map.getStreetView().getVisible()){
      data.latitude = map.getStreetView().getPosition().lat();
      data.longitude = map.getStreetView().getPosition().lng();
      data.pov = map.getStreetView().getPov();
    } else{
      data.latitude = marker.getPosition().lat();
      data.longitude = marker.getPosition().lng();
    }
    var $item = $('.item');
    var catalogAlias = $item.data('catalog-alias');
    var itemId = $item.data('item-id');
    console.log('Saving geo-tag', catalogAlias, itemId, data);
    var url = '/' + catalogAlias + '/' + itemId + '/save-geotag';
    $.ajax({
      type: 'post',
      url: url,
      data: data,
      dataType: 'json',
      success: function(response) {
        if(response.success) {
          location.reload();
        } else {
          showError('Der skete en fejl - prøv igen');
        }
      },
      error: function(response) {
        var err = response.responseJSON;
        showError(err.message || 'Der skete en uventet fejl.');
      }
    });
  });
})(jQuery);

function initMap() {
  var initialPosition = new google.maps.LatLng(55.6747, 12.5747); // The National Museums coordinates
  var address = $('#address').text();

  geocoder = new google.maps.Geocoder();

  geocoder.geocode({ 'address': address }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var geocodeLocation = results[0].geometry.location;
        var geocodeLatLng = new google.maps.LatLng(geocodeLocation.lat(), geocodeLocation.lng());

        map.setCenter(geocodeLatLng);
        marker.setPosition(geocodeLatLng);
        google.maps.event.trigger(map, 'resize');
      }
  });

  map = new google.maps.Map(document.getElementById('geotagging-map'), {
    center: initialPosition,
    zoom: 12
  });

  marker = new google.maps.Marker({
    position: initialPosition,
    map: map,
    draggable:true
  });

  google.maps.event.addListener(map, 'click', function(event) {
    marker.setPosition(event.latLng);
  });

  resizeMap();
}
<commit_msg>Added a secondary marker to the map indicating viewing direction<commit_after>var resizeMap;
var map;

(function($) {
  // Let's define a global function, to be called when initializing or when
  // the window resizes.
  resizeMap = function() {
    var assetImgHeight = $('.primary-asset img').height();
    $('#geotagging-map').height(assetImgHeight);
    var center = map.getCenter();
    google.maps.event.trigger(map, 'resize');
    map.setCenter(center);
  }

  var showError = function(msg) {
    $error = $('
');
    $error.text(msg);
    $('.geotagging').append($error);
  };

  $('.call-to-action .btn').click(function() {
    $(this).hide();
    if(!window.localStorage.getItem('geotagging-overlay-closed')) {
      $('.geotagging .overlay').show();
    }
    $('.map-container').slideDown('slow', function() {
      // resize google map to match asset image on click and on window resize
      $( window ).bind('resize', resizeMap).trigger('resize');
    });
  });

  $('.map-buttons .hide-map').click(function() {
    $('.map-container').slideUp('slow', function() {
      $('.call-to-action .btn').show();
      $( window ).unbind('resize', resizeMap);
    });
  });

  $('.overlay .close-overlay').click(function() {
    window.localStorage.setItem('geotagging-overlay-closed', true);
    $('.geotagging .overlay').hide();
  });

  $('.map-buttons .save-coordinates').click(function() {
    $(this).addClass('disabled');
    $(this).text('Gemmer placering');
    $('.map-buttons .hide-map').hide();
    var data = {
      force: location.search.indexOf('forceGeotagging') !== -1
    };
    if(map.getStreetView().getVisible()){
      data.latitude = map.getStreetView().getPosition().lat();
      data.longitude = map.getStreetView().getPosition().lng();
      data.pov = map.getStreetView().getPov();
    } else{
      data.latitude = marker.getPosition().lat();
      data.longitude = marker.getPosition().lng();
    }
    var $item = $('.item');
    var catalogAlias = $item.data('catalog-alias');
    var itemId = $item.data('item-id');
    console.log('Saving geo-tag', catalogAlias, itemId, data);
    var url = '/' + catalogAlias + '/' + itemId + '/save-geotag';
    $.ajax({
      type: 'post',
      url: url,
      data: data,
      dataType: 'json',
      success: function(response) {
        if(response.success) {
          location.reload();
        } else {
          showError('Der skete en fejl - prøv igen');
        }
      },
      error: function(response) {
        var err = response.responseJSON;
        showError(err.message || 'Der skete en uventet fejl.');
      }
    });
  });
})(jQuery);

function initMap() {
  var initialPosition = new google.maps.LatLng(55.6747, 12.5747);
  var address = $('#address').text();

  if(address){
    geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'address': address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var geocodeLocation = results[0].geometry.location;
          var geocodeLatLng = new google.maps.LatLng(geocodeLocation.lat(), geocodeLocation.lng());

          map.setCenter(geocodeLatLng);
          resizeMap();
        }
    });
  }

  map = new google.maps.Map(document.getElementById('geotagging-map'), {
    center: initialPosition,
    zoom: 16
  });

  var marker = new google.maps.Marker({
    map: map,
    draggable: true
  });

  var headingMarker = new google.maps.Marker({
    map: map,
    icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
    draggable:true
  });

  var headingLine = new google.maps.Polyline({
    map: map,
    strokeColor: '#9E0B0F'
  });

  map.addListener('click', function(event) {
    // Ensure that the relative distance between markers is the same on every zoom level
    latIncrease = 100 * Math.pow(0.5, map.getZoom());
    headingMarkerPosition = new google.maps.LatLng(event.latLng.lat() + latIncrease, event.latLng.lng());

    marker.setPosition(event.latLng);
    headingMarker.setPosition(headingMarkerPosition);
    headingLine.setPath([event.latLng, headingMarkerPosition]);
  });

  marker.addListener('drag', function(event) {
    recalculateLine();
  });

  headingMarker.addListener('drag', function(event) {
    recalculateLine();
  });

  function recalculateLine(){
    headingLine.setPath([marker.getPosition(), headingMarker.getPosition()]);
  }

  resizeMap();
}
<|endoftext|>


<commit_before>// here we store some shared functions that persons and organisations need

var d3 = require('d3');
var $ = require('jquery');
var utils = require('../utils');
var infoArea = require('./info');

var dim = {
  width: 0,
  height: 0,
  radius: 0
};

var container;

var diagonal = d3.svg.diagonal();

var innerArc = d3.svg.arc();

var activePerson = null;
var activeOrganisation = null;
var activeChapterPersons = [];
var chapterForce = d3.layout.force();

$(document).on('reset', function(){
  resetActiveOrganisation();
  resetActivePerson();
  resetActiveChapterPersons();
  infoArea.reset();

  container.selectAll('.person').style('opacity', 1);
  container.selectAll('.connection').remove();
});

var personColors = {
  euColor : '#284bdd',
  usColor : '#db2e4c',
  unknownColor : '#dddddd'
};

var orgaColors = {
  de: {
    'Europäische Kommission' : '#325a7c',
    'Öffentlicher Arbeitgeber (EU)': '#3e74a0',
    'Öffentlicher Arbeitgeber (US)': '#e9473e',
    'Privater Arbeitgeber': '#808080',
    'US-Handelsbehörde (USTR)': '#db2e4c'
  },
  en: {
    'European Commission' : '#325a7c',
    'Public Sector (EU)': '#3e74a0',
    'Public sector (US)': '#e9473e',
    'Private sector': '#808080',
    'Office of the U.S. Trade Representative (USTR)': '#db2e4c'
  }
};

function appendCircleMask(svg) {
  svg
    .append('defs')
    .append('mask')
    .attr('id', 'mask-circle')
    .append('circle')
    .attr('r', dim.radius - 70)
    .attr('cx', dim.width / 2)
    .attr('cy', dim.height / 2)
    .style('fill', '#fff');
}

function appendConnectionGroup(svg){
   svg.append('g')
    .classed('connection-group', true);
}

function appendChapterCircleGroup(svg){
   svg.append('g')
    .classed('chapter-circle-group', true);
}

function createBaseSVG(element) {
  container = element;
  var core = container.select('.viz-core');

  dim.width = parseInt(core.style('width'));
  dim.height = dim.width;
  dim.radius = Math.min(dim.width, dim.height) / 2;

  innerArc.outerRadius(dim.radius - 70)
          .innerRadius(dim.radius - 70);

  container.style('height', dim.height + 'px');

  chapterForce.size([dim.width, dim.height])
    .gravity(0.1)
    .charge(-100);

  return core
    .append('svg')
    .attr('width', dim.width)
    .attr('height', dim.height);
}

function drawConnections(svg, links) {

  container.select('.person-group')
    .selectAll('.connection')
    .data(links)
    .enter()
    .append('path')
    .classed('connection', true)
    .attr('stroke', '#ccc')
    .attr('stroke-width', 1)
    .attr('fill', 'none')
    .attr('d', diagonal);

  container.selectAll('.person').moveToFront();
}

function getLink(svg, d){

  var arcCentroid = innerArc.centroid(d),
    person = svg.select('#person-' + utils.slugify(d.data.pId)),
    personCentroid = [ parseFloat(person.attr('cx')), parseFloat(person.attr('cy'))]

  arcCentroid[0] += dim.width / 2;
  arcCentroid[1] += dim.height / 2;

  return {data: d.data, target : { x :arcCentroid[0], y : arcCentroid[1] }, source : { x : personCentroid[0], y : personCentroid[1] }};
}

function resetActiveOrganisation(){
  activeOrganisation = null;

  container.selectAll('.organisation')
    .style({
      stroke: '#fff',
      'stroke-width' : '1px'
    });
}

function resetActivePerson(){
  activePerson = null;

  container.selectAll('.person')
    .style({
      stroke: 'none'
    });
}

function resetActiveChapterPersons(){

  chapterForce.stop();

  container.selectAll('.chapter-circle')
    .remove();

  container.selectAll('.chapter-title')
    .style('display', 'none');

  container.selectAll('.chapter-person')
    .classed('chapter-person', false)
    .transition()
    .duration(400)
    .attr({
      cx : function(d){
        d.x = d.oldX;
        return d.oldX;
      },
      cy : function(d){
        d.y = d.oldY;
        return d.oldY;
      }
    });
}

// public functions
module.exports = {
  color : d3.scale.category20c(),
  appendCircleMask : appendCircleMask,
  appendConnectionGroup : appendConnectionGroup,
  appendChapterCircleGroup: appendChapterCircleGroup,
  createBaseSVG : createBaseSVG,
  drawConnections: drawConnections,
  resetActiveOrganisation: resetActiveOrganisation,
  resetActivePerson: resetActivePerson,
  getLink: getLink,
  dim: dim,
  activePerson : activePerson,
  activeOrganisation : activeOrganisation,
  activeChapterPersons : activeChapterPersons,
  resetActiveChapterPersons : resetActiveChapterPersons,
  chapterForce : chapterForce,
  personColors : personColors,
  orgaColors: orgaColors
};
<commit_msg>Fix spelling mistake to fix coloring of ec<commit_after>// here we store some shared functions that persons and organisations need

var d3 = require('d3');
var $ = require('jquery');
var utils = require('../utils');
var infoArea = require('./info');

var dim = {
  width: 0,
  height: 0,
  radius: 0
};

var container;

var diagonal = d3.svg.diagonal();

var innerArc = d3.svg.arc();

var activePerson = null;
var activeOrganisation = null;
var activeChapterPersons = [];
var chapterForce = d3.layout.force();

$(document).on('reset', function(){
  resetActiveOrganisation();
  resetActivePerson();
  resetActiveChapterPersons();
  infoArea.reset();

  container.selectAll('.person').style('opacity', 1);
  container.selectAll('.connection').remove();
});

var personColors = {
  euColor : '#284bdd',
  usColor : '#db2e4c',
  unknownColor : '#dddddd'
};

var orgaColors = {
  de: {
    'Europäische Kommission' : '#325a7c',
    'Öffentlicher Arbeitgeber (EU)': '#3e74a0',
    'Öffentlicher Arbeitgeber (US)': '#e9473e',
    'Privater Arbeitgeber': '#808080',
    'US-Handelsbehörde (USTR)': '#db2e4c'
  },
  en: {
    'European Commission' : '#325a7c',
    'Public sector (EU)': '#3e74a0',
    'Public sector (US)': '#e9473e',
    'Private sector': '#808080',
    'Office of the U.S. Trade Representative (USTR)': '#db2e4c'
  }
};

function appendCircleMask(svg) {
  svg
    .append('defs')
    .append('mask')
    .attr('id', 'mask-circle')
    .append('circle')
    .attr('r', dim.radius - 70)
    .attr('cx', dim.width / 2)
    .attr('cy', dim.height / 2)
    .style('fill', '#fff');
}

function appendConnectionGroup(svg){
   svg.append('g')
    .classed('connection-group', true);
}

function appendChapterCircleGroup(svg){
   svg.append('g')
    .classed('chapter-circle-group', true);
}

function createBaseSVG(element) {
  container = element;
  var core = container.select('.viz-core');

  dim.width = parseInt(core.style('width'));
  dim.height = dim.width;
  dim.radius = Math.min(dim.width, dim.height) / 2;

  innerArc.outerRadius(dim.radius - 70)
          .innerRadius(dim.radius - 70);

  container.style('height', dim.height + 'px');

  chapterForce.size([dim.width, dim.height])
    .gravity(0.1)
    .charge(-100);

  return core
    .append('svg')
    .attr('width', dim.width)
    .attr('height', dim.height);
}

function drawConnections(svg, links) {

  container.select('.person-group')
    .selectAll('.connection')
    .data(links)
    .enter()
    .append('path')
    .classed('connection', true)
    .attr('stroke', '#ccc')
    .attr('stroke-width', 1)
    .attr('fill', 'none')
    .attr('d', diagonal);

  container.selectAll('.person').moveToFront();
}

function getLink(svg, d){

  var arcCentroid = innerArc.centroid(d),
    person = svg.select('#person-' + utils.slugify(d.data.pId)),
    personCentroid = [ parseFloat(person.attr('cx')), parseFloat(person.attr('cy'))]

  arcCentroid[0] += dim.width / 2;
  arcCentroid[1] += dim.height / 2;

  return {data: d.data, target : { x :arcCentroid[0], y : arcCentroid[1] }, source : { x : personCentroid[0], y : personCentroid[1] }};
}

function resetActiveOrganisation(){
  activeOrganisation = null;

  container.selectAll('.organisation')
    .style({
      stroke: '#fff',
      'stroke-width' : '1px'
    });
}

function resetActivePerson(){
  activePerson = null;

  container.selectAll('.person')
    .style({
      stroke: 'none'
    });
}

function resetActiveChapterPersons(){

  chapterForce.stop();

  container.selectAll('.chapter-circle')
    .remove();

  container.selectAll('.chapter-title')
    .style('display', 'none');

  container.selectAll('.chapter-person')
    .classed('chapter-person', false)
    .transition()
    .duration(400)
    .attr({
      cx : function(d){
        d.x = d.oldX;
        return d.oldX;
      },
      cy : function(d){
        d.y = d.oldY;
        return d.oldY;
      }
    });
}

// public functions
module.exports = {
  color : d3.scale.category20c(),
  appendCircleMask : appendCircleMask,
  appendConnectionGroup : appendConnectionGroup,
  appendChapterCircleGroup: appendChapterCircleGroup,
  createBaseSVG : createBaseSVG,
  drawConnections: drawConnections,
  resetActiveOrganisation: resetActiveOrganisation,
  resetActivePerson: resetActivePerson,
  getLink: getLink,
  dim: dim,
  activePerson : activePerson,
  activeOrganisation : activeOrganisation,
  activeChapterPersons : activeChapterPersons,
  resetActiveChapterPersons : resetActiveChapterPersons,
  chapterForce : chapterForce,
  personColors : personColors,
  orgaColors: orgaColors
};
<|endoftext|>


<commit_before>import { default as React, Component } from 'react';
import { ItemCheckboxList } from './component/ItemCheckboxList.js';
import { NestedItem } from './component/NestedItem.js';
import classNames from 'classnames';
import { manager } from '../middleware/ChannelManager.js';
import { StaticSearch } from './component/StaticSearch.js';
var helper = require('../middleware/helper.js');
var _ = require('lodash');

export class NestedList extends Component {
	constructor(props, context) {
		super(props);
		this.state = {
			items: [],
			storedItems: [],
			rawData: {
				hits: {
					hits: []
				}
			},
			subItems: [],
			selectedValues: []
		};
		this.channelId = null;
		this.channelListener = null;
		this.defaultSelected = this.props.defaultSelected;
		this.filterBySearch = this.filterBySearch.bind(this);
		this.onItemSelect = this.onItemSelect.bind(this);
		this.defaultQuery = this.defaultQuery.bind(this);
		this.handleSelect = this.handleSelect.bind(this);
		this.type = this.props.multipleSelect ? 'Terms' : 'Term';
	}

	// Get the items from Appbase when component is mounted
	componentWillMount() {
		this.setQueryInfo();
		this.createChannel();
		this.createSubChannel();
	}

	componentDidMount() {
		if(this.props.defaultSelected) {
			this.setValue('', false);
			setTimeout(() => {
				this.handleSelect();
			}, 2000);
		}
	}

	handleSelect() {
		if(this.props.defaultSelected) {
			this.props.defaultSelected.forEach((value, index) => {
				console.log(value, index);
				this.onItemSelect(value, index);
			})
		}
	}

	componentWillUpdate() {
		setTimeout(() => {
			if (!_.isEqual(this.defaultSelected, this.props.defaultSelected)) {
				this.defaultSelected = this.props.defaultSelected;
				let items = this.state.items;
				items = items.map((item) => {
					item.key = item.key.toString();
					item.status = this.defaultSelected.length && this.defaultSelected.indexOf(item.key) > -1 ? true : false;
					return item;
				});
				this.setState({
					items: items,
					storedItems: items
				});
				this.handleSelect(this.defaultSelected);
			}
		}, 300);
	}

	// stop streaming request and remove listener when component will unmount
	componentWillUnmount() {
		if(this.channelId) {
			manager.stopStream(this.channelId);
		}
		if(this.subChannelId) {
			manager.stopStream(this.subChannelId);
		}
		if(this.channelListener) {
			this.channelListener.remove();
		}
		if(this.subChannelListener) {
			this.subChannelListener.remove();
		}
	}

	// build query for this sensor only
	defaultQuery(record) {
		if(record) {
			let query = {
				bool: {
					must: generateRangeQuery(this.props.appbaseField)
				}
			};
			return query;
		}
		function generateRangeQuery(appbaseField) {
			return record.map((singleRecord, index) => {
				return {
					term: {
						[appbaseField[index]]: singleRecord
					}
				};
			});
		}
	}

	// set the query type and input data
	setQueryInfo() {
		var obj = {
				key: this.props.sensorId,
				value: {
					queryType: this.type,
					inputData: this.props.appbaseField[0],
					defaultQuery: this.defaultQuery
				}
		};
		helper.selectedSensor.setSensorInfo(obj);
	}

	// Create a channel which passes the depends and receive results whenever depends changes
	createChannel() {
		// Set the depends - add self aggs query as well with depends
		let depends = this.props.depends ? this.props.depends : {};
		depends['aggs'] = {
			key: this.props.appbaseField[0],
			sort: this.props.sortBy,
			size: this.props.size
		};
		// create a channel and listen the changes
		var channelObj = manager.create(this.context.appbaseRef, this.context.type, depends);
		this.channelId = channelObj.channelId;
		this.channelListener = channelObj.emitter.addListener(this.channelId, function(res) {
			let data = res.data;
			let rawData;
			if(res.mode === 'streaming') {
				rawData = this.state.rawData;
				rawData.hits.hits.push(res.data);
			} else if(res.mode === 'historic') {
				rawData = data;
			}
			this.setState({
				rawData: rawData
			});
			this.setData(rawData, 0);
		}.bind(this));
	}

	// Create a channel for sub category
	createSubChannel() {
		this.setSubCategory();
		let depends = {
			'aggs': {
				key: this.props.appbaseField[1],
				sort: this.props.sortBy,
				size: this.props.size
			},
			'subCategory': { operation: "must" }
		};
		// create a channel and listen the changes
		var subChannelObj = manager.create(this.context.appbaseRef, this.context.type, depends);
		this.subChannelId = subChannelObj.channelId;
		this.subChannelListener = subChannelObj.emitter.addListener(this.subChannelId, function(res) {
			let data = res.data;
			let rawData;
			if(res.mode === 'streaming') {
				rawData = this.state.subRawData;
				rawData.hits.hits.push(res.data);
			} else if(res.mode === 'historic') {
				rawData = data;
			}
			if(this.state.selectedValues.length) {
				this.setState({
					subRawData: rawData
				});
				this.setData(rawData, 1);
			}
		}.bind(this));
		var obj = {
			key: 'subCategory',
			value: ''
		};
		helper.selectedSensor.set(obj, true);
	}

	// set the query type and input data
	setSubCategory() {
		var obj = {
				key: 'subCategory',
				value: {
					queryType: 'term',
					inputData: this.props.appbaseField[0]
				}
		};

		helper.selectedSensor.setSensorInfo(obj);
	}

	setData(data, level) {
		if(data.aggregations && data.aggregations[this.props.appbaseField[level]] && data.aggregations[this.props.appbaseField[level]].buckets) {
			this.addItemsToList(data.aggregations[this.props.appbaseField[level]].buckets, level);
		}
	}

	addItemsToList(newItems, level) {
		newItems = newItems.map((item) => {
			item.key = item.key.toString();
			item.status = this.defaultSelected && this.defaultSelected.indexOf(item.key) > -1 ? true : false;
			return item
		});
		let itemVar = level === 0 ? 'items' : 'subItems';
		this.setState({
			[itemVar]: newItems,
			storedItems: newItems
		});
	}

	// set value
	setValue(value, isExecuteQuery=false) {
		var obj = {
			key: this.props.sensorId,
			value: value
		};
		helper.selectedSensor.set(obj, isExecuteQuery);
	}

	// filter
	filterBySearch(value) {
		if(value) {
			let items = this.state.storedItems.filter(function(item) {
				return item.key && item.key.toLowerCase().indexOf(value.toLowerCase()) > -1;
			});
			this.setState({
				items: items
			});
		} else {
			this.setState({
				items: this.state.storedItems
			});
		}
	}

	onItemSelect(key, level) {
		let selectedValues = this.state.selectedValues;
		let stateItems = {};
		if (selectedValues[level] == key && this.defaultSelected.length == 1) {
			delete selectedValues[level];
			stateItems = {
				selectedValues: selectedValues
			};
		} else {
			selectedValues[level] = key;
			stateItems = {
				selectedValues: selectedValues
			};
			if(level === 0) {
				selectedValues.splice(1, 1);
				if(key !== selectedValues[0]) {
					stateItems.subItems = [];
				}
				var obj = {
					key: 'subCategory',
					value: key
				};
				helper.selectedSensor.set(obj, true);
			}
		}
		this.setValue(selectedValues, true);
		this.setState(stateItems);
	}

	renderChevron(level) {
		return level === 0 ? () : '' ;
	}

	renderItems(items, level) {
		return items.map((item, index) => {
			let cx = classNames({
				'rbc-item-active': (item.key === this.state.selectedValues[level]),
				'rbc-item-inactive': !(item.key === this.state.selectedValues[level])
			});
			return (

					<a href="javascript:void(0);" className={`rbc-list-item ${cx}`} onClick={() => this.onItemSelect(item.key, level)}>
						 {item.key}
						 {item.doc_count}
						{this.renderChevron(level)}

					{this.renderList(item.key, level)}

			);
		});
	}

	renderList(key, level) {
		let list;
		if(key === this.state.selectedValues[level] && level === 0) {
			list = (

					{this.renderItems(this.state.subItems, 1)}

			)
		}
		return list;
	}

	render() {
		let listComponent,
			searchComponent = null,
			title = null;

		listComponent = (

				{this.renderItems(this.state.items, 0)}

		);

		// set static search
		if(this.props.showSearch) {
			searchComponent = <StaticSearch
				placeholder={this.props.searchPlaceholder}
				changeCallback={this.filterBySearch}
			/>
		}

		if(this.props.title) {
			title = (
{this.props.title}
);
		}

		let cx = classNames({
			'rbc-search-active': this.props.showSearch,
			'rbc-search-inactive': !this.props.showSearch,
			'rbc-title-active': this.props.title,
			'rbc-title-inactive': !this.props.title
		});

		return (
			<div className={`rbc rbc-nestedlist col s12 col-xs-12 card thumbnail ${cx}`}>
				{title}
				{searchComponent}
				{listComponent}

		);
	}
}

NestedList.propTypes = {
	appbaseField: React.PropTypes.array.isRequired,
	defaultQuery: React.PropTypes.func,
	size: React.PropTypes.number,
	showCount: React.PropTypes.bool,
	multipleSelect: React.PropTypes.bool,
	sortBy: React.PropTypes.string,
	includeSelectAll: React.PropTypes.bool
};

// Default props value
NestedList.defaultProps = {
	showCount: true,
	multipleSelect: false,
	sortBy: 'count',
	size: 100,
	showSearch: false,
	title: null,
	searchPlaceholder: 'Search',
	includeSelectAll: false
};

// context type
NestedList.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired
};
<commit_msg>minor fix<commit_after>import { default as React, Component } from 'react';
import { ItemCheckboxList } from './component/ItemCheckboxList.js';
import { NestedItem } from './component/NestedItem.js';
import classNames from 'classnames';
import { manager } from '../middleware/ChannelManager.js';
import { StaticSearch } from './component/StaticSearch.js';
var helper = require('../middleware/helper.js');
var _ = require('lodash');

export class NestedList extends Component {
	constructor(props, context) {
		super(props);
		this.state = {
			items: [],
			storedItems: [],
			rawData: {
				hits: {
					hits: []
				}
			},
			subItems: [],
			selectedValues: []
		};
		this.channelId = null;
		this.channelListener = null;
		this.defaultSelected = this.props.defaultSelected;
		this.filterBySearch = this.filterBySearch.bind(this);
		this.onItemSelect = this.onItemSelect.bind(this);
		this.defaultQuery = this.defaultQuery.bind(this);
		this.handleSelect = this.handleSelect.bind(this);
		this.type = this.props.multipleSelect ? 'Terms' : 'Term';
	}

	// Get the items from Appbase when component is mounted
	componentWillMount() {
		this.setQueryInfo();
		this.createChannel();
		this.createSubChannel();
	}

	componentDidMount() {
		if(this.props.defaultSelected) {
			this.setValue('', false);
			setTimeout(() => {
				this.handleSelect();
			}, 2000);
		}
	}

	handleSelect() {
		if(this.props.defaultSelected) {
			this.props.defaultSelected.forEach((value, index) => {
				this.onItemSelect(value, index);
			})
		}
	}

	componentWillUpdate() {
		setTimeout(() => {
			if (!_.isEqual(this.defaultSelected, this.props.defaultSelected)) {
				this.defaultSelected = this.props.defaultSelected;
				let items = this.state.items;
				items = items.map((item) => {
					item.key = item.key.toString();
					item.status = this.defaultSelected.length && this.defaultSelected.indexOf(item.key) > -1 ? true : false;
					return item;
				});
				this.setState({
					items: items,
					storedItems: items
				});
				this.handleSelect(this.defaultSelected);
			}
		}, 300);
	}

	// stop streaming request and remove listener when component will unmount
	componentWillUnmount() {
		if(this.channelId) {
			manager.stopStream(this.channelId);
		}
		if(this.subChannelId) {
			manager.stopStream(this.subChannelId);
		}
		if(this.channelListener) {
			this.channelListener.remove();
		}
		if(this.subChannelListener) {
			this.subChannelListener.remove();
		}
	}

	// build query for this sensor only
	defaultQuery(record) {
		if(record) {
			let query = {
				bool: {
					must: generateRangeQuery(this.props.appbaseField)
				}
			};
			return query;
		}
		function generateRangeQuery(appbaseField) {
			return record.map((singleRecord, index) => {
				return {
					term: {
						[appbaseField[index]]: singleRecord
					}
				};
			});
		}
	}

	// set the query type and input data
	setQueryInfo() {
		var obj = {
				key: this.props.sensorId,
				value: {
					queryType: this.type,
					inputData: this.props.appbaseField[0],
					defaultQuery: this.defaultQuery
				}
		};
		helper.selectedSensor.setSensorInfo(obj);
	}

	// Create a channel which passes the depends and receive results whenever depends changes
	createChannel() {
		// Set the depends - add self aggs query as well with depends
		let depends = this.props.depends ? this.props.depends : {};
		depends['aggs'] = {
			key: this.props.appbaseField[0],
			sort: this.props.sortBy,
			size: this.props.size
		};
		// create a channel and listen the changes
		var channelObj = manager.create(this.context.appbaseRef, this.context.type, depends);
		this.channelId = channelObj.channelId;
		this.channelListener = channelObj.emitter.addListener(this.channelId, function(res) {
			let data = res.data;
			let rawData;
			if(res.mode === 'streaming') {
				rawData = this.state.rawData;
				rawData.hits.hits.push(res.data);
			} else if(res.mode === 'historic') {
				rawData = data;
			}
			this.setState({
				rawData: rawData
			});
			this.setData(rawData, 0);
		}.bind(this));
	}

	// Create a channel for sub category
	createSubChannel() {
		this.setSubCategory();
		let depends = {
			'aggs': {
				key: this.props.appbaseField[1],
				sort: this.props.sortBy,
				size: this.props.size
			},
			'subCategory': { operation: "must" }
		};
		// create a channel and listen the changes
		var subChannelObj = manager.create(this.context.appbaseRef, this.context.type, depends);
		this.subChannelId = subChannelObj.channelId;
		this.subChannelListener = subChannelObj.emitter.addListener(this.subChannelId, function(res) {
			let data = res.data;
			let rawData;
			if(res.mode === 'streaming') {
				rawData = this.state.subRawData;
				rawData.hits.hits.push(res.data);
			} else if(res.mode === 'historic') {
				rawData = data;
			}
			if(this.state.selectedValues.length) {
				this.setState({
					subRawData: rawData
				});
				this.setData(rawData, 1);
			}
		}.bind(this));
		var obj = {
			key: 'subCategory',
			value: ''
		};
		helper.selectedSensor.set(obj, true);
	}

	// set the query type and input data
	setSubCategory() {
		var obj = {
				key: 'subCategory',
				value: {
					queryType: 'term',
					inputData: this.props.appbaseField[0]
				}
		};

		helper.selectedSensor.setSensorInfo(obj);
	}

	setData(data, level) {
		if(data.aggregations && data.aggregations[this.props.appbaseField[level]] && data.aggregations[this.props.appbaseField[level]].buckets) {
			this.addItemsToList(data.aggregations[this.props.appbaseField[level]].buckets, level);
		}
	}

	addItemsToList(newItems, level) {
		newItems = newItems.map((item) => {
			item.key = item.key.toString();
			item.status = this.defaultSelected && this.defaultSelected.indexOf(item.key) > -1 ? true : false;
			return item
		});
		let itemVar = level === 0 ? 'items' : 'subItems';
		this.setState({
			[itemVar]: newItems,
			storedItems: newItems
		});
	}

	// set value
	setValue(value, isExecuteQuery=false) {
		var obj = {
			key: this.props.sensorId,
			value: value
		};
		helper.selectedSensor.set(obj, isExecuteQuery);
	}

	// filter
	filterBySearch(value) {
		if(value) {
			let items = this.state.storedItems.filter(function(item) {
				return item.key && item.key.toLowerCase().indexOf(value.toLowerCase()) > -1;
			});
			this.setState({
				items: items
			});
		} else {
			this.setState({
				items: this.state.storedItems
			});
		}
	}

	onItemSelect(key, level) {
		let selectedValues = this.state.selectedValues;
		let stateItems = {};
		if (selectedValues[level] == key && this.defaultSelected.length == 1) {
			delete selectedValues[level];
			stateItems = {
				selectedValues: selectedValues
			};
		} else {
			selectedValues[level] = key;
			stateItems = {
				selectedValues: selectedValues
			};
			if(level === 0) {
				selectedValues.splice(1, 1);
				if(key !== selectedValues[0]) {
					stateItems.subItems = [];
				}
				var obj = {
					key: 'subCategory',
					value: key
				};
				helper.selectedSensor.set(obj, true);
			}
		}
		this.setValue(selectedValues, true);
		this.setState(stateItems);
	}

	renderChevron(level) {
		return level === 0 ? () : '' ;
	}

	renderItems(items, level) {
		return items.map((item, index) => {
			let cx = classNames({
				'rbc-item-active': (item.key === this.state.selectedValues[level]),
				'rbc-item-inactive': !(item.key === this.state.selectedValues[level])
			});
			return (

					<a href="javascript:void(0);" className={`rbc-list-item ${cx}`} onClick={() => this.onItemSelect(item.key, level)}>
						 {item.key}
						 {item.doc_count}
						{this.renderChevron(level)}

					{this.renderList(item.key, level)}

			);
		});
	}

	renderList(key, level) {
		let list;
		if(key === this.state.selectedValues[level] && level === 0) {
			list = (

					{this.renderItems(this.state.subItems, 1)}

			)
		}
		return list;
	}

	render() {
		let listComponent,
			searchComponent = null,
			title = null;

		listComponent = (

				{this.renderItems(this.state.items, 0)}

		);

		// set static search
		if(this.props.showSearch) {
			searchComponent = <StaticSearch
				placeholder={this.props.searchPlaceholder}
				changeCallback={this.filterBySearch}
			/>
		}

		if(this.props.title) {
			title = (
{this.props.title}
);
		}

		let cx = classNames({
			'rbc-search-active': this.props.showSearch,
			'rbc-search-inactive': !this.props.showSearch,
			'rbc-title-active': this.props.title,
			'rbc-title-inactive': !this.props.title
		});

		return (
			<div className={`rbc rbc-nestedlist col s12 col-xs-12 card thumbnail ${cx}`}>
				{title}
				{searchComponent}
				{listComponent}

		);
	}
}

NestedList.propTypes = {
	appbaseField: React.PropTypes.array.isRequired,
	defaultQuery: React.PropTypes.func,
	size: React.PropTypes.number,
	showCount: React.PropTypes.bool,
	multipleSelect: React.PropTypes.bool,
	sortBy: React.PropTypes.string,
	includeSelectAll: React.PropTypes.bool
};

// Default props value
NestedList.defaultProps = {
	showCount: true,
	multipleSelect: false,
	sortBy: 'count',
	size: 100,
	showSearch: false,
	title: null,
	searchPlaceholder: 'Search',
	includeSelectAll: false
};

// context type
NestedList.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired
};
<|endoftext|>


<commit_before>import Ember from 'ember';
/* global jsSHA */
/* global Identicon */

/**
 * @classdesc Description
 * @extends Ember.Service
 */
export default Ember.Service.extend({
    create: function(hash, options) {
        options || (options = {});
        var raw = new jsSHA('SHA-1', 'TEXT');
        raw.update(hash);

        var updatedHash = raw.getHash('HEX'),
            data = new Identicon(updatedHash, options.size || 420, options.margin || .1, options).toString();

        return 'data:image/png;base64,' + data;
    }
});<commit_msg>Fix background colour with new identicon.js<commit_after>import Ember from 'ember';
/* global jsSHA */
/* global Identicon */

/**
 * @classdesc Description
 * @extends Ember.Service
 */
export default Ember.Service.extend({
    create: function(hash, options) {
        options || (options = {});
        var raw = new jsSHA('SHA-1', 'TEXT');
        raw.update(hash);

        options.size = options.size || 420;
        options.margin = options.margin || 0.1;
        // Backwards compatibility
        options.background = options.background || options.bgColors;

        var updatedHash = raw.getHash('HEX'),
            data = new Identicon(updatedHash, options).toString();

        return 'data:image/png;base64,' + data;
    }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';
import { pluralize } from 'ember-inflector';

const { inject, Service, RSVP, computed } = Ember;
const { PromiseArray } = DS;
const { service } = inject;

export default Service.extend({
  store: service(),
  currentUser: service(),
  reportsList: computed('currentUser.model.reports.[]', function(){
    let defer = RSVP.defer();
    this.get('currentUser').get('model').then( user => {
      user.get('reports').then( reports => {
        defer.resolve(reports);
      });
    });
    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  getResults(report){
    const subject = report.get('subject');
    const object = report.get('prepositionalObject');
    const objectId = report.get('prepositionalObjectTableRowId');
    let defer = RSVP.defer();
    report.get('school').then(school => {
      this.get('store').query(
        this.getModel(subject),
        this.getQuery(subject, object, objectId, school)
      ).then(results => {
        let mapper = pluralize(subject.camelize()) + 'Results';
        this[mapper](results).then(mappedResults => {
          defer.resolve(mappedResults.sortBy('value'));
        });
      });
    });
    return DS.PromiseArray.create({
      promise: defer.promise
    });
  },
  getModel(subject){
    let model = subject.dasherize();
    if(model === 'instructor'){
      model = 'user';
    }
    if(model === 'mesh-term'){
      model = 'mesh-descriptor';
    }

    return model;
  },
  getQuery(subject, object, objectId, school){
    let query = {
      limit: 1000,
      filters: {}
    };

    if(object && objectId){
      let what = pluralize(object.camelize());
      if(object === 'mesh term'){
        what = 'meshDescriptors';
      }
      if(subject = 'session' && object === 'session type'){
        what = 'sessionType';
      }
      query.filters[what] = objectId;
    } else {
      if(subject !== 'mesh term' && subject !== 'instructor' && subject !== 'learning material' && school){
        query.filters['schools'] = [school.get('id')];
      }
    }

    return query;
  },
  coursesResults(results){
    const canViewCourses = this.get('currentUser.canViewCourses');
    let map = results.map(course => {
      let rhett = {};
      rhett.value = course.get('academicYear') + ' ' + course.get('title');
      if(canViewCourses){
        rhett.route = 'course';
        rhett.model = course;
      }

      return rhett;
    });

    return RSVP.resolve(map);
  },
  sessionsResults(results){
    const canView = this.get('currentUser.canViewCourses');
    let map = results.map(item => {
      return new RSVP.Promise(resolve => {
        let rhett = {};
        item.get('course').then(course => {
          rhett.value = course.get('academicYear') + ' ' + course.get('title') + ' ' + item.get('title');
          if(canView){
            rhett.route = 'session';
            rhett.model = course;
            rhett.model2 = item;
          }
          resolve(rhett);
        });
      });
    });

    return RSVP.all(map);
  },
  programsResults(results){
    const canView = this.get('currentUser.canViewPrograms');
    let map = results.map(item => {
      return new RSVP.Promise(resolve => {
        let rhett = {};
        item.get('school').then(school => {
          rhett.value = school.get('title') + ': ' + item.get('title');
          if(canView){
            rhett.route = 'program';
            rhett.model = item;
          }
          resolve(rhett);
        });
      });
    });

    return RSVP.all(map);
  },
  programYearsResults(results){
    const canView = this.get('currentUser.canViewPrograms');
    let map = results.map(item => {
      return new RSVP.Promise(resolve => {
        let rhett = {};
        item.get('program').then(program => {
          program.get('school').then(school => {
            rhett.value = school.get('title') + ' ' + program.get('title') + ' ' + item.get('classOfYear');
            if(canView){
              rhett.route = 'programYear';
              rhett.model = program;
              rhett.model2 = item;
            }
            resolve(rhett);
          });
        });

      });
    });

    return RSVP.all(map);
  },
  instructorsResults(results){
    let map = results.map( result => {
      return {
        value: result.get('fullName')
      };
    });
    return RSVP.resolve(map);
  },
  titleResults(results){
    let map = results.map( result => {
      return {
        value: result.get('title')
      };
    });
    return RSVP.resolve(map);
  },
  instructorGroupsResults(results){
    return this.titleResults(results);
  },
  learningMaterialsResults(results){
    return this.titleResults(results);
  },
  competenciesResults(results){
    return this.titleResults(results);
  },
  topicsResults(results){
    return this.titleResults(results);
  },
  settionTypesResults(results){
    return this.titleResults(results);
  },
  meshTermsResults(results){
    let map = results.map( result => {
      return {
        value: result.get('name')
      };
    });
    return RSVP.resolve(map);
  }
});
<commit_msg>Fix sessionType reporting results<commit_after>import Ember from 'ember';
import DS from 'ember-data';
import { pluralize } from 'ember-inflector';

const { inject, Service, RSVP, computed } = Ember;
const { PromiseArray } = DS;
const { service } = inject;

export default Service.extend({
  store: service(),
  currentUser: service(),
  reportsList: computed('currentUser.model.reports.[]', function(){
    let defer = RSVP.defer();
    this.get('currentUser').get('model').then( user => {
      user.get('reports').then( reports => {
        defer.resolve(reports);
      });
    });
    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  getResults(report){
    const subject = report.get('subject');
    const object = report.get('prepositionalObject');
    const objectId = report.get('prepositionalObjectTableRowId');
    let defer = RSVP.defer();
    report.get('school').then(school => {
      this.get('store').query(
        this.getModel(subject),
        this.getQuery(subject, object, objectId, school)
      ).then(results => {
        let mapper = pluralize(subject.camelize()) + 'Results';
        this[mapper](results).then(mappedResults => {
          defer.resolve(mappedResults.sortBy('value'));
        });
      });
    });
    return DS.PromiseArray.create({
      promise: defer.promise
    });
  },
  getModel(subject){
    let model = subject.dasherize();
    if(model === 'instructor'){
      model = 'user';
    }
    if(model === 'mesh-term'){
      model = 'mesh-descriptor';
    }

    return model;
  },
  getQuery(subject, object, objectId, school){
    let query = {
      limit: 1000,
      filters: {}
    };

    if(object && objectId){
      let what = pluralize(object.camelize());
      if(object === 'mesh term'){
        what = 'meshDescriptors';
      }
      if(subject = 'session' && object === 'session type'){
        what = 'sessionType';
      }
      query.filters[what] = objectId;
    } else {
      if(subject !== 'mesh term' && subject !== 'instructor' && subject !== 'learning material' && school){
        query.filters['schools'] = [school.get('id')];
      }
    }

    return query;
  },
  coursesResults(results){
    const canViewCourses = this.get('currentUser.canViewCourses');
    let map = results.map(course => {
      let rhett = {};
      rhett.value = course.get('academicYear') + ' ' + course.get('title');
      if(canViewCourses){
        rhett.route = 'course';
        rhett.model = course;
      }

      return rhett;
    });

    return RSVP.resolve(map);
  },
  sessionsResults(results){
    const canView = this.get('currentUser.canViewCourses');
    let map = results.map(item => {
      return new RSVP.Promise(resolve => {
        let rhett = {};
        item.get('course').then(course => {
          rhett.value = course.get('academicYear') + ' ' + course.get('title') + ' ' + item.get('title');
          if(canView){
            rhett.route = 'session';
            rhett.model = course;
            rhett.model2 = item;
          }
          resolve(rhett);
        });
      });
    });

    return RSVP.all(map);
  },
  programsResults(results){
    const canView = this.get('currentUser.canViewPrograms');
    let map = results.map(item => {
      return new RSVP.Promise(resolve => {
        let rhett = {};
        item.get('school').then(school => {
          rhett.value = school.get('title') + ': ' + item.get('title');
          if(canView){
            rhett.route = 'program';
            rhett.model = item;
          }
          resolve(rhett);
        });
      });
    });

    return RSVP.all(map);
  },
  programYearsResults(results){
    const canView = this.get('currentUser.canViewPrograms');
    let map = results.map(item => {
      return new RSVP.Promise(resolve => {
        let rhett = {};
        item.get('program').then(program => {
          program.get('school').then(school => {
            rhett.value = school.get('title') + ' ' + program.get('title') + ' ' + item.get('classOfYear');
            if(canView){
              rhett.route = 'programYear';
              rhett.model = program;
              rhett.model2 = item;
            }
            resolve(rhett);
          });
        });

      });
    });

    return RSVP.all(map);
  },
  instructorsResults(results){
    let map = results.map( result => {
      return {
        value: result.get('fullName')
      };
    });
    return RSVP.resolve(map);
  },
  titleResults(results){
    let map = results.map( result => {
      return {
        value: result.get('title')
      };
    });
    return RSVP.resolve(map);
  },
  instructorGroupsResults(results){
    return this.titleResults(results);
  },
  learningMaterialsResults(results){
    return this.titleResults(results);
  },
  competenciesResults(results){
    return this.titleResults(results);
  },
  topicsResults(results){
    return this.titleResults(results);
  },
  sessionTypesResults(results){
    return this.titleResults(results);
  },
  meshTermsResults(results){
    let map = results.map( result => {
      return {
        value: result.get('name')
      };
    });
    return RSVP.resolve(map);
  }
});
<|endoftext|>


<commit_before>let index = 0;
var interval = 7000;

let chatsEl = $('.chats');

function getChatHTML(chat) {
    let bubbleHTML = ``;
    for (let i = 0; i < chat.dialog.length; i++) {
        let bubble = chat.dialog[i];
        let userClass = 'me'
        if (bubble.user === 'student') {
            userClass = 'student';
        }
        bubbleHTML += `

                                ${bubble.text}

`;

    }
    return bubbleHTML;
}

function changeScreen() {
    if (index > chats.length - 1) {
        index = 0;
    }
    if (chatsEl.html() !== '') {
        chatsEl.addClass('animated bounceOutUp');
        setTimeout(function () {
            chatsEl.html(getChatHTML(chats[index]));
            chatsEl.removeClass('animated bounceOutUp').addClass('animated bounceInUp');
            index++;
        }, 2000);

    } else {
        chatsEl.html(getChatHTML(chats[index]));
        chatsEl.removeClass('animated bounceOutUp').addClass('animated bounceInUp');
        index++;
    }

}

function start(interval) {
    intervalId = setInterval(function () {
        changeScreen();
    }, interval);
}

function getInterval() {
    return interval;
}

//kickoff
$.getJSON('json/chats.json', function (data) {
    chats = data.chats;
    start(interval);
    changeScreen();
});<commit_msg>Lengthened interval<commit_after>let index = 0;
var interval = 15000;

let chatsEl = $('.chats');

function getChatHTML(chat) {
    let bubbleHTML = ``;
    for (let i = 0; i < chat.dialog.length; i++) {
        let bubble = chat.dialog[i];
        let userClass = 'me'
        if (bubble.user === 'student') {
            userClass = 'student';
        }
        bubbleHTML += `

                                ${bubble.text}

`;

    }
    return bubbleHTML;
}

function changeScreen() {
    if (index > chats.length - 1) {
        index = 0;
    }
    if (chatsEl.html() !== '') {
        chatsEl.addClass('animated bounceOutUp');
        setTimeout(function () {
            chatsEl.html(getChatHTML(chats[index]));
            chatsEl.removeClass('animated bounceOutUp').addClass('animated bounceInUp');
            index++;
        }, 2000);

    } else {
        chatsEl.html(getChatHTML(chats[index]));
        chatsEl.removeClass('animated bounceOutUp').addClass('animated bounceInUp');
        index++;
    }

}

function start(interval) {
    intervalId = setInterval(function () {
        changeScreen();
    }, interval);
}

function getInterval() {
    return interval;
}

//kickoff
$.getJSON('json/chats.json', function (data) {
    chats = data.chats;
    start(interval);
    changeScreen();
});<|endoftext|>


<commit_before>/**
 * Main mixin for the Bolt module.
 *
 * @mixin
 * @namespace Bolt.app
 *
 * @param {Object} bolt - The Bolt module.
 * @param {Object} $ - jQuery.
 */
(function (bolt, $) {
    /**
     * Bolt.app mixin container.
     *
     * @private
     * @type {Object}
     */
    var app = {};

    /**
     * Loading state of Google Maps API.
     *
     * @private
     * @type {boolean|undefined} Values: undefined: initial state; false: pending; true: loaded.
     */
    var gMapsApiLoaded;

    /**
     * Callback that signals that Google Maps API is fully loaded.
     *
     * See: https://developers.google.com/maps/documentation/javascript/tutorial#asynch
     *
     * @function gMapsApiReady
     * @memberof Bolt.app
     */
    app.gMapsApiReady = function () {
        gMapsApiLoaded = true;
        $(bolt).trigger('bolt:gmaps-loaded');
    };

    /**
     * Initializes and then starts the Bolt module.
     * Is automatically executed on jQueries ``$(document).ready()``.
     *
     * @function run
     * @memberof Bolt.app
     */
    app.run = function () {
        initGlobal();

        bolt.conf.init();
        bolt.data.init();

        initHandler();

        bolt.actions.init();
        bolt.secmenu.init();
        bolt.stack.init();
        bolt.omnisearch.init();

        bolt.activity.init();
        bolt.ckeditor.init();
        bolt.datetime.init();

        legacyInit();
        initBuic();
        initFields();
    };

    /*
     * Start when ready.
     */
    $(document).ready(app.run);

    /**
     * Legacy stuff from start.js.
     *
     * @private
     * @static
     * @function legacyInit
     * @memberof Bolt.app
     * @todo Move functionality to Bolt mixins.
     * @deprecated To be removed!
     */
    function legacyInit() {
        // Get passed in data from Twig function data()

        // Initialize objects
        bolt.moments = new Moments();
        bolt.imagelist = [];
        bolt.filelist = [];

        // Initialisation
        init.confirmationDialogs();
        init.magnificPopup();
        init.dropZone();
        init.popOvers();
        init.dropDowns();
        init.deferredWidgets();
        init.passwordInput();
        init.dashboardCheckboxes();
        init.sortables();
        init.uploads();
        init.focusStatusSelect();
        init.depublishTracking();

        $('[data-bind]').each(function () {
            var data = $(this).data('bind');
            //console.log('Binding: ' + data.bind);

            switch (data.bind) {
                case 'editcontent': bolt.editcontent.init(data); break;
                case 'editfile': init.bindEditFile(data); break;
                case 'editlocale': init.bindEditLocale(data); break;
                case 'filebrowser': init.bindFileBrowser(); break;
                case 'ckfileselect': init.bindCkFileSelect(); break;
                case 'prefill': init.bindPrefill(); break;
                case 'video': bolt.video.bind(data.key); break;
                default: console.log('Binding ' + data.bind + ' failed!');
            }
        });
    }

    /**
     * Initializes Bolts event handler.
     *
     * @private
     * @static
     * @function initHandler
     * @memberof Bolt.app
     */
    function initHandler() {
        $(bolt)
            // Google Maps API loading
            // - bolt:gmaps-load:   request API loading.
            // - bolt:gmaps-loaded: API loaded successfully.
            // - bolt:gmaps-failed: loading failed.
            .on('bolt:gmaps-load', function (e) {
                if (gMapsApiLoaded === undefined) {
                    // Request loading Google Maps API.
                    gMapsApiLoaded = false;
                    $.getScript('https://maps.google.com/maps/api/js?sensor=false&callback=Bolt.app.gMapsApiReady')
                        .fail(function (jqxhr, settings, exception) {
                            gMapsApiLoaded = undefined;
                            $(bolt).trigger('bolt:gmaps-failed');
                        });
                } else if (gMapsApiLoaded === true) {
                    // Already loaded, signal it.
                    $(bolt).trigger('bolt:gmaps-loaded');
                }
            });
    }

    /**
     * Initializes globals.
     *
     * @private
     * @function initBuic
     * @memberof Bolt.app
     */
    function initGlobal() {
        var localeLong = bolt.conf('locale.long');

        // Init select2 language.
        $.fn.select2.defaults.set('language', localeLong.replace('_', '-'));
        // Set locale of moments.js.
        moment.locale(localeLong);
        // Set global datepicker locale.
        $.datepicker.setDefaults($.datepicker.regional[localeLong]);
    }

    /**
     * Initializes BUICs.
     *
     * @private
     * @function initBuic
     * @memberof Bolt.app
     */
    function initBuic() {
        $('.buic-checkbox').each(function () {
            bolt.buic.checkbox.init(this);
        });
        $('.buic-moment').each(function () {
            bolt.buic.moment.init(this);
        });
        $('.buic-select').each(function () {
            bolt.buic.select.init(this);
        });
    }

    /**
     * Initializes fieldsets.
     *
     * @private
     * @function initFields
     * @memberof Bolt.app
     */
    function initFields() {
        // Init fieldsets
        $('[data-bolt-field]').each(function () {
            var type = $(this).data('bolt-field'),
                conf = $(this).data('bolt-fconf');

            switch (type) {
                case 'categories':
                    bolt.fields.categories.init(this, conf);
                    break;

                case 'geolocation':
                    bolt.fields.geolocation.init(this, conf);
                    break;

                case 'meta':
                    bolt.fields.meta.init(this, conf);
                    break;

                case 'relationship':
                    bolt.fields.relationship.init(this, conf);
                    break;

                case 'select':
                    bolt.fields.select.init(this, conf);
                    break;

                case 'slug':
                    bolt.fields.slug.init(this, conf);
                    break;

                case 'tags':
                    bolt.fields.tags.init(this, conf);
                    break;

                case 'templateselect':
                    bolt.fields.templateselect.init(this, conf);
                    break;

                case 'checkbox':
                case 'date':
                case 'datetime':
                case 'file':
                case 'filelist':
                case 'float':
                case 'grouping':
                case 'html':
                case 'image':
                case 'imagelist':
                case 'integer':
                case 'markdown':
                case 'text':
                case 'textarea':
                case 'video':
                    // Not implemented yet.
                    break;

                default:
                    console.log('Unknown field type: ' + type);
            }

        });
    }

    // Apply mixin container
    bolt.app = app;

})(Bolt || {}, jQuery);
<commit_msg>Inject moment and init into bolt.app<commit_after>/**
 * Main mixin for the Bolt module.
 *
 * @mixin
 * @namespace Bolt.app
 *
 * @param {Object} bolt - The Bolt module.
 * @param {Object} $ - jQuery.
 * @param {Object} moment - moment.js.
 * @param {Object} init - Bolts deprectated init object.
 */
(function (bolt, $, moment, init) {
    /**
     * Bolt.app mixin container.
     *
     * @private
     * @type {Object}
     */
    var app = {};

    /**
     * Loading state of Google Maps API.
     *
     * @private
     * @type {boolean|undefined} Values: undefined: initial state; false: pending; true: loaded.
     */
    var gMapsApiLoaded;

    /**
     * Callback that signals that Google Maps API is fully loaded.
     *
     * See: https://developers.google.com/maps/documentation/javascript/tutorial#asynch
     *
     * @function gMapsApiReady
     * @memberof Bolt.app
     */
    app.gMapsApiReady = function () {
        gMapsApiLoaded = true;
        $(bolt).trigger('bolt:gmaps-loaded');
    };

    /**
     * Initializes and then starts the Bolt module.
     * Is automatically executed on jQueries ``$(document).ready()``.
     *
     * @function run
     * @memberof Bolt.app
     */
    app.run = function () {
        initGlobal();

        bolt.conf.init();
        bolt.data.init();

        initHandler();

        bolt.actions.init();
        bolt.secmenu.init();
        bolt.stack.init();
        bolt.omnisearch.init();

        bolt.activity.init();
        bolt.ckeditor.init();
        bolt.datetime.init();

        legacyInit();
        initBuic();
        initFields();
    };

    /*
     * Start when ready.
     */
    $(document).ready(app.run);

    /**
     * Legacy stuff from start.js.
     *
     * @private
     * @static
     * @function legacyInit
     * @memberof Bolt.app
     * @todo Move functionality to Bolt mixins.
     * @deprecated To be removed!
     */
    function legacyInit() {
        // Get passed in data from Twig function data()

        // Initialize objects
        bolt.moments = new Moments();
        bolt.imagelist = [];
        bolt.filelist = [];

        // Initialisation
        init.confirmationDialogs();
        init.magnificPopup();
        init.dropZone();
        init.popOvers();
        init.dropDowns();
        init.deferredWidgets();
        init.passwordInput();
        init.dashboardCheckboxes();
        init.sortables();
        init.uploads();
        init.focusStatusSelect();
        init.depublishTracking();

        $('[data-bind]').each(function () {
            var data = $(this).data('bind');
            //console.log('Binding: ' + data.bind);

            switch (data.bind) {
                case 'editcontent': bolt.editcontent.init(data); break;
                case 'editfile': init.bindEditFile(data); break;
                case 'editlocale': init.bindEditLocale(data); break;
                case 'filebrowser': init.bindFileBrowser(); break;
                case 'ckfileselect': init.bindCkFileSelect(); break;
                case 'prefill': init.bindPrefill(); break;
                case 'video': bolt.video.bind(data.key); break;
                default: console.log('Binding ' + data.bind + ' failed!');
            }
        });
    }

    /**
     * Initializes Bolts event handler.
     *
     * @private
     * @static
     * @function initHandler
     * @memberof Bolt.app
     */
    function initHandler() {
        $(bolt)
            // Google Maps API loading
            // - bolt:gmaps-load:   request API loading.
            // - bolt:gmaps-loaded: API loaded successfully.
            // - bolt:gmaps-failed: loading failed.
            .on('bolt:gmaps-load', function (e) {
                if (gMapsApiLoaded === undefined) {
                    // Request loading Google Maps API.
                    gMapsApiLoaded = false;
                    $.getScript('https://maps.google.com/maps/api/js?sensor=false&callback=Bolt.app.gMapsApiReady')
                        .fail(function (jqxhr, settings, exception) {
                            gMapsApiLoaded = undefined;
                            $(bolt).trigger('bolt:gmaps-failed');
                        });
                } else if (gMapsApiLoaded === true) {
                    // Already loaded, signal it.
                    $(bolt).trigger('bolt:gmaps-loaded');
                }
            });
    }

    /**
     * Initializes globals.
     *
     * @private
     * @function initBuic
     * @memberof Bolt.app
     */
    function initGlobal() {
        var localeLong = bolt.conf('locale.long');

        // Init select2 language.
        $.fn.select2.defaults.set('language', localeLong.replace('_', '-'));
        // Set locale of moments.js.
        moment.locale(localeLong);
        // Set global datepicker locale.
        $.datepicker.setDefaults($.datepicker.regional[localeLong]);
    }

    /**
     * Initializes BUICs.
     *
     * @private
     * @function initBuic
     * @memberof Bolt.app
     */
    function initBuic() {
        $('.buic-checkbox').each(function () {
            bolt.buic.checkbox.init(this);
        });
        $('.buic-moment').each(function () {
            bolt.buic.moment.init(this);
        });
        $('.buic-select').each(function () {
            bolt.buic.select.init(this);
        });
    }

    /**
     * Initializes fieldsets.
     *
     * @private
     * @function initFields
     * @memberof Bolt.app
     */
    function initFields() {
        // Init fieldsets
        $('[data-bolt-field]').each(function () {
            var type = $(this).data('bolt-field'),
                conf = $(this).data('bolt-fconf');

            switch (type) {
                case 'categories':
                    bolt.fields.categories.init(this, conf);
                    break;

                case 'geolocation':
                    bolt.fields.geolocation.init(this, conf);
                    break;

                case 'meta':
                    bolt.fields.meta.init(this, conf);
                    break;

                case 'relationship':
                    bolt.fields.relationship.init(this, conf);
                    break;

                case 'select':
                    bolt.fields.select.init(this, conf);
                    break;

                case 'slug':
                    bolt.fields.slug.init(this, conf);
                    break;

                case 'tags':
                    bolt.fields.tags.init(this, conf);
                    break;

                case 'templateselect':
                    bolt.fields.templateselect.init(this, conf);
                    break;

                case 'checkbox':
                case 'date':
                case 'datetime':
                case 'file':
                case 'filelist':
                case 'float':
                case 'grouping':
                case 'html':
                case 'image':
                case 'imagelist':
                case 'integer':
                case 'markdown':
                case 'text':
                case 'textarea':
                case 'video':
                    // Not implemented yet.
                    break;

                default:
                    console.log('Unknown field type: ' + type);
            }

        });
    }

    // Apply mixin container
    bolt.app = app;

})(Bolt || {}, jQuery, moment, init);
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('app.layout')
        .controller('Sidebar', Sidebar);

    Sidebar.$inject = ['$route', 'routehelper'];

    function Sidebar($route, routehelper) {
        /*jshint validthis: true */
        var vm = this;
        var routes = routehelper.getRoutes();

        vm.isCurrent = isCurrent;

        activate();

        function activate() { getNavRoutes(); }

        function getNavRoutes() {
            vm.navRoutes = routes.filter(function (r) {
                return r.settings && r.settings.nav;
            }).sort(function (r1, r2) {
                return r1.settings.nav - r2.settings.nav;
            });
        }

        function isCurrent(route) {
            if (!route.title || !$route.current || !$route.current.title) {
                return '';
            }
            var menuName = route    .title;
            return $route.current.title.substr(0, menuName.length) === menuName ? 'current' : '';
        }
    }
})();<commit_msg>modular: removed spacing bug<commit_after>(function () {
    'use strict';

    angular
        .module('app.layout')
        .controller('Sidebar', Sidebar);

    Sidebar.$inject = ['$route', 'routehelper'];

    function Sidebar($route, routehelper) {
        /*jshint validthis: true */
        var vm = this;
        var routes = routehelper.getRoutes();

        vm.isCurrent = isCurrent;

        activate();

        function activate() { getNavRoutes(); }

        function getNavRoutes() {
            vm.navRoutes = routes.filter(function (r) {
                return r.settings && r.settings.nav;
            }).sort(function (r1, r2) {
                return r1.settings.nav - r2.settings.nav;
            });
        }

        function isCurrent(route) {
            if (!route.title || !$route.current || !$route.current.title) {
                return '';
            }
            var menuName = route.title;
            return $route.current.title.substr(0, menuName.length) === menuName ? 'current' : '';
        }
    }
})();<|endoftext|>


<commit_before>/**
 * page_capture
 * Copyright (c) 2015 Yieldbot, Inc. - All rights reserved.
 */

'use strict';

/* exported PageCapture */

var pcQueue = pcQueue || [];

// public api
var PageCapture = {};

(function () {
  var index = 10;
  var callbacks = {};

  // listen to messages from the content script
  window.addEventListener('message', function (event) {
    if (event.data.__key && typeof callbacks[event.data.__key] === 'function') {
      callbacks[event.data.__key](event.data.value);
    }
  });

  /**
   *
   * @param {function} cmd
   * @return {undefined}
   */
  var runCmd = function(cmd){
    if (typeof cmd === 'function') {
      cmd();
    }
  };

  /**
   *
   * @param {string} api
   * @param {object} opt
   * @param {function} cb
   * @return {undefined}
   */
  var send = function(api, opt, cb){
    opt.ns = 'page_capture';
    opt.api = api;
    opt.__index = index;
    callbacks[index] = cb;

    window.postMessage(opt, '*');
    index++;
  };

  /**
   * get the version
   * @param {function} cb
   * @return {undefined}
   */
  PageCapture.getVersion = function (cb) {
    var opt = {};
    send('getVersion', opt, cb);
  };

  /**
   * take snapshots of elements on a given url
   * @param {string} element
   * @param {function} cb
   */
  PageCapture.captureElement = function (element, cb) {
    var opt = {element: element};
    send('captureElement', opt, cb);
  };

  /**
   * take snapshots of a given url
   * @param {function} cb
   */
  PageCapture.capturePage = function (cb) {
    var opt = {};
    send('capturePage', opt, cb);
  };

  /**
   * take snapshots of a section on a given url
   * @param {number} x
   * @param {number} y
   * @param {number} width
   * @param {number} height
   * @param {function} cb
   */
  PageCapture.captureSection = function (x, y, width, height, cb) {
    var opt = {
      x: x,
      y: y,
      width: width,
      height: height
    };
    send('captureSection', opt, cb);
  };

  /**
   *
   * @param {string} imgUrl
   * @param {number} width
   * @param {number} height
   * @param {function} cb
   */
  PageCapture.captureImage = function(imgUrl, width, height, cb){
    var img = document.getElementById('__pc_image_');

    if(!img){
      img = new Image();
      img.id = '__pc_image_';
      img.style.position = 'fixed';
      img.style.top = '10px';
      img.style.left = '10px';
    }

    img.style.display = 'block';

    img.onload = function() {
      document.body.appendChild(img);
      setTimeout(function(){
        PageCapture.captureElement('#__pc_image_', function(imgData) {
          cb(imgData);
          img.style.display = 'none';
        });
      }, 300);
    };

    if (width) {
      img.width = width;
    }
    if (height) {
      img.height = height;
    }

    img.src = imgUrl;
  };

  /**
   *
   * @param {string} url
   * @param {function} cb
   */
  PageCapture.captureUrl = function(url, cb){
    var opt = {
      url: url,
    };
    send('captureUrl', opt, cb);
  };

  /**
   *
   * @param {string} url
   * @param {string} imgUrl
   * @param {boolean} includeOverlay
   * @param {function} cb
   */
  PageCapture.captureUrlWithOverlay = function(url, imgUrl, includeOverlay, cb){
    var opt = {
      url: url,
      imgUrl: imgUrl,
      includeOverlay: includeOverlay
    };
    send('captureUrl', opt, cb);
  };

  // process the queue
  if (Array.isArray(pcQueue)) {
    pcQueue.forEach(runCmd);
  }

  // redefine pcQueue as an object
  pcQueue = {
    push: function (cmd) {
      runCmd(cmd);
    }
  };

})();
<commit_msg>add z-index to PageCapture.captureImage api<commit_after>/**
 * page_capture
 * Copyright (c) 2015 Yieldbot, Inc. - All rights reserved.
 */

'use strict';

/* exported PageCapture */

var pcQueue = pcQueue || [];

// public api
var PageCapture = {};

(function () {
  var index = 10;
  var callbacks = {};

  // listen to messages from the content script
  window.addEventListener('message', function (event) {
    if (event.data.__key && typeof callbacks[event.data.__key] === 'function') {
      callbacks[event.data.__key](event.data.value);
    }
  });

  /**
   *
   * @param {function} cmd
   * @return {undefined}
   */
  var runCmd = function(cmd){
    if (typeof cmd === 'function') {
      cmd();
    }
  };

  /**
   *
   * @param {string} api
   * @param {object} opt
   * @param {function} cb
   * @return {undefined}
   */
  var send = function(api, opt, cb){
    opt.ns = 'page_capture';
    opt.api = api;
    opt.__index = index;
    callbacks[index] = cb;

    window.postMessage(opt, '*');
    index++;
  };

  /**
   * get the version
   * @param {function} cb
   * @return {undefined}
   */
  PageCapture.getVersion = function (cb) {
    var opt = {};
    send('getVersion', opt, cb);
  };

  /**
   * take snapshots of elements on a given url
   * @param {string} element
   * @param {function} cb
   */
  PageCapture.captureElement = function (element, cb) {
    var opt = {element: element};
    send('captureElement', opt, cb);
  };

  /**
   * take snapshots of a given url
   * @param {function} cb
   */
  PageCapture.capturePage = function (cb) {
    var opt = {};
    send('capturePage', opt, cb);
  };

  /**
   * take snapshots of a section on a given url
   * @param {number} x
   * @param {number} y
   * @param {number} width
   * @param {number} height
   * @param {function} cb
   */
  PageCapture.captureSection = function (x, y, width, height, cb) {
    var opt = {
      x: x,
      y: y,
      width: width,
      height: height
    };
    send('captureSection', opt, cb);
  };

  /**
   *
   * @param {string} imgUrl
   * @param {number} width
   * @param {number} height
   * @param {function} cb
   */
  PageCapture.captureImage = function(imgUrl, width, height, cb){
    var img = document.getElementById('__pc_image_');

    if(!img){
      img = new Image();
      img.id = '__pc_image_';
      img.style.position = 'fixed';
      img.style.top = '10px';
      img.style.left = '10px';
    }

    img.style.display = 'block';
    img.style.zIndex = '99999999999';

    img.onload = function() {
      document.body.appendChild(img);
      setTimeout(function(){
        PageCapture.captureElement('#__pc_image_', function(imgData) {
          cb(imgData);
          img.style.display = 'none';
        });
      }, 300);
    };

    if (width) {
      img.width = width;
    }
    if (height) {
      img.height = height;
    }

    img.src = imgUrl;
  };

  /**
   *
   * @param {string} url
   * @param {function} cb
   */
  PageCapture.captureUrl = function(url, cb){
    var opt = {
      url: url,
    };
    send('captureUrl', opt, cb);
  };

  /**
   *
   * @param {string} url
   * @param {string} imgUrl
   * @param {boolean} includeOverlay
   * @param {function} cb
   */
  PageCapture.captureUrlWithOverlay = function(url, imgUrl, includeOverlay, cb){
    var opt = {
      url: url,
      imgUrl: imgUrl,
      includeOverlay: includeOverlay
    };
    send('captureUrl', opt, cb);
  };

  // process the queue
  if (Array.isArray(pcQueue)) {
    pcQueue.forEach(runCmd);
  }

  // redefine pcQueue as an object
  pcQueue = {
    push: function (cmd) {
      runCmd(cmd);
    }
  };

})();
<|endoftext|>