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

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

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

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

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

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

    module.exports.activeMap = map;

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

    realtime = mapModule.realtime();

  } else {

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

  return map;
};

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

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

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];
module.exports.makerpoint_creadas = [];
module.exports.collision_group = {};
module.exports.marker_collision_group = [];

module.exports.drawMakerCollision = function () {
    var collision_group = L.layerGroup.collision();
    collision_group.addLayer(this.marker_collision_group);
    collision_group.onAdd(this.activeMap);
    this.collision_group =  collision_group;
    console.log("este es el collision group ->", this.collision_group);
};

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

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

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

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

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarkerCollision = function() {
    for (i in this.marker_collision_group) {
        this.collision_group.removeLayer(this.marker_collision_group[i]);
    }

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

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

  this.marker_creadas = [];

};

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

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

  this.makerpoint_creadas = [];

};

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

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

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

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

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

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

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

    var name = to[2];
    var class_name = '';
    var html;
    if (!set_hover){
        class_name = 'leaflet-div-icon1';
        html = "
" + name + "
";
    }else{
        class_name = 'leaflet-div-icon2';
        html = "";
    }
    console.log("class_name ->", class_name);
    var marker = L.marker({"lat":to[0], "lng": to[1]}, {
				icon: L.divIcon({
                    className: class_name,
                    iconSize: [15, 15],
                    iconAnchor: [0, 0],
                    html:html
				})
				,interactive: false
				,clickable:   false
				});

    this.marker_collision_group.push(marker);
};

module.exports.drawRouteAmigo = function(legs,mode, option) {

    var route = legs.legGeometry.points;
    var circle_from = [legs.from.lat, legs.from.lon, legs.from.name];
    var circle_to = [legs.to.lat, legs.to.lon, legs.to.name];
    var color = '#000000';
    var weight = 5;
    var set_hover = false;
    if (option.stroke){
        set_hover = true;
    }

    var dasharray= '';

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

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            if(!(legs.routeColor === undefined)) {
                color = "#"+legs.routeColor;
             }
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
             if(!(legs.routeColor === undefined)) {
                if (legs.routeColor != "" || legs.routeColor.length == 6) {
                    color = "#"+legs.routeColor;
                }

             }
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap, set_hover);
             this.marker_map_point(circle_to, this.activeMap, set_hover);

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

        else if(mode=="BUS") {
            //color = '#FEF0B5';
            if(!(legs.routeColor === undefined)) {
                if (legs.routeColor != "" || legs.routeColor.length == 6) {
                    color = "#"+legs.routeColor;
                }
             }
             weight = 5;
             this.marker_map_point(circle_from, this.activeMap, set_hover);
             this.marker_map_point(circle_to, this.activeMap, set_hover);
        }

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

       if (option.stroke){
         delete color_options.opacity;
       }
       if (option.class_name){
            color_options.className = 'message_';
            color_options.color = '#000';
       }

      var argpolyline = L.PolylineUtil.decode(route, 5);
      argpolyline.unshift(circle_from);
      route = new L.Polyline(argpolyline, color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var boxpolys = new Array(boxes.length);
      route.addTo(this.activeMap);
};

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

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

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

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

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

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

    module.exports.activeMap = map;

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

    realtime = mapModule.realtime();

  } else {

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

  return map;
};

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

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

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];
module.exports.makerpoint_creadas = [];
module.exports.collision_group = {};
module.exports.marker_collision_group = [];

module.exports.drawMakerCollision = function () {
    var collision_group = L.layerGroup.collision();
    collision_group.addLayer(this.marker_collision_group);
    collision_group.onAdd(this.activeMap);
    this.collision_group =  collision_group;
    console.log("este es el collision group ->", this.collision_group);
};

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

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

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

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

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarkerCollision = function() {
    for (i in this.marker_collision_group) {
        this.collision_group.removeLayer(this.marker_collision_group[i]);
    }

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

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

  this.marker_creadas = [];

};

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

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

  this.makerpoint_creadas = [];

};

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

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

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

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

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

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

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

    var name = to[2];
    var class_name = '';
    var html;
    if (!set_hover){
        class_name = 'leaflet-div-icon1';
        html = "
" + name + "
";
    }else{
        class_name = 'leaflet-div-icon2';
        html = "";
    }
    console.log("class_name ->", class_name);
    var marker = L.marker({"lat":to[0], "lng": to[1]}, {
				icon: L.divIcon({
                    className: class_name,
                    iconSize: [15, 15],
                    iconAnchor: [0, 0],
                    html:html
				})
				,interactive: false
				,clickable:   false
				});

    this.marker_collision_group.push(marker);
};

module.exports.drawRouteAmigo = function(legs,mode, option) {

    var route = legs.legGeometry.points;
    var circle_from = [legs.from.lat, legs.from.lon, legs.from.name];
    var circle_to = [legs.to.lat, legs.to.lon, legs.to.name];
    var color = '#000000';
    var weight = 5;
    var set_hover = false;
    if (option.stroke){
        set_hover = true;
    }
    console.log("option.stroke ->", option.stroke);

    var dasharray= '';

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

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            if(!(legs.routeColor === undefined)) {
                color = "#"+legs.routeColor;
             }
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
             if(!(legs.routeColor === undefined)) {
                if (legs.routeColor != "" || legs.routeColor.length == 6) {
                    color = "#"+legs.routeColor;
                }

             }
             weight = 8;
             this.marker_map_point(circle_from, this.activeMap, set_hover);
             this.marker_map_point(circle_to, this.activeMap, set_hover);

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

        else if(mode=="BUS") {
            //color = '#FEF0B5';
            if(!(legs.routeColor === undefined)) {
                if (legs.routeColor != "" || legs.routeColor.length == 6) {
                    color = "#"+legs.routeColor;
                }
             }
             weight = 5;
             this.marker_map_point(circle_from, this.activeMap, set_hover);
             this.marker_map_point(circle_to, this.activeMap, set_hover);
        }

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

       if (option.stroke){
         delete color_options.opacity;
       }
       if (option.class_name){
            color_options.className = 'message_';
            color_options.color = '#ccc';
       }

      var argpolyline = L.PolylineUtil.decode(route, 5);
      argpolyline.unshift(circle_from);
      route = new L.Polyline(argpolyline, color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var boxpolys = new Array(boxes.length);
      route.addTo(this.activeMap);
};

<|endoftext|>


<commit_before>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

$(function () {
    Highcharts.setOptions({
        chart: {
            backgroundColor: 'white'
        },
        title: {
            style: {
                color: 'white'
            }
        },
        legend: {
            title: {
                style: {
                    color: 'silver'
                }
            }
        },
        colorAxis: {
            minColor: '#FFEFD5',
            maxColor: '#8B4513'
        }

    });

    $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=world-population-density.json&callback=?',
function (data) {

        console.log(data);

        // Initiate the chart
        $('#container').highcharts('Map', {

            mapNavigation: {
                enabled: true,
                buttonOptions: {
                    verticalAlign: 'bottom'
                }
            },

            legend: {
                enabled: false
            },

        //     chart: {
        //     events: {
        //         click: function(event) {
        //             alert ('x: '+ event.xAxis[0].value +', y: '+
        //                   event.yAxis[0].value);
        //         }

        //     }
        // },

        colorAxis: {
            min: 1,
            max: 1000,
            type: 'logarithmic',
            minColor: '#EEEEFF',
            maxColor: '#000022',
        },

            plotOptions: {
                series: {
                    cursor: 'pointer',
                    events: {
                        click: function(event) {
                            console.log(event.point.name);
                            $("#search").val(event.point.name);
                            $("#searchbutton").click();
                        }
                    }
                }
            },

            series : [{
                data : data,
                mapData: Highcharts.maps['custom/world'],
                joinBy: ['iso-a2', 'code'],
                name: 'Country',
                states: {
                    hover: {
                        color: '#BADA55'
                    }
                },
                tooltip: {
                pointFormat: '{point.name}'
                }
            }]

        });

        // $('g.highcharts-series-group .highcharts-series path').on('click', function(e) {
        //         e.preventDefault();
        //         var target = $( event.target );
        //         var split_route = $(target).attr("class").split(' ');
        //         var route = split_route[1].split('-')
        //         var final_route = route[2]
        //         var request = $.ajax({
        //             url: '/'+ final_route,
        //             type: 'get',
        //             data: {country_sting: $(target).attr("class")}
        //         });

        //         request.done(function(response) {
        //             console.log(response);
        //         })
        //     })
    });

});

$(".map").click(function(event) {
    console.log("hello");
        // alert(event.target.id+" and "+event.target.class);
    });

<commit_msg>add country name to mouseover on map<commit_after>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

$(function () {
    Highcharts.setOptions({
        chart: {
            backgroundColor: 'white',
            height: 800,
            width: 1400
        },
        title: {
            style: {
                color: 'white'
            }
        },
        legend: {
            title: {
                style: {
                    color: 'silver'
                }
            }
        },
        colorAxis: {
            minColor: '#FFEFD5',
            maxColor: '#8B4513'
        }

    });

    $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=world-population-density.json&callback=?',
function (data) {

        console.log(data);

        // Initiate the chart
        $('#container').highcharts('Map', {

            mapNavigation: {
                enabled: true,
                buttonOptions: {
                    verticalAlign: 'bottom'
                }
            },

            legend: {
                enabled: false
            },

        //     chart: {
        //     events: {
        //         click: function(event) {
        //             alert ('x: '+ event.xAxis[0].value +', y: '+
        //                   event.yAxis[0].value);
        //         }

        //     }
        // },

        colorAxis: {
            min: 1,
            max: 1000,
            type: 'logarithmic',
            minColor: '#EEEEFF',
            maxColor: '#000022',
        },

            plotOptions: {
                series: {
                    cursor: 'pointer',
                    events: {
                        click: function(event) {
                            console.log(event.point.name);
                            $("#search").val(event.point.name);
                            $("#searchbutton").click();
                        }
                    }
                }
            },

            series : [{
                data : data,
                mapData: Highcharts.maps['custom/world'],
                joinBy: ['iso-a2', 'code'],
                name: 'Country',
                states: {
                    hover: {
                        color: '#BADA55'
                    }
                },
                tooltip: {
                pointFormat: '{point.name}'
                }
            }]

        });

        // $('g.highcharts-series-group .highcharts-series path').on('click', function(e) {
        //         e.preventDefault();
        //         var target = $( event.target );
        //         var split_route = $(target).attr("class").split(' ');
        //         var route = split_route[1].split('-')
        //         var final_route = route[2]
        //         var request = $.ajax({
        //             url: '/'+ final_route,
        //             type: 'get',
        //             data: {country_sting: $(target).attr("class")}
        //         });

        //         request.done(function(response) {
        //             console.log(response);
        //         })
        //     })
    });

});

$(".map").click(function(event) {
    console.log("hello");
        // alert(event.target.id+" and "+event.target.class);
    });

<|endoftext|>


<commit_before>/* Copyright 2015 Krzysztof Daniel

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

var ProgressHelper = function(){
	var self = this;
	self.maxnumberofsteps = 4;
	self.maxstate = 100;
	self.progress = -1;
	self.refresh = function() {
		$.ajax({
			type : 'GET',
			url : progressURL /* defined in mapeditor.jade */,
			dataType : 'json',
			success : function(data) {
				self.progress = data.progress;
				self.updateUI(data.progress, false);
			}
		});
	};

	self.advance = function(){
		$.ajax({
			type : 'PUT',
			url : progressURL /* defined in mapeditor.jade */,
			dataType : 'json',
			success : function(data) {
				self.progress = data.progress;
				self.updateUI(data.progress, true);
			}
		});
	};

	self.updateUI = function(progress,progressadvanced){
		/*progress not tracked for this map*/
		if(progress == -1) return;

		for(var i = 0; i < self.maxnumberofsteps - 1; i++){
			var title = $('#mapping-progress-' + i +'> p.progress-title');
			var group = $('#mapping-progress-group-' + i);
			if(i == progress){
				title.css('text-decoration', '');
				title.css('color', 'black');
				title.css('font-weight', 'bold');
				group.show();
			} else {
				if(i < progress){
					title.css('text-decoration', 'line-through');
					title.css('color', 'silver');
				} else {
					title.css('text-decoration', '');
					title.css('color', 'black');
				}
				title.css('font-weight', 'normal');
				group.hide();
			}
		}
		var progressvalue = progress *10;
		$('#progressprogressbar').attr('aria-valuenow', progressvalue).css('width', '' + progressvalue + '%');
		// there is progress, show the assistant box
		if(progress > -1){
			$('#mapcreationassist').show(100);
		}
		if(progress >= self.maxnumberofsteps - 1 && progressadvanced){
		    $('#progressprogressbar').attr('aria-valuenow', progressvalue).css('width', '' + 100 + '%');
		    $('#mapcreationassist').hide(500);
		}
		// progress has not been changed, so the mapcreation assist is invisible, and even if it is, it should not be shown to the user.
		if(progress >= self.maxnumberofsteps - 1 && !progressadvanced){
            $('#mapcreationassist').hide();
        }
		// fr=irst two steps involve a lot of node creation, so enable create by click
		if(progress < 2){
		    $('#mapeditor-preference-clickcreate')[0].checked = false;
		}
		// disable create by click if progress was changed
		if(progress === 2 && progressadvanced){
		    $('#mapeditor-preference-clickcreate')[0].checked = true;
        }

		//defined in the mapeditor.jade
		if(map.nodes.length > 0){
			self.makeAdvanceFromUserNeedAvailable();
		}
	};

	self.updateNodeAccordingToProgressState = function(node){
		if(self.progress == 0){
			node.setUserNeed(true);
			node.setText('user need');
			self.makeAdvanceFromUserNeedAvailable();
		}
	};

	self.makeAdvanceFromUserNeedAvailable = function(){
		$('#mapping-progress-group-' + self.progress +'> button').removeAttr('disabled');
	};

	self.limitEndpointsToShow = function(endpoints){
		if(self.progress > 2 || self.progress == -1){
			return endpoints;
		}
		return [endpoints[0]];
	};
};<commit_msg>Fix a bug where the progress editor appears after window resize.<commit_after>/* Copyright 2015 Krzysztof Daniel

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

var ProgressHelper = function(){
	var self = this;
	self.maxnumberofsteps = 4;
	self.maxstate = 100;
	self.progress = -1;
	self.refresh = function() {
		$.ajax({
			type : 'GET',
			url : progressURL /* defined in mapeditor.jade */,
			dataType : 'json',
			success : function(data) {
				self.progress = data.progress;
				self.updateUI(data.progress, false);
			}
		});
	};

	self.advance = function(){
		$.ajax({
			type : 'PUT',
			url : progressURL /* defined in mapeditor.jade */,
			dataType : 'json',
			success : function(data) {
				self.progress = data.progress;
				self.updateUI(data.progress, true);
			}
		});
	};

	self.updateUI = function(progress,progressadvanced){
		/*progress not tracked for this map*/
		if(progress == -1) return;

		for(var i = 0; i < self.maxnumberofsteps - 1; i++){
			var title = $('#mapping-progress-' + i +'> p.progress-title');
			var group = $('#mapping-progress-group-' + i);
			if(i == progress){
				title.css('text-decoration', '');
				title.css('color', 'black');
				title.css('font-weight', 'bold');
				group.show();
			} else {
				if(i < progress){
					title.css('text-decoration', 'line-through');
					title.css('color', 'silver');
				} else {
					title.css('text-decoration', '');
					title.css('color', 'black');
				}
				title.css('font-weight', 'normal');
				group.hide();
			}
		}
		var progressvalue = progress *10;
		$('#progressprogressbar').attr('aria-valuenow', progressvalue).css('width', '' + progressvalue + '%');
		// there is progress, show the assistant box
		if(progress > -1 && progress < self.maxnumberofsteps - 1){
			$('#mapcreationassist').show(100);
		}
		if(progress >= self.maxnumberofsteps - 1 && progressadvanced){
		    $('#progressprogressbar').attr('aria-valuenow', progressvalue).css('width', '' + 100 + '%');
		    $('#mapcreationassist').hide(500);
		}
		// progress has not been changed, so the mapcreation assist is invisible, and even if it is, it should not be shown to the user.
		if(progress >= self.maxnumberofsteps - 1 && !progressadvanced){
            $('#mapcreationassist').hide();
        }
		// fr=irst two steps involve a lot of node creation, so enable create by click
		if(progress < 2){
		    $('#mapeditor-preference-clickcreate')[0].checked = false;
		}
		// disable create by click if progress was changed
		if(progress === 2 && progressadvanced){
		    $('#mapeditor-preference-clickcreate')[0].checked = true;
        }

		//defined in the mapeditor.jade
		if(map.nodes.length > 0){
			self.makeAdvanceFromUserNeedAvailable();
		}
	};

	self.updateNodeAccordingToProgressState = function(node){
		if(self.progress == 0){
			node.setUserNeed(true);
			node.setText('user need');
			self.makeAdvanceFromUserNeedAvailable();
		}
	};

	self.makeAdvanceFromUserNeedAvailable = function(){
		$('#mapping-progress-group-' + self.progress +'> button').removeAttr('disabled');
	};

	self.limitEndpointsToShow = function(endpoints){
		if(self.progress > 2 || self.progress == -1){
			return endpoints;
		}
		return [endpoints[0]];
	};
};<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
// The order of inclusion of jQuery is important –
// ensure you load jquery.turbolinks before turbolinks and after jquery.
//= require jquery
//= require jquery.turbolinks
// Include all your custom js between jquery-turbolinks.js
//= require jquery_ujs
//= require jquery-ui/datepicker
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require 'short_monograph_description'
// and turbolinks.js
//= require turbolinks
// Required by Blacklight
//= require blacklight/blacklight
// Required by Heliotrope?
// conorom 20170717: disabling CSB temporarily (until its JS plays nice with IE11)
// require cozy-sun-bear-main
//= require leaflet_1.0.3
//= require leaflet-iiif_1.2.1_best_fit
//= require 'edit_users'
//= require 'file_set_sort_date'
//= require 'disable_video_download'
//= require 'disable_audio_download'
//= require 'disable_image_download'
//= require 'ga_event_tracking'
//= require 'bowser.min'
//= require 'disable_chrome_media_download_button'
// AblePlayer audio/video player and dependencies
//= require js.cookie
//= require modernizr.custom
//= require ableplayer
//= require ableplayer_transcript
// Required by Hydra/Rails?
//= require_tree .
//= require hyrax
<commit_msg>re-enable CSB<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
// The order of inclusion of jQuery is important –
// ensure you load jquery.turbolinks before turbolinks and after jquery.
//= require jquery
//= require jquery.turbolinks
// Include all your custom js between jquery-turbolinks.js
//= require jquery_ujs
//= require jquery-ui/datepicker
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require 'short_monograph_description'
// and turbolinks.js
//= require turbolinks
// Required by Blacklight
//= require blacklight/blacklight
// Required by Heliotrope?
//= require cozy-sun-bear-main
//= require leaflet_1.0.3
//= require leaflet-iiif_1.2.1_best_fit
//= require 'edit_users'
//= require 'file_set_sort_date'
//= require 'disable_video_download'
//= require 'disable_audio_download'
//= require 'disable_image_download'
//= require 'ga_event_tracking'
//= require 'bowser.min'
//= require 'disable_chrome_media_download_button'
// AblePlayer audio/video player and dependencies
//= require js.cookie
//= require modernizr.custom
//= require ableplayer
//= require ableplayer_transcript
// Required by Hydra/Rails?
//= require_tree .
//= require hyrax
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
<commit_msg>Initial asset pipeline setup<commit_after>//= require jquery
//= require jquery_ujs
//= require hogan
//= require underscore
//= require backbone
//= require_tree .
<|endoftext|>


<commit_before>app.Interest = React.createClass({
  _liked: false,

  checkLiked: function (interests) {
    this._liked = false;
    var currentUser = app.UserStore.get();
    if (currentUser){
      interests.forEach(function (interest) {
        if (interest.owner === currentUser._id){
          this._liked = interest._id;
        }
      }.bind(this));
    }
  },

  getInitialState: function () {
    var interests = app.InterestStore.getAll(this.props.idea_id);
    this.checkLiked(interests);
    return {
      interests: interests
    };
  },

  handleClick: function () {
    if (this._liked){
      app.InterestActions.delete(this._liked);
    } else {
      app.InterestActions.create(this.props.idea_id);
    }
  },

  componentDidMount: function () {
    app.InterestStore.addChangeListener(function () {
      if(this.isMounted()) {
        var interests = app.InterestStore.getAll(this.props.idea_id);
        this.checkLiked(interests);
        this.setState({ interests: interests });
      }
    }.bind(this));
  },

  render: function () {
    var interestCount = this.state.interests.length;
    return (

        <button className="button-small pure-button" onClick={this.handleClick}>{this._liked ? 'UnLike' : 'Like'}</button>
         {interestCount} Likes

    );
  }

});
<commit_msg>preventDefaultOnLike<commit_after>app.Interest = React.createClass({
  _liked: false,

  checkLiked: function (interests) {
    this._liked = false;
    var currentUser = app.UserStore.get();
    if (currentUser){
      interests.forEach(function (interest) {
        if (interest.owner === currentUser._id){
          this._liked = interest._id;
        }
      }.bind(this));
    }
  },

  getInitialState: function () {
    var interests = app.InterestStore.getAll(this.props.idea_id);
    this.checkLiked(interests);
    return {
      interests: interests
    };
  },

  handleClick: function (e) {
    e.preventDefault();
    if (this._liked){
      app.InterestActions.delete(this._liked);
    } else {
      app.InterestActions.create(this.props.idea_id);
    }
  },

  componentDidMount: function () {
    app.InterestStore.addChangeListener(function () {
      if(this.isMounted()) {
        var interests = app.InterestStore.getAll(this.props.idea_id);
        this.checkLiked(interests);
        this.setState({ interests: interests });
      }
    }.bind(this));
  },

  render: function () {
    var interestCount = this.state.interests.length;
    return (

        <button className="button-small pure-button" onClick={this.handleClick}>{this._liked ? 'UnLike' : 'Like'}</button>
         {interestCount} Likes

    );
  }

});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap/dropdown
//= require bootstrap/collapse
//= require bootstrap/alert
//= require jquery_nested_form
//= require_tree .

Turbolinks.enableTransitionCache();
Turbolinks.enableProgressBar();
<commit_msg>Make transitions smoother<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap/dropdown
//= require bootstrap/collapse
//= require bootstrap/alert
//= require bootstrap/transition
//= require jquery_nested_form
//= require_tree .

Turbolinks.enableTransitionCache();
Turbolinks.enableProgressBar();
<|endoftext|>


<commit_before>/* Contains code for thief goal. */

const RG = require('./rg');
const Goal = require('./goals');

const {
    GOAL_ACTIVE,
    GOAL_COMPLETED} = Goal;
const RNG = RG.Random.getRNG();

/* With this Goal, an actor can search a house for interesting features,
 * such as items to pick up. */
class GoalSearchHouse extends Goal.Base {

    constructor(actor) {
        super(actor);
        this.setType('GoalSearchHouse');
        const cell = actor.getCell();
        if (cell.hasDoor()) {
            this.door = cell.getXY();
        }
        this.subGoals = [];
        this.searchTime = RNG.getUniformInt(20, 40);
    }

    activate() {
        this.status = GOAL_ACTIVE;
        const seenCells = this.actor.getBrain().getSeenCells();
        if (!this.floorCells || this.floorCells.length === 0) {
            this.floorCells = seenCells.filter(c => (
                c.getBaseElem().getType() === 'floorhouse'
            ));
        }

        let nextGoal = findItem(this.actor, seenCells);
        if (!nextGoal) {
            const cell = RNG.arrayGetRand(this.floorCells);
            nextGoal = Goal.FollowPath(this.actor, cell.getXY());
        }

        if (this.searchTime <= 0) {
            const actorCell = this.actor.getCell();
            // Get out of the house
            if (actorCell.hasDoor()) {
                // Get out finally
                const cells = RG.Brain.getCellsAroundActor(this.actor);
                let chosenCell = null;
                cells.forEach(cell => {
                    if (cell.getBaseElem().getType() !== 'floorhouse') {
                        if (cell.isPassable()) {
                            chosenCell = cell;
                            return;
                        }
                    }
                });

                if (chosenCell) {
                    Goal.moveActorTo(this.actor, chosenCell);
                    this.status = GOAL_COMPLETED;
                }
                else {
                    RG.warn('Goal.SearcHouse', 'activate',
                        'Could not move out of the house');
                }
            }
            else {
                nextGoal = Goal.FollowPath(this.actor, actorCell.getXY());
            }
        }

        if (nextGoal) {
            this.addSubGoal(nextGoal);
        }
    }

    process() {
        this.activateIfInactive();
        --this.searchTime;
        if (this.hasSubGoals()) {
            this.status = this.processSubGoals();
        }
        else {
            this.activate();
            if (this.status !== GOAL_COMPLETED) {
                this.status = this.processSubGoals();
            }
        }
    }

}

/* This goal of thief makes an actor to find items, then sell them to a
 * shopkeeper. */
class GoalThief extends Goal.Base {

    constructor(actor) {
        super(actor);
        this.setType('GoalThief');
        this.subGoals = [];
        this.shopCooldown = 20;
        this.doorCooldown = 25;
        this.visitedDoors = {}; // Stores info about doors seen by thief
        this.shops = {}; // Stores known shop location
    }

    activate() {
        this.status = GOAL_ACTIVE;
        this.chooseThiefTask();
    }

    process() {
        this.activateIfInactive();
        --this.shopCooldown;
        console.log('Thief process() shopCooldown is', this.shopCooldown);
        --this.doorCooldown;
        if (this.hasSubGoals()) {
            console.log('Goal.Thief process() processSubGoals()');
            this.status = this.processSubGoals();
        }
        else {
            this.chooseThiefTask();
            this.status = this.processSubGoals();
        }
    }

    isInActiveShop() {
        const cell = this.actor.getCell();
        if (cell.hasShop()) {
            const shop = cell.getShop();
            if (!shop.isAbandoned()) {
                this.shops[cell.getKeyXY()] = cell;
                return true;
            }
        }
        return false;
    }

    tryToSellItem() {
        const inventory = this.actor.getInvEq().getInventory();
        const itemToSell = RNG.arrayGetRand(inventory.getItems());
        const actorCell = this.actor.getCell();
        console.log('Thief trying to sell at', actorCell.getXY());

        const shopElem = actorCell.getPropType('shop')[0];
        // const price = shopElem.getItemPriceForSelling(itemToSell);
        const trans = new RG.Component.Transaction();
        trans.setArgs({item: itemToSell, seller: this._actor,
            shop: shopElem, buyer: shopElem.getShopkeeper(),
            count: itemToSell.count});
        this._actor.add(trans);
    }

    tryToGoToShopCell() {
        let nextGoal = null;
        const knownShopCells = Object.values(this.shops);
        if (knownShopCells.length > 0) {
            const shopCell = RG.arrayGetRand(knownShopCells);
            return new Goal.FollowPath(this.actor, shopCell.getXY());
        }
        const seenCells = this.actor.getBrain().getSeenCells();
        for (let i = 0; i < seenCells.length; i++) {
            const cell = seenCells[i];
            if (cell.hasShop()) {
                nextGoal = new Goal.FollowPath(this.actor, cell.getXY());
            }
        }
        if (!nextGoal) {
            this.shopCooldown = 20;
        }
        return nextGoal;
    }

    chooseThiefTask() {
        console.log('Goal.Thief chooseThiefTask() shopCooldown',
            this.shopCooldown);
        const inventory = this.actor.getInvEq().getInventory();
        const hasItems = !inventory.isEmpty();
        let nextGoal = null;
        const actorCell = this.actor.getCell();

        if (this.isInActiveShop()) {
            this.tryToSellItem();
        }
        else if (hasItems && this.shopCooldown <= 0) {
            console.log('KKK Thief has items. Should find a shop');
            nextGoal = this.tryToGoToShopCell();
        }
        else {
            const seenCells = this.actor.getBrain().getSeenCells();
            const elemsCache = {};
            nextGoal = findItem(this.actor, seenCells, elemsCache,
                cell => cell.hasElements());

            if (!nextGoal && !actorCell.hasDoor() && this.doorCooldown <= 0) {
                // Else if a door is seen, go inside
                Object.values(elemsCache).forEach(cell => {
                    if (cell.hasDoor()) {
                        const xy = cell.getXY();
                        const keyXY = cell.getKeyXY();
                        if (!this.visitedDoors.hasOwnProperty(keyXY)) {
                            this.doorCooldown = 25;
                            nextGoal = new Goal.FollowPath(this.actor, xy);
                            return;
                        }
                    }
                });
            }
            else if (actorCell.hasDoor()) {
                this.visitedDoors[actorCell.getKeyXY()] = actorCell.getXY();
                nextGoal = new GoalSearchHouse(this.actor);
            }

            if (!nextGoal) {
                // Else if a wall is seen, follow it until door found
                // TODO
            }

            if (!nextGoal) {
                // Need to find a house, so skulk around
                // Goal.moveToRandomDir(this.actor);
                nextGoal = new Goal.Explore(this.actor, 30);
                nextGoal.setCallback(this.exploreCallback.bind(this));
            }

        }

        if (nextGoal) {
            this.addSubGoal(nextGoal);
        }
    }

    exploreCallback(x, y) {
        const map = this.actor.getLevel().getMap();
        if (map.hasXY(x, y)) {
            const cell = map.getCell(x, y);
            if (cell.hasShop()) {
                this.shops[cell.getKeyXY()] = cell;
            }
        }
    }

}
Goal.Thief = GoalThief;

function findItem(actor, seenCells, cache, cacheAcceptFunc) {
    let nextGoal = null;
    for (let i = 0; i < seenCells.length; i++) {
        const cell = seenCells[i];
        if (cell.hasItems()) {
            const item = cell.getItems()[0];
            nextGoal = new Goal.GetItem(actor, item);
            console.log('GoalThief found an item', item.getName());
            break;
        }

        // If cache given, try cache cells using cacheAcceptFunc as criteria
        if (cache) {
            if (cacheAcceptFunc(seenCells[i])) {
                cache[cell.getKeyXY()] = cell;
            }
        }
    }
    return nextGoal;
}

module.exports = GoalThief;
<commit_msg>Added some debugging print statements.<commit_after>/* Contains code for thief goal. */

const RG = require('./rg');
const Goal = require('./goals');

const {
    GOAL_ACTIVE,
    GOAL_COMPLETED} = Goal;
const RNG = RG.Random.getRNG();

/* With this Goal, an actor can search a house for interesting features,
 * such as items to pick up. */
class GoalSearchHouse extends Goal.Base {

    constructor(actor) {
        super(actor);
        this.setType('GoalSearchHouse');
        const cell = actor.getCell();
        if (cell.hasDoor()) {
            this.door = cell.getXY();
        }
        this.subGoals = [];
        this.searchTime = RNG.getUniformInt(20, 40);
    }

    activate() {
        this.status = GOAL_ACTIVE;
        const seenCells = this.actor.getBrain().getSeenCells();
        if (!this.floorCells || this.floorCells.length === 0) {
            this.floorCells = seenCells.filter(c => (
                c.getBaseElem().getType() === 'floorhouse'
            ));
        }

        let nextGoal = findItem(this.actor, seenCells);
        if (!nextGoal) {
            const cell = RNG.arrayGetRand(this.floorCells);
            nextGoal = Goal.FollowPath(this.actor, cell.getXY());
        }

        if (this.searchTime <= 0) {
            const actorCell = this.actor.getCell();
            // Get out of the house
            if (actorCell.hasDoor()) {
                // Get out finally
                const cells = RG.Brain.getCellsAroundActor(this.actor);
                let chosenCell = null;
                cells.forEach(cell => {
                    if (cell.getBaseElem().getType() !== 'floorhouse') {
                        if (cell.isPassable()) {
                            chosenCell = cell;
                            return;
                        }
                    }
                });

                if (chosenCell) {
                    Goal.moveActorTo(this.actor, chosenCell);
                    this.status = GOAL_COMPLETED;
                }
                else {
                    RG.warn('Goal.SearcHouse', 'activate',
                        'Could not move out of the house');
                }
            }
            else {
                nextGoal = Goal.FollowPath(this.actor, actorCell.getXY());
            }
        }

        if (nextGoal) {
            this.addSubGoal(nextGoal);
        }
    }

    process() {
        this.activateIfInactive();
        --this.searchTime;
        if (this.hasSubGoals()) {
            this.status = this.processSubGoals();
        }
        else {
            this.activate();
            if (this.status !== GOAL_COMPLETED) {
                this.status = this.processSubGoals();
            }
        }
    }

}

/* This goal of thief makes an actor to find items, then sell them to a
 * shopkeeper. */
class GoalThief extends Goal.Base {

    constructor(actor) {
        super(actor);
        this.setType('GoalThief');
        this.subGoals = [];
        this.shopCooldown = 20;
        this.doorCooldown = 25;
        this.visitedDoors = {}; // Stores info about doors seen by thief
        this.shops = {}; // Stores known shop location
    }

    activate() {
        this.status = GOAL_ACTIVE;
        this.chooseThiefTask();
    }

    process() {
        this.activateIfInactive();
        --this.shopCooldown;
        --this.doorCooldown;
        if (this.hasSubGoals()) {
            this.status = this.processSubGoals();
        }
        else {
            this.chooseThiefTask();
            this.status = this.processSubGoals();
        }
    }

    isInActiveShop() {
        const cell = this.actor.getCell();
        if (cell.hasShop()) {
            const shop = cell.getShop();
            if (!shop.isAbandoned()) {
                this.shops[cell.getKeyXY()] = cell;
                return true;
            }
        }
        return false;
    }

    tryToSellItem() {
        const inventory = this.actor.getInvEq().getInventory();
        const itemToSell = RNG.arrayGetRand(inventory.getItems());
        const actorCell = this.actor.getCell();
        console.log('Thief trying to sell at', actorCell.getXY());

        const shopElem = actorCell.getPropType('shop')[0];
        // const price = shopElem.getItemPriceForSelling(itemToSell);
        const trans = new RG.Component.Transaction();
        trans.setArgs({item: itemToSell, seller: this._actor,
            shop: shopElem, buyer: shopElem.getShopkeeper(),
            count: itemToSell.count});
        this._actor.add(trans);
    }

    tryToGoToShopCell() {
        let nextGoal = null;
        const knownShopCells = Object.values(this.shops);
        if (knownShopCells.length > 0) {
            const shopCell = RG.arrayGetRand(knownShopCells);
            return new Goal.FollowPath(this.actor, shopCell.getXY());
        }
        const seenCells = this.actor.getBrain().getSeenCells();
        for (let i = 0; i < seenCells.length; i++) {
            const cell = seenCells[i];
            if (cell.hasShop()) {
                nextGoal = new Goal.FollowPath(this.actor, cell.getXY());
            }
        }
        if (!nextGoal) {
            this.shopCooldown = 20;
        }
        return nextGoal;
    }

    chooseThiefTask() {
        const inventory = this.actor.getInvEq().getInventory();
        const hasItems = !inventory.isEmpty();
        let nextGoal = null;
        const actorCell = this.actor.getCell();

        if (this.isInActiveShop()) {
            this.tryToSellItem();
        }
        else if (hasItems && this.shopCooldown <= 0) {
            console.log('KKK Thief has items. Should find a shop');
            nextGoal = this.tryToGoToShopCell();
        }
        else {
            const seenCells = this.actor.getBrain().getSeenCells();
            const elemsCache = {};
            nextGoal = findItem(this.actor, seenCells, elemsCache,
                cell => cell.hasElements());

            if (!nextGoal && !actorCell.hasDoor() && this.doorCooldown <= 0) {
                // Else if a door is seen, go inside
                Object.values(elemsCache).forEach(cell => {
                    if (cell.hasDoor()) {
                        const xy = cell.getXY();
                        const keyXY = cell.getKeyXY();
                        if (!this.visitedDoors.hasOwnProperty(keyXY)) {
                            this.doorCooldown = 25;
                            console.log('KKK Thief follow path to', xy);
                            nextGoal = new Goal.FollowPath(this.actor, xy);
                            return;
                        }
                    }
                });
            }
            else if (actorCell.hasDoor()) {
                this.visitedDoors[actorCell.getKeyXY()] = actorCell.getXY();
                console.log('KKK Thief searching house now');
                nextGoal = new GoalSearchHouse(this.actor);
            }

            if (!nextGoal) {
                // Need to find a house, so skulk around
                // Goal.moveToRandomDir(this.actor);
                console.log('Thief added new Goal.Explore');
                nextGoal = new Goal.Explore(this.actor, 30);
                nextGoal.setCallback(this.exploreCallback.bind(this));
            }

        }

        if (nextGoal) {
            this.addSubGoal(nextGoal);
        }
    }

    /* Callback given to Goal.Explore for each x,y explored. */
    exploreCallback(x, y) {
        const map = this.actor.getLevel().getMap();
        if (map.hasXY(x, y)) {
            const cell = map.getCell(x, y);
            if (cell.hasShop()) {
                this.shops[cell.getKeyXY()] = cell;
            }
        }
    }

}
Goal.Thief = GoalThief;

function findItem(actor, seenCells, cache, cacheAcceptFunc) {
    let nextGoal = null;
    for (let i = 0; i < seenCells.length; i++) {
        const cell = seenCells[i];
        if (cell.hasItems()) {
            const item = cell.getItems()[0];
            nextGoal = new Goal.GetItem(actor, item);
            console.log('GoalThief found an item', item.getName());
            break;
        }

        // If cache given, try cache cells using cacheAcceptFunc as criteria
        if (cache) {
            if (cacheAcceptFunc(seenCells[i])) {
                cache[cell.getKeyXY()] = cell;
            }
        }
    }
    return nextGoal;
}

module.exports = GoalThief;
<|endoftext|>


<commit_before>$(document).ready(function(){

  // var turbolinks = require('turbolinks')

  $("#walk-me-home").on("click", function(e){
    e.preventDefault();

    $.ajax({
      url: "http://172.16.50.232:8080/start",
      crossDomain : true,
    })
    .done(function(serverResponse){
      $("#walk-me-home").hide();
      $("#home-safely").show();
      console.log(serverResponse + "This is the server response");
    })
  // need to add failure response
  })

  $("#home-safely").on("click", function(e){
    console.log("I'm home!!")
    e.preventDefault();
    $.ajax({
      url: "http://172.16.50.232:8080/end",
      crossDomain : true,
    })
    .done(function(serverResponse){
      $("#home-safely").hide();
      $("#show-events").show();
      console.log(serverResponse + "This is the server response");

    })
  })

});
<commit_msg>Add ajax call to sms controller<commit_after>$(document).ready(function(){

  // var turbolinks = require('turbolinks')

  $("#walk-me-home").on("click", function(e){
    e.preventDefault();

    $.ajax({
      url: "/sms/text_friend"
    })
    .done(function(serverResponse){

      console.log(serverResponse + " This is the server response");
    })

    .fail(function(serverResponse){

      console.log("Request failed");
    })

    $.ajax({
      url: "http://172.16.50.232:8080/start",
      crossDomain : true,
    })
    .done(function(serverResponse){
      $("#walk-me-home").hide();
      $("#home-safely").show();
      console.log(serverResponse + "This is the server response");
    })
  // need to add failure response
  })

  $("#home-safely").on("click", function(e){
    console.log("I'm home!!")
    e.preventDefault();
    $.ajax({
      url: "http://172.16.50.232:8080/end",
      crossDomain : true,
    })
    .done(function(serverResponse){
      $("#home-safely").hide();
      $("#show-events").show();
      console.log(serverResponse + "This is the server response");

    })
  })

});
<|endoftext|>


<commit_before>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require rails.validations
//= require mousetrap
//= require highlight_js/highlight
//= require highlight_js/languages/ruby
//= require highlight_js/languages/javascript
//= require highlight_js/languages/bash
//= require highlight_js/languages/xml
//= require highlight_js/languages/css
<commit_msg>fix client side validations & Turbolinks bug.<commit_after>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require rails.validations
//= require mousetrap
//= require highlight_js/highlight
//= require highlight_js/languages/ruby
//= require highlight_js/languages/javascript
//= require highlight_js/languages/bash
//= require highlight_js/languages/xml
//= require highlight_js/languages/css

$(function() {
  // Client Side Validations - Turbolinks
  $(document).bind('page:change', function() {
    $('form[data-validate]').validate();
  });
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require Chart
//= require bootstrap-dashboard/bootstrap/alert
//= require bootstrap-dashboard/custom/chartjs-data-api
//= require_tree .
<commit_msg>Include bootstrap/collapse JavaScript<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require Chart
//= require bootstrap-dashboard/bootstrap/alert
//= require bootstrap-dashboard/bootstrap/collapse
//= require bootstrap-dashboard/custom/chartjs-data-api
//= require_tree .
<|endoftext|>


<commit_before>//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require nyulibraries
//= require bootstrap-typeahead
//= require marli
<commit_msg>Don't use Bootstrap typeahead<commit_after>//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require nyulibraries
//= require marli
<|endoftext|>


<commit_before>let test = require("../util/test")

// Ava provides a nice ability to run tests in parallel, but we need to run these tests
// synchronously because too much parallel activity causes webdriver to throw EPIPE errors.

test("Home Page", async t => {
  // We can use t.plan() to indicate how many assertions we plan to make.
  // This provides safety in case there's a silent failure and the test
  // looks like it exited successfully, when in fact it just died. I've
  // seen people get bit by that a done with frameworks like Mocha which
  // do not offer test planning.
  t.plan(6)

  let {
    assertElementText,
    assertElementNotPresent,
    assertElementTextIsInt,
    $,
    $$,
    shortWaitMs
  } = t.context

  await t.context.get("/")

  // Use a CSS selector to find an element that we care about on the page.
  let [
    $draftReports,
    $reportsPending,
    $orgReports,
    $upcomingEngagements
  ] = await $$(".home-tile h1")

  await assertElementTextIsInt(t, $reportsPending)
  await assertElementTextIsInt(t, $draftReports)
  await assertElementTextIsInt(t, $orgReports)
  await assertElementTextIsInt(t, $upcomingEngagements)

  let $tourLauncher = await $(".persistent-tour-launcher")
  await $tourLauncher.click()
  let $hopscotchTitle = await $(".hopscotch-title")
  await assertElementText(
    t,
    $hopscotchTitle,
    "Welcome",
    "Clicking the hopscotch launch button starts the hopscotch tour"
  )

  let $hopscotchNext = await $(".hopscotch-next")
  await $hopscotchNext.click()

  let $myReportsLink = await $("#leftNav > li:nth-child(3) > a")
  await $myReportsLink.click()
  await t.context.driver.sleep(shortWaitMs) // wait for transition
  await assertElementNotPresent(
    t,
    ".hopscotch-title",
    "Navigating to a new page clears the hopscotch tour",
    shortWaitMs
  )
})
<commit_msg>Add sensitive info home tile to e2e tests<commit_after>let test = require("../util/test")

// Ava provides a nice ability to run tests in parallel, but we need to run these tests
// synchronously because too much parallel activity causes webdriver to throw EPIPE errors.

test("Home Page", async t => {
  // We can use t.plan() to indicate how many assertions we plan to make.
  // This provides safety in case there's a silent failure and the test
  // looks like it exited successfully, when in fact it just died. I've
  // seen people get bit by that a done with frameworks like Mocha which
  // do not offer test planning.
  t.plan(7)

  let {
    assertElementText,
    assertElementNotPresent,
    assertElementTextIsInt,
    $,
    $$,
    shortWaitMs
  } = t.context

  await t.context.get("/")

  // Use a CSS selector to find an element that we care about on the page.
  let [
    $draftReports,
    $reportsPending,
    $orgReports,
    $upcomingEngagements,
    $sensitiveInfo
  ] = await $$(".home-tile h1")

  await assertElementTextIsInt(t, $reportsPending)
  await assertElementTextIsInt(t, $draftReports)
  await assertElementTextIsInt(t, $orgReports)
  await assertElementTextIsInt(t, $upcomingEngagements)
  await assertElementTextIsInt(t, $sensitiveInfo)

  let $tourLauncher = await $(".persistent-tour-launcher")
  await $tourLauncher.click()
  let $hopscotchTitle = await $(".hopscotch-title")
  await assertElementText(
    t,
    $hopscotchTitle,
    "Welcome",
    "Clicking the hopscotch launch button starts the hopscotch tour"
  )

  let $hopscotchNext = await $(".hopscotch-next")
  await $hopscotchNext.click()

  let $myReportsLink = await $("#leftNav > li:nth-child(3) > a")
  await $myReportsLink.click()
  await t.context.driver.sleep(shortWaitMs) // wait for transition
  await assertElementNotPresent(
    t,
    ".hopscotch-title",
    "Navigating to a new page clears the hopscotch tour",
    shortWaitMs
  )
})
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require("webpack");
const childProcess = require('child_process')
// As of v3.0.3 GitRevisionPlugin does not work with MiniCssExtractPlugin
// const GitRevisionPlugin = require('git-revision-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
// These steps remove the need for a separate plugin to set the githash
const gitHash = childProcess.execSync('git rev-parse --short HEAD').toString().trim();
const config = require('./src/js/config.json')

module.exports = (env, argv) => ({
  entry: {
      main: './src/js/app/index.js',
  },
  output: {
    filename: '[name]-bundle.js',
    path: path.resolve(__dirname, 'dist', gitHash),
    publicPath: path.join('/dist', gitHash, '/'),
  },
  devServer: {
    host: (env && env.host) || 'localhost',
    port: (env && env.port) || 9000,
    https: true,
    historyApiFallback: {
      index: '/dist/'+gitHash+'/index.html',
    },
    proxy: [{
        context: ['/api'],
        // Change this target to where SynchWeb server is running
        target: (env && env.proxy && env.proxy.target) || 'http://127.0.0.1',
        // Intercept the request and add auth header
        onProxyReq: function(proxyReq, req, res) {
          if (req.headers.authorization) {
            proxyReq.setHeader('Authorization', req.headers.authorization);
          }
        },
        secure: env && env.proxy && env.proxy.secure && JSON.parse(env.proxy.secure)
      },
    ],
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
  resolve: {
    alias: {
      marionette: 'backbone.marionette/lib/backbone.marionette.min',

      'jquery.touchswipe': 'jquery-touchswipe',
      'jquery-ui.timepicker': 'jquery-ui-timepicker-addon', // Need to update timepicker css to avoid showing microseconds/milliseconds
      // Jquery-ui-combox is based on an extension from npm
      // The original was based on a collection of extensions: (https://github.com/bseth99/jquery-ui-extensions)
      // Currently using a modified version from npm
      'jquery-ui.combobox': 'vendor/jquery/jquery-ui.combobox.custom',
      // 'jquery-ui.combobox': 'vendor/jquery/jquery-ui.combobox',

      // Jquery.flot provided by NPM package (exact name match)
      // Jquery.flot.resize also from NPM but slightly older version 1.0.0 2012 instead of 2013 (vendor lib)
      'jquery.flot.resize': 'jquery-flot-resize',
      'jquery.flot.pie': 'flot-pie',
      'jquery.flot.time': 'vendor/flot/jquery.flot.time.min',
      'jquery.flot.selection': 'vendor/flot/jquery.flot.selection',
      'jquery.flot.stack': 'vendor/flot/jquery.flot.stack',

       // Jquery flot tooltip is provided ny NPM with exact name match,
       // so not aliased here, was: 'vendor/flot/jquery.flot.tooltip',
      'jquery.flot.tickrotor': 'vendor/flot/jquery.flot.tickrotor',
      'jquery.flot.axislabels': 'flot-axislabels',

      // We can't currently use the magnific-popup from npm e.g.:
      // 'jquery.mp': 'magnific-popup',
      // The vendor library has been modified to append proposal to the request
      // Hence the vendor magnific-popup has a dependency on our utils/xhrimage
      'jquery.mp': 'vendor/jquery/jquery.magnific-popup',

      // jeditable can be provided by NPM (but only for jQuery 3.x). Does not work with our legacy jquery.
      // 'jquery.editable': 'jquery-jeditable/dist/jquery.jeditable.min',
      // 'jquery.editable.datepicker': 'jquery-jeditable/dist/jquery.jeditable.datepicker.min',
      'jquery.editable': 'vendor/jquery/jquery.jeditable.min',
      'jquery.editable.datepicker': 'vendor/jquery/jquery.jeditable.datepicker',

      // Jquery.color plugin also NPM package
      // Only used from within utils.js
      'jquery.color': 'jquery-color',

      // Caman npm depends on fibers, canvas, fs which we don't want...
      // So use direct downloaded dependency
      caman: 'vendor/caman.min',

      // heatmap in npm has dependency on canvas/node-gyp... so use old one for now
      heatmap: 'vendor/hmap',

      // gunzip is actually the zlib library
      // https://npm.taobao.org/package/zlibjs
      gzip: 'zlibjs/bin/gunzip.min',

      markdown: 'markdown/lib/markdown',

      highmaps: 'highcharts/highmaps',
      'highmaps-world': '@highcharts/map-collection/custom/world',

      // Vue packages from npm (vee-validate requires promise polyfill - also npm)
      vue: 'vue/dist/vue.min',
      veevalidate: 'vee-validate/dist/vee-validate.min',
      luxon: 'luxon',
      formatDate: 'date-fns/format',

      js: path.resolve(__dirname, 'src/js'),
      css: path.resolve(__dirname, 'src/css'),
      // vuejs: path.resolve(__dirname, 'src/js/vuejs'),

    },
    modules: [
      path.resolve(__dirname, 'src/js'),
      path.resolve(__dirname, 'src/css'),
      path.resolve(__dirname, 'node_modules'),
    ],
  },
  module: {
    rules: [
      {
        test: /\.html$/,
        use: [
          {
            loader: 'underscore-template-loader',
            options: {
              engine: 'underscore',
            }
          }
        ],
        exclude: [
          path.resolve(__dirname, 'src/js/templates/vue')
        ]
      },
      {
        test: /\.xml$/,
        use: [
          {
            loader: 'raw-loader',
          }
        ]
      },
      // Font loader - url should be relative to entry main.scss file
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: {
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: '../../assets/fonts', // output path is relative to main module outputPath
            publicPath: '/assets/fonts'
          }
        }
      },
      // SVG could be images or fonts so use more explicit test here...
      {
        test: /font-awesome[\\\/].+\.(svg)$/,
        use: {
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: '../../assets/fonts',
            publicPath: '/assets/fonts'
          }
        }
      },
      {
        test: /\.vue$/,
        use: [
          {
            loader: 'vue-loader',
          }
        ]
      },
      {
        test: /templates[\\\/]vue[\\\/].+\.html$/,
        use: ['html-loader']
      },
      // We need to help Caman load properly
      // Caman adds to the window object within a browser
      // The import loader ensures it it recognised as browser env not NodeJS
      {
        test: /caman\.min\.js$/,
        use: "imports-loader?exports=>undefined,require=>false,this=>window"
      },
      {
        test: /\.(sa|sc|c)ss$/,
        use: [
          // Extract the CSS into separate files
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: argv.mode === 'development',
              // reloadAll: true,
            }
          },
          "css-loader", // translates CSS into CommonJS
          "postcss-loader",
        ]
      },
      {
        test: /\.(png|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 4096, // Anything less than this limit is inlined
              name: '[path][name].[ext]',
              outputPath: '../../assets',
              publicPath: '/assets',
              context: 'src',
            }
          }
        ]
      }
    ]
  },

  plugins: [
    new webpack.ProvidePlugin({
       $: "jquery",
        jQuery: "jquery",
        _: "underscore",
        "window.jQuery": "jquery",
        Highcharts: "highmaps"
    }),
    // This generates a short (8 char) git hash used for build paths
    // new GitRevisionPlugin({
    //   commithashCommand: 'rev-parse --short HEAD'
    // }),
    // This builds an index.php file from the src template
    new HtmlWebpackPlugin({
      title: 'ISPyB',
      filename: path.resolve(__dirname, 'index.php'),
      template: 'src/index.php',
      jsonConfig: config,
    }),
    new HtmlWebpackPlugin({
      title: 'ISPyB',
      filename: path.resolve(__dirname, 'dist/', gitHash, 'index.html'),
      template: 'src/index.html',
      jsonConfig: config,
    }),
    // Generate main html file in root client dir
    new HtmlWebpackPlugin({
      title: 'ISPyB',
      filename: path.resolve(__dirname, 'index.html'),
      template: 'src/index.html',
      jsonConfig: config,
    }),
    // Copy static assets to the assets folder
    // Anything matching in the from path is copied so images/file.png => assets/images/file.png
    // Also copy jquery to assets dir, so we can use it for Dialog popup with log files (see js/views/log.js)
    // Also copy config.json to assets dir, app uses the assets/js/config.json to tell if client needs updating
    new CopyPlugin([
      { context: path.resolve(__dirname, 'src'),
        from: 'images/**',
        to: path.resolve(__dirname, 'assets') },
      { context: path.resolve(__dirname, 'src'),
        from: 'js/config.json',
        to: path.resolve(__dirname, 'assets/js/') },
      { context: path.resolve(__dirname, 'src'),
        from: 'js/vendor/jquery/jquery-1.9.1.min.js',
        to: path.resolve(__dirname, 'assets/js/') },
      { context: path.resolve(__dirname, 'src'),
        from: 'files/**',
        to: path.resolve(__dirname, 'assets') }
    ]),
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
    // Allow use to use process.env.NODE_ENV in the build
    // NODE_ENV should be set in scripts for production builds
    new webpack.EnvironmentPlugin(['NODE_ENV'])
  ]
})
<commit_msg>webpack dev server change to allow dots in parameters<commit_after>const path = require('path');
const webpack = require("webpack");
const childProcess = require('child_process')
// As of v3.0.3 GitRevisionPlugin does not work with MiniCssExtractPlugin
// const GitRevisionPlugin = require('git-revision-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
// These steps remove the need for a separate plugin to set the githash
const gitHash = childProcess.execSync('git rev-parse --short HEAD').toString().trim();
const config = require('./src/js/config.json')

module.exports = (env, argv) => ({
  entry: {
      main: './src/js/app/index.js',
  },
  output: {
    filename: '[name]-bundle.js',
    path: path.resolve(__dirname, 'dist', gitHash),
    publicPath: path.join('/dist', gitHash, '/'),
  },
  devServer: {
    host: (env && env.host) || 'localhost',
    port: (env && env.port) || 9000,
    https: true,
    historyApiFallback: {
      index: '/dist/'+gitHash+'/index.html',
      // Allow parsing urls with dots in parameters (e.g. unit cell search)
      disableDotRule: true
    },
    proxy: [{
        context: ['/api'],
        // Change this target to where SynchWeb server is running
        target: (env && env.proxy && env.proxy.target) || 'http://127.0.0.1',
        // Intercept the request and add auth header
        onProxyReq: function(proxyReq, req, res) {
          if (req.headers.authorization) {
            proxyReq.setHeader('Authorization', req.headers.authorization);
          }
        },
        secure: env && env.proxy && env.proxy.secure && JSON.parse(env.proxy.secure)
      },
    ],
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
  resolve: {
    alias: {
      marionette: 'backbone.marionette/lib/backbone.marionette.min',

      'jquery.touchswipe': 'jquery-touchswipe',
      'jquery-ui.timepicker': 'jquery-ui-timepicker-addon', // Need to update timepicker css to avoid showing microseconds/milliseconds
      // Jquery-ui-combox is based on an extension from npm
      // The original was based on a collection of extensions: (https://github.com/bseth99/jquery-ui-extensions)
      // Currently using a modified version from npm
      'jquery-ui.combobox': 'vendor/jquery/jquery-ui.combobox.custom',
      // 'jquery-ui.combobox': 'vendor/jquery/jquery-ui.combobox',

      // Jquery.flot provided by NPM package (exact name match)
      // Jquery.flot.resize also from NPM but slightly older version 1.0.0 2012 instead of 2013 (vendor lib)
      'jquery.flot.resize': 'jquery-flot-resize',
      'jquery.flot.pie': 'flot-pie',
      'jquery.flot.time': 'vendor/flot/jquery.flot.time.min',
      'jquery.flot.selection': 'vendor/flot/jquery.flot.selection',
      'jquery.flot.stack': 'vendor/flot/jquery.flot.stack',

       // Jquery flot tooltip is provided ny NPM with exact name match,
       // so not aliased here, was: 'vendor/flot/jquery.flot.tooltip',
      'jquery.flot.tickrotor': 'vendor/flot/jquery.flot.tickrotor',
      'jquery.flot.axislabels': 'flot-axislabels',

      // We can't currently use the magnific-popup from npm e.g.:
      // 'jquery.mp': 'magnific-popup',
      // The vendor library has been modified to append proposal to the request
      // Hence the vendor magnific-popup has a dependency on our utils/xhrimage
      'jquery.mp': 'vendor/jquery/jquery.magnific-popup',

      // jeditable can be provided by NPM (but only for jQuery 3.x). Does not work with our legacy jquery.
      // 'jquery.editable': 'jquery-jeditable/dist/jquery.jeditable.min',
      // 'jquery.editable.datepicker': 'jquery-jeditable/dist/jquery.jeditable.datepicker.min',
      'jquery.editable': 'vendor/jquery/jquery.jeditable.min',
      'jquery.editable.datepicker': 'vendor/jquery/jquery.jeditable.datepicker',

      // Jquery.color plugin also NPM package
      // Only used from within utils.js
      'jquery.color': 'jquery-color',

      // Caman npm depends on fibers, canvas, fs which we don't want...
      // So use direct downloaded dependency
      caman: 'vendor/caman.min',

      // heatmap in npm has dependency on canvas/node-gyp... so use old one for now
      heatmap: 'vendor/hmap',

      // gunzip is actually the zlib library
      // https://npm.taobao.org/package/zlibjs
      gzip: 'zlibjs/bin/gunzip.min',

      markdown: 'markdown/lib/markdown',

      highmaps: 'highcharts/highmaps',
      'highmaps-world': '@highcharts/map-collection/custom/world',

      // Vue packages from npm (vee-validate requires promise polyfill - also npm)
      vue: 'vue/dist/vue.min',
      veevalidate: 'vee-validate/dist/vee-validate.min',
      luxon: 'luxon',
      formatDate: 'date-fns/format',

      js: path.resolve(__dirname, 'src/js'),
      css: path.resolve(__dirname, 'src/css'),
      // vuejs: path.resolve(__dirname, 'src/js/vuejs'),

    },
    modules: [
      path.resolve(__dirname, 'src/js'),
      path.resolve(__dirname, 'src/css'),
      path.resolve(__dirname, 'node_modules'),
    ],
  },
  module: {
    rules: [
      {
        test: /\.html$/,
        use: [
          {
            loader: 'underscore-template-loader',
            options: {
              engine: 'underscore',
            }
          }
        ],
        exclude: [
          path.resolve(__dirname, 'src/js/templates/vue')
        ]
      },
      {
        test: /\.xml$/,
        use: [
          {
            loader: 'raw-loader',
          }
        ]
      },
      // Font loader - url should be relative to entry main.scss file
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: {
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: '../../assets/fonts', // output path is relative to main module outputPath
            publicPath: '/assets/fonts'
          }
        }
      },
      // SVG could be images or fonts so use more explicit test here...
      {
        test: /font-awesome[\\\/].+\.(svg)$/,
        use: {
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: '../../assets/fonts',
            publicPath: '/assets/fonts'
          }
        }
      },
      {
        test: /\.vue$/,
        use: [
          {
            loader: 'vue-loader',
          }
        ]
      },
      {
        test: /templates[\\\/]vue[\\\/].+\.html$/,
        use: ['html-loader']
      },
      // We need to help Caman load properly
      // Caman adds to the window object within a browser
      // The import loader ensures it it recognised as browser env not NodeJS
      {
        test: /caman\.min\.js$/,
        use: "imports-loader?exports=>undefined,require=>false,this=>window"
      },
      {
        test: /\.(sa|sc|c)ss$/,
        use: [
          // Extract the CSS into separate files
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: argv.mode === 'development',
              // reloadAll: true,
            }
          },
          "css-loader", // translates CSS into CommonJS
          "postcss-loader",
        ]
      },
      {
        test: /\.(png|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 4096, // Anything less than this limit is inlined
              name: '[path][name].[ext]',
              outputPath: '../../assets',
              publicPath: '/assets',
              context: 'src',
            }
          }
        ]
      }
    ]
  },

  plugins: [
    new webpack.ProvidePlugin({
       $: "jquery",
        jQuery: "jquery",
        _: "underscore",
        "window.jQuery": "jquery",
        Highcharts: "highmaps"
    }),
    // This generates a short (8 char) git hash used for build paths
    // new GitRevisionPlugin({
    //   commithashCommand: 'rev-parse --short HEAD'
    // }),
    // This builds an index.php file from the src template
    new HtmlWebpackPlugin({
      title: 'ISPyB',
      filename: path.resolve(__dirname, 'index.php'),
      template: 'src/index.php',
      jsonConfig: config,
    }),
    new HtmlWebpackPlugin({
      title: 'ISPyB',
      filename: path.resolve(__dirname, 'dist/', gitHash, 'index.html'),
      template: 'src/index.html',
      jsonConfig: config,
    }),
    // Generate main html file in root client dir
    new HtmlWebpackPlugin({
      title: 'ISPyB',
      filename: path.resolve(__dirname, 'index.html'),
      template: 'src/index.html',
      jsonConfig: config,
    }),
    // Copy static assets to the assets folder
    // Anything matching in the from path is copied so images/file.png => assets/images/file.png
    // Also copy jquery to assets dir, so we can use it for Dialog popup with log files (see js/views/log.js)
    // Also copy config.json to assets dir, app uses the assets/js/config.json to tell if client needs updating
    new CopyPlugin([
      { context: path.resolve(__dirname, 'src'),
        from: 'images/**',
        to: path.resolve(__dirname, 'assets') },
      { context: path.resolve(__dirname, 'src'),
        from: 'js/config.json',
        to: path.resolve(__dirname, 'assets/js/') },
      { context: path.resolve(__dirname, 'src'),
        from: 'js/vendor/jquery/jquery-1.9.1.min.js',
        to: path.resolve(__dirname, 'assets/js/') },
      { context: path.resolve(__dirname, 'src'),
        from: 'files/**',
        to: path.resolve(__dirname, 'assets') }
    ]),
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
    // Allow use to use process.env.NODE_ENV in the build
    // NODE_ENV should be set in scripts for production builds
    new webpack.EnvironmentPlugin(['NODE_ENV'])
  ]
})
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require_tree .

 $(document).ready(function() {

	$(".focus .desc").mCustomScrollbar();
	$(".scroll").mCustomScrollbar();

	$('.nodemargin').css('padding-top',$('.focus').css('height'));

	// if there's an add topic directly to page form loaded on the page you're on then let the user add one
	$('#newtopic').click(function(event){
		obj1 = document.getElementById('new_item');
		if (obj1 != null) {
			  $('#new_synapse').css('display','none');
			  $('#new_item').fadeIn('fast');
			  event.preventDefault();
		}
	});

	// if there's an add synapse directly to page form loaded on the page you're on then let the user add one
	$('#newsynapse').click(function(event){
		obj2 = document.getElementById('new_synapse');
		if (obj2 != null) {
			  $('#new_item').css('display','none');
			  $('#new_synapse').fadeIn('fast');
			  event.preventDefault();
		}
	});

	// controls the sliding hover of the filters
    var sliding1 = false;
    $(".accountWrap").hover(
        function () {
          if (! sliding1) {
            sliding1 = true;
            $(".account").slideDown('slow', function() {
              sliding1 = false;
            });
          }
        },
        function () {
          if (! sliding1) {
            sliding1 = true;
            $(".account").slideUp('slow', function() {
              sliding1 = false;
            });
          }
        }
    );

	var sliding2 = false;
    $(".createWrap").hover(
        function () {
          if (! sliding2) {
            sliding2 = true;
            $(".create").slideDown('slow', function() {
              sliding2 = false;
            });
          }
        },
        function () {
          if (! sliding2) {
            sliding2 = true;
            $(".create").slideUp('slow', function() {
              sliding2 = false;
            });
          }
        }
    );

	var sliding3 = false;
    $(".exploreWrap").hover(
        function () {
          if (! sliding3) {
            sliding3 = true;
            $(".explore").slideDown('slow', function() {
              sliding3 = false;
            });
          }
        },
        function () {
          if (! sliding3) {
            sliding3 = true;
            $(".explore").slideUp('slow', function() {
              sliding3 = false;
            });
          }
        }
    );

	var sliding4 = false;
	var lT;
    $(".legend").hover(
        function () {
		  clearTimeout(lT);
          if (! sliding4) {
			  sliding4 = true;
			  $("#iconLegend ul").slideDown('slow', function() {
				sliding4 = false;
			  });
          }
        },
        function () {
          lT = setTimeout(function() {
			  if (! sliding4) {
					sliding4 = true;
					$("#iconLegend ul").slideUp('slow', function() {
					  sliding4 = false;
					});
			  }
		  },800);
        }
    );

	// toggle visibility of item categories based on status in the filters list
	$('.legend ul li').click(function(event) {
		obj = document.getElementById('container');

		var switchAll = $(this).attr('id');
		console.log(switchAll);

		if ( switchAll === "showAll" || switchAll === "hideAll") {
			if (switchAll == "showAll") {
				// this means that we are on a map view
				if (obj != null) {
					if (fd != null) {
						  showAll(fd);
					}
					else if (rg != null) {
						  showAll(rg);
					}
				}
				// this means that we are on a card view
				else {
					console.log('rightone');
					$('.item').fadeIn('slow');
				}
				$('.legend ul li').not('#hideAll, #showAll').removeClass('toggledOff');
				for (var catVis in categoryVisible) {
					categoryVisible[catVis] = true;
				}
			}
			else if (switchAll == "hideAll") {
				// this means that we are on a map view
				if (obj != null) {
					if (fd != null) {
						  hideAll(fd);
					}
					else if (rg != null) {
						  hideAll(rg);
					}
				}
				// this means that we are on a card view
				else {
					$('.item').fadeOut('slow');
				}
				$('.legend ul li').not('#hideAll, #showAll').addClass('toggledOff');
				for (var catVis in categoryVisible) {
					categoryVisible[catVis] = false;
				}
			}
		}
		else {
			var category = $(this).children('img').attr('alt');

			// this means that we are on a map view
			if (obj != null) {
				  if (fd != null) {
						switchVisible(fd, category);
				  }
				  else if (rg != null) {
						switchVisible(rg, category);
				  }
			}
			// this means that we are on a card view
			else {
			  if (categoryVisible[category] == true) {
				  if (category.split(' ').length == 1) {
					$('#cards .' + category).fadeOut('slow');
				  }
				  else {
					  $('#cards .' + category.split(' ')[0]).fadeOut('slow');
				  }
			  }
			  else if (categoryVisible[category] == false) {
				  if (category.split(' ').length == 1) {
					$('#cards .' + category).fadeIn('slow');
				  }
				  else {
					  $('#cards .' + category.split(' ')[0]).fadeIn('slow');
				  }
			  }
			}
					// toggle the image and the boolean array value
			if (categoryVisible[category] == true) {
				$(this).addClass('toggledOff');
				categoryVisible[category] = false;
			}
			else if (categoryVisible[category] == false) {
				$(this).removeClass('toggledOff');
				categoryVisible[category] = true;
			}
		}
	});

	// this is to save the layout of maps
	var coor = "";
	$("#saveLayout").click(function(event) {
	  event.preventDefault();
	  coor = "";
	  if (map != null) {
		  map.graph.eachNode(function(n) {
			coor = coor + n.data.$mappingid + '/' + n.pos.x + '/' + n.pos.y + ',';
		  });
	  }
	  else if (fd != null) {
		  fd.graph.eachNode(function(n) {
			coor = coor + n.data.$mappingid + '/' + n.pos.x + '/' + n.pos.y + ',';
		  });
	  }
	  coor = coor.slice(0, -1);
	  $('#map_coordinates').val(coor);
	  $('#saveMapLayout').submit();
	});
});

<commit_msg>fixed filters on arranged map pages<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require_tree .

 $(document).ready(function() {

	$(".focus .desc").mCustomScrollbar();
	$(".scroll").mCustomScrollbar();

	$('.nodemargin').css('padding-top',$('.focus').css('height'));

	// if there's an add topic directly to page form loaded on the page you're on then let the user add one
	$('#newtopic').click(function(event){
		obj1 = document.getElementById('new_item');
		if (obj1 != null) {
			  $('#new_synapse').css('display','none');
			  $('#new_item').fadeIn('fast');
			  event.preventDefault();
		}
	});

	// if there's an add synapse directly to page form loaded on the page you're on then let the user add one
	$('#newsynapse').click(function(event){
		obj2 = document.getElementById('new_synapse');
		if (obj2 != null) {
			  $('#new_item').css('display','none');
			  $('#new_synapse').fadeIn('fast');
			  event.preventDefault();
		}
	});

	// controls the sliding hover of the filters
    var sliding1 = false;
    $(".accountWrap").hover(
        function () {
          if (! sliding1) {
            sliding1 = true;
            $(".account").slideDown('slow', function() {
              sliding1 = false;
            });
          }
        },
        function () {
          if (! sliding1) {
            sliding1 = true;
            $(".account").slideUp('slow', function() {
              sliding1 = false;
            });
          }
        }
    );

	var sliding2 = false;
    $(".createWrap").hover(
        function () {
          if (! sliding2) {
            sliding2 = true;
            $(".create").slideDown('slow', function() {
              sliding2 = false;
            });
          }
        },
        function () {
          if (! sliding2) {
            sliding2 = true;
            $(".create").slideUp('slow', function() {
              sliding2 = false;
            });
          }
        }
    );

	var sliding3 = false;
    $(".exploreWrap").hover(
        function () {
          if (! sliding3) {
            sliding3 = true;
            $(".explore").slideDown('slow', function() {
              sliding3 = false;
            });
          }
        },
        function () {
          if (! sliding3) {
            sliding3 = true;
            $(".explore").slideUp('slow', function() {
              sliding3 = false;
            });
          }
        }
    );

	var sliding4 = false;
	var lT;
    $(".legend").hover(
        function () {
		  clearTimeout(lT);
          if (! sliding4) {
			  sliding4 = true;
			  $("#iconLegend ul").slideDown('slow', function() {
				sliding4 = false;
			  });
          }
        },
        function () {
          lT = setTimeout(function() {
			  if (! sliding4) {
					sliding4 = true;
					$("#iconLegend ul").slideUp('slow', function() {
					  sliding4 = false;
					});
			  }
		  },800);
        }
    );

	// toggle visibility of item categories based on status in the filters list
	$('.legend ul li').click(function(event) {
		obj = document.getElementById('container');

		var switchAll = $(this).attr('id');
		console.log(switchAll);

		if ( switchAll === "showAll" || switchAll === "hideAll") {
			if (switchAll == "showAll") {
				// this means that we are on a map view
				if (obj != null) {
					if (fd != null) {
						  showAll(fd);
					}
					else if (rg != null) {
						  showAll(rg);
					}
					else if (map != null) {
						  showAll(map);
					}
				}
				// this means that we are on a card view
				else {
					console.log('rightone');
					$('.item').fadeIn('slow');
				}
				$('.legend ul li').not('#hideAll, #showAll').removeClass('toggledOff');
				for (var catVis in categoryVisible) {
					categoryVisible[catVis] = true;
				}
			}
			else if (switchAll == "hideAll") {
				// this means that we are on a map view
				if (obj != null) {
					if (fd != null) {
						  hideAll(fd);
					}
					else if (rg != null) {
						  hideAll(rg);
					}
					else if (map != null) {
						  hideAll(map);
					}
				}
				// this means that we are on a card view
				else {
					$('.item').fadeOut('slow');
				}
				$('.legend ul li').not('#hideAll, #showAll').addClass('toggledOff');
				for (var catVis in categoryVisible) {
					categoryVisible[catVis] = false;
				}
			}
		}
		else {
			var category = $(this).children('img').attr('alt');

			// this means that we are on a map view
			if (obj != null) {
				  if (fd != null) {
						switchVisible(fd, category);
				  }
				  else if (rg != null) {
						switchVisible(rg, category);
				  }
				  else if (map != null) {
						switchVisible(map, category);
				  }
			}
			// this means that we are on a card view
			else {
			  if (categoryVisible[category] == true) {
				  if (category.split(' ').length == 1) {
					$('#cards .' + category).fadeOut('slow');
				  }
				  else {
					  $('#cards .' + category.split(' ')[0]).fadeOut('slow');
				  }
			  }
			  else if (categoryVisible[category] == false) {
				  if (category.split(' ').length == 1) {
					$('#cards .' + category).fadeIn('slow');
				  }
				  else {
					  $('#cards .' + category.split(' ')[0]).fadeIn('slow');
				  }
			  }
			}
					// toggle the image and the boolean array value
			if (categoryVisible[category] == true) {
				$(this).addClass('toggledOff');
				categoryVisible[category] = false;
			}
			else if (categoryVisible[category] == false) {
				$(this).removeClass('toggledOff');
				categoryVisible[category] = true;
			}
		}
	});

	// this is to save the layout of maps
	var coor = "";
	$("#saveLayout").click(function(event) {
	  event.preventDefault();
	  coor = "";
	  if (map != null) {
		  map.graph.eachNode(function(n) {
			coor = coor + n.data.$mappingid + '/' + n.pos.x + '/' + n.pos.y + ',';
		  });
	  }
	  else if (fd != null) {
		  fd.graph.eachNode(function(n) {
			coor = coor + n.data.$mappingid + '/' + n.pos.x + '/' + n.pos.y + ',';
		  });
	  }
	  coor = coor.slice(0, -1);
	  $('#map_coordinates').val(coor);
	  $('#saveMapLayout').submit();
	});
});

<|endoftext|>