<commit_before>Math.rand = function(value){
  return Math.floor(Math.random() * value);
};
var imageCacher = new function(){
  var onLoadCache = {}, imageCache = {};
  var thisObj;
//-------------------------------------
//  載入圖片
//-------------------------------------
  function loadImage(url, callback){
    var image = imageCache[url];
    if (image == undefined){ //還沒有開始載入圖片
      imageCache[url] = (image = new Image());
      image.crossOrigin = "anonymous"; //use CORS //https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes
      onLoadCache[url] = (callback ? [callback] : []);
      image.onload = function(){
        onLoadCache[url].forEach(function(s){ s(image); });
        delete onLoadCache[url];
      };
      image.src = url;
    }else if (onLoadCache[url] == undefined){ //已經開始載入圖片，且已經載入完成了
      if (callback) callback(image);
    }else{ //已經開始載入圖片，但還沒有載入好
      if (callback) onLoadCache[url].push(callback);
    }
  }
  return thisObj = {
    onload: function(url, callback){
      if (url == undefined) return; //missing assets
      if (url.getKey){ //sprite
        alert('not support');
        //loadSprite(url, callback);
      }else{
        loadImage(url, callback);
      }
    },
    ifloaded: function(url, callback, scale){
      var image = imageCache[url];
      if (image == undefined){
        thisObj.onload(url);
      }else if (onLoadCache[url] == undefined){
        if (scale && scale != 1){
          image = imageCacher.loadBy(url + '=> scaled: ' + scale.toFixed(2), function(){
            var width = Math.floor(image.width * scale);
            var height = Math.floor(image.height * scale);
            return (new FilterableImage(image, width, height).getCanvas());
          })
        }
        callback(image);
      }
    },
    loadBy: function(url, onMissFunc){
      if (imageCache[url] == undefined) imageCache[url] = onMissFunc();
      return imageCache[url];
    }
  };
};
function FilterableImage(image, width, height, sx, sy){
  var thisObj;
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  if (width == undefined) width = image.width;
  if (height == undefined) height = image.height;
  canvas.width = width;
  canvas.height = height;
  if (sx == undefined){
    ctx.drawImage(image, 0, 0, width, height);
  }else{
    ctx.drawImage(image, sx, sy, width, height, 0, 0, width, height);
  }
  var imageData = ctx.getImageData( 0, 0, width, height);
  var changeFlag = false;
  return thisObj = {
    applyFilter: function(filter){
      changeFlag = true;
      var args = [imageData.data];
      for(var i = 1; i < arguments.length; ++i) args.push(arguments[i]);
      filter.apply(this, args);
      return thisObj;
    },
    getCanvas: function(){
      if (changeFlag == true){
        changeFlag = false;
        ctx.putImageData(imageData, 0, 0);
      }
      return canvas;
    }
  };
}
//-------------------------------------
//  requestAnimFrame
//-------------------------------------
window.requestAnimFrame = function(){
  return (
    window.requestAnimationFrame       ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame    ||
    window.oRequestAnimationFrame      ||
    window.msRequestAnimationFrame     ||
    function(callback){
      window.setTimeout(callback, 1000 / 60);
    }
  );
}();
//-------------------------------------
//  main
//-------------------------------------
var Input = new function(){
  var statuses = {}, counter = {};
  function getCount(key){
    var count = counter[key];
    return (count == undefined ? 0 : count);
  }
  return {
    KEYS: {
      ENTER: 13,
      SPACE: 32,
      LEFT: 37,
      UP: 38,
      RIGHT: 39,
      DOWN: 40,
      A: 65,
      D: 68,
      S: 83,
      W: 87
    },
    setKeyStatus: function(key, status){
      statuses[key] = status;
    },
    update: function(){
      _.each(Input.KEYS, function(key){
        if (statuses[key]){
          counter[key] = (counter[key] || 0) + 1;
        }else{
          delete counter[key];
        }
      });
      // console.log(counter); //DEBUG
    },
    pressed: function(key){
      return (getCount(key) > 0);
    },
    triggered: function(key){
      return (getCount(key) == 1);
    }
  };
};
$(function(){
  $(window).keydown(function(e){
    // console.log(e.which); //DEBUG
    Input.setKeyStatus(e.which, true);
  }).keyup(function(e){
    Input.setKeyStatus(e.which, false);
  });
});
var sceneManager = new function(){
  var scenes = [];
  return {
    goto: function(scene){
      scene.characterFoctory = createCharacterFactory();
      scenes.unshift(scene);
      scene.initialize();
    },
    back: function(){
      var scene = scenes.shift();
      scene.characterFoctory.destroy();
      return scene;
    },
    update: function(){
      var scene = scenes[0];
      if (scene) scene.update();
    },
    render: function(canvas){
      var scene = scenes[0];
      if (scene) scene.render(canvas);
    },
    getScene: function(){
      return scenes[0];
    }
  };
}

//-------------------------------------
//  Character
//-------------------------------------
function createCharacterFactory(){
  function getMaxPattern(path){ return MAX_PATTERNS[path] || 1; }
  var MAX_PATTERNS = {
    "images/characters/wolf.png": 4,
    "images/characters/enemy.png": 4,
    "images/characters/monster-01.png": 1,
    "images/characters/monster-02.png": 1,
    "images/characters/monster-03.png": 1
  };
  return new function(){
    var characters = {}, counter = 0;
    return {
      characters: characters,
      create: function(path, attrs, preUpdateFunc){
        var cid = (counter += 1);
        var isDead = new FlagObject(false), isDestroyed = new FlagObject(false);
        var pattern = 0, patternCounter = 0, patternAnimeSpeed = 12;
        var character = {
          attrs: attrs,
          ifLoaded: function(callback){
            imageCacher.ifloaded(path, function(image){ callback(image); }, attrs.scale);
          },
          getPattern: function(){ return pattern; },
          maxPattern: getMaxPattern(path),
          update: function(){
            if (preUpdateFunc) preUpdateFunc();
            patternCounter += patternAnimeSpeed;
            if (patternCounter > 100){
              patternCounter -= 100;
              pattern = (pattern + 1) % character.maxPattern;
            }
          },
          damage: function(damage){
            attrs.hp -= damage;
            if (attrs.hp < 0 && isDead.changeTo(true) == true){
              //TODO 死亡動畫
              character.destroy();
            }
          },
          destroy: function(){
            if (isDestroyed.changeTo(true) == false) return;
            delete characters[cid];
          }
        };
        return characters[cid] = character;
      },
      destroy: function(){
        _.each(characters, function(character){ character.destroy(); });
        characters = undefined;
      }
    }
  }
}
function NumericSpring(xv, xt, zeta, omega){
  var f = 1.0 + 2.0 * zeta * omega;
  var oo = omega * omega;
  var detInv = 1.0 / (f + oo);
  var detX = f * xv.x + xv.v + oo * xt;
  var detV = xv.v + oo * (xt - xv.x);
  xv.x = detX * detInv;
  xv.v = detV * detInv;
}
function SpringAnimator(defaultVal, updateSpan, zeta, time, onUpdate){
  var thisObj, epsilon = 0.01;
  var xv = {x: defaultVal, v: 0};
  var omega = 2 * Math.PI * updateSpan / time;
  var animaFunc;
  var delayCount = 0, delayCallback, delayedArguments = [];
  return thisObj = {
    update: function(){
      if (animaFunc == undefined) return;
      if (animaFunc() == false) animaFunc = undefined;
    },
    setVal: function(targetVal, onEnd){
      if (delayCount > 0){ delayedArguments.push(['setVal', arguments]); return thisObj; }
      animaFunc = function(){
        if (delayCount > 0){
          delayCount -= 1;
          if (delayCount == 0){
            var tmp = delayedArguments;
            delayedArguments = [];
            _.each(tmp, function(data){ thisObj[data[0]].apply(thisObj, data[1]); });
            delayCallback();
          }
        }
        var preX = xv.x;
        NumericSpring(xv, targetVal, zeta, omega);
        if (Math.abs(preX - xv.x) < epsilon && Math.abs(targetVal - xv.x) < epsilon){
          xv.x = targetVal;
          xv.v = 0;
          if (onUpdate) onUpdate(targetVal);
          if (onEnd) onEnd();
          return false;
        }
        if (onUpdate) onUpdate(xv.x);
        return true;
      };
      return thisObj;
    },
    delay: function(time, callback){
      if (delayCount > 0){ delayedArguments.push(['delay', arguments]); return thisObj; }
      delayCount = time;
      delayCallback = callback;
      return thisObj;
    },
    remove: function(onRemove){
      if (delayCount > 0){ delayedArguments.push(['remove', arguments]); return thisObj; }
      if (onRemove) onRemove();
    }
  };
}
function drawImageWithXRepeat(canvas, viewX, ratio, path){
  var ctx = canvas.getContext("2d");
  imageCacher.ifloaded(path, function(image){
    var width = image.width * (canvas.height / image.height);
    var dx = -(viewX * ratio) % width;
    if (dx > 0) dx -= width;
    while(dx < canvas.width){
      ctx.drawImage(image, dx, 0, width, canvas.height);
      dx += width;
    }
  });
}
function FlagObject(flag){
  var thisObj, prevFlag;
  return thisObj = {
    changeTo: function(newFlag){ //回傳flag有沒有變
      if (newFlag == flag) return false;
      prevFlag = flag;
      flag = newFlag;
      return true;
    },
    toggle: function(newFlag){
      thisObj.changeTo(newFlag != undefined ? newFlag : !flag);
      return thisObj.val();
    },
    is: function(checkFlag){
      return (flag == checkFlag);
    },
    val: function(){
      return flag;
    },
    prevVal: function(){
      return prevFlag;
    }
  };
}
<commit_msg>sceneManager provide push, pop, goto methods<commit_after>Math.rand = function(value){
  return Math.floor(Math.random() * value);
};
var imageCacher = new function(){
  var onLoadCache = {}, imageCache = {};
  var thisObj;
//-------------------------------------
//  載入圖片
//-------------------------------------
  function loadImage(url, callback){
    var image = imageCache[url];
    if (image == undefined){ //還沒有開始載入圖片
      imageCache[url] = (image = new Image());
      image.crossOrigin = "anonymous"; //use CORS //https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes
      onLoadCache[url] = (callback ? [callback] : []);
      image.onload = function(){
        onLoadCache[url].forEach(function(s){ s(image); });
        delete onLoadCache[url];
      };
      image.src = url;
    }else if (onLoadCache[url] == undefined){ //已經開始載入圖片，且已經載入完成了
      if (callback) callback(image);
    }else{ //已經開始載入圖片，但還沒有載入好
      if (callback) onLoadCache[url].push(callback);
    }
  }
  return thisObj = {
    onload: function(url, callback){
      if (url == undefined) return; //missing assets
      if (url.getKey){ //sprite
        alert('not support');
        //loadSprite(url, callback);
      }else{
        loadImage(url, callback);
      }
    },
    ifloaded: function(url, callback, scale){
      var image = imageCache[url];
      if (image == undefined){
        thisObj.onload(url);
      }else if (onLoadCache[url] == undefined){
        if (scale && scale != 1){
          image = imageCacher.loadBy(url + '=> scaled: ' + scale.toFixed(2), function(){
            var width = Math.floor(image.width * scale);
            var height = Math.floor(image.height * scale);
            return (new FilterableImage(image, width, height).getCanvas());
          })
        }
        callback(image);
      }
    },
    loadBy: function(url, onMissFunc){
      if (imageCache[url] == undefined) imageCache[url] = onMissFunc();
      return imageCache[url];
    }
  };
};
function FilterableImage(image, width, height, sx, sy){
  var thisObj;
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  if (width == undefined) width = image.width;
  if (height == undefined) height = image.height;
  canvas.width = width;
  canvas.height = height;
  if (sx == undefined){
    ctx.drawImage(image, 0, 0, width, height);
  }else{
    ctx.drawImage(image, sx, sy, width, height, 0, 0, width, height);
  }
  var imageData = ctx.getImageData( 0, 0, width, height);
  var changeFlag = false;
  return thisObj = {
    applyFilter: function(filter){
      changeFlag = true;
      var args = [imageData.data];
      for(var i = 1; i < arguments.length; ++i) args.push(arguments[i]);
      filter.apply(this, args);
      return thisObj;
    },
    getCanvas: function(){
      if (changeFlag == true){
        changeFlag = false;
        ctx.putImageData(imageData, 0, 0);
      }
      return canvas;
    }
  };
}
//-------------------------------------
//  requestAnimFrame
//-------------------------------------
window.requestAnimFrame = function(){
  return (
    window.requestAnimationFrame       ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame    ||
    window.oRequestAnimationFrame      ||
    window.msRequestAnimationFrame     ||
    function(callback){
      window.setTimeout(callback, 1000 / 60);
    }
  );
}();
//-------------------------------------
//  main
//-------------------------------------
var Input = new function(){
  var statuses = {}, counter = {};
  function getCount(key){
    var count = counter[key];
    return (count == undefined ? 0 : count);
  }
  return {
    KEYS: {
      ENTER: 13,
      SPACE: 32,
      LEFT: 37,
      UP: 38,
      RIGHT: 39,
      DOWN: 40,
      A: 65,
      D: 68,
      S: 83,
      W: 87
    },
    setKeyStatus: function(key, status){
      statuses[key] = status;
    },
    update: function(){
      _.each(Input.KEYS, function(key){
        if (statuses[key]){
          counter[key] = (counter[key] || 0) + 1;
        }else{
          delete counter[key];
        }
      });
      // console.log(counter); //DEBUG
    },
    pressed: function(key){
      return (getCount(key) > 0);
    },
    triggered: function(key){
      return (getCount(key) == 1);
    }
  };
};
$(function(){
  $(window).keydown(function(e){
    // console.log(e.which); //DEBUG
    Input.setKeyStatus(e.which, true);
  }).keyup(function(e){
    Input.setKeyStatus(e.which, false);
  });
});
var sceneManager = new function(){
  var thisObj, scenes = [];
  return thisObj = {
    push: function(scene){
      scene.characterFoctory = createCharacterFactory();
      scenes.unshift(scene);
      scene.initialize();
    },
    goto: function(scene){
      while(thisObj.pop() != undefined);
      thisObj.push(scene);
    },
    pop: function(){
      var scene = scenes.shift();
      if (scene) scene.characterFoctory.destroy();
      return scene;
    },
    update: function(){
      var scene = scenes[0];
      if (scene) scene.update();
    },
    render: function(canvas){
      var scene = scenes[0];
      if (scene) scene.render(canvas);
    },
    getScene: function(){
      return scenes[0];
    }
  };
}

//-------------------------------------
//  Character
//-------------------------------------
function createCharacterFactory(){
  function getMaxPattern(path){ return MAX_PATTERNS[path] || 1; }
  var MAX_PATTERNS = {
    "images/characters/wolf.png": 4,
    "images/characters/enemy.png": 4,
    "images/characters/monster-01.png": 1,
    "images/characters/monster-02.png": 1,
    "images/characters/monster-03.png": 1
  };
  return new function(){
    var characters = {}, counter = 0;
    return {
      characters: characters,
      create: function(path, attrs, preUpdateFunc){
        var cid = (counter += 1);
        var isDead = new FlagObject(false), isDestroyed = new FlagObject(false);
        var pattern = 0, patternCounter = 0, patternAnimeSpeed = 12;
        var character = {
          attrs: attrs,
          ifLoaded: function(callback){
            imageCacher.ifloaded(path, function(image){ callback(image); }, attrs.scale);
          },
          getPattern: function(){ return pattern; },
          maxPattern: getMaxPattern(path),
          update: function(){
            if (preUpdateFunc) preUpdateFunc();
            patternCounter += patternAnimeSpeed;
            if (patternCounter > 100){
              patternCounter -= 100;
              pattern = (pattern + 1) % character.maxPattern;
            }
          },
          damage: function(damage){
            attrs.hp -= damage;
            if (attrs.hp < 0 && isDead.changeTo(true) == true){
              //TODO 死亡動畫
              character.destroy();
            }
          },
          destroy: function(){
            if (isDestroyed.changeTo(true) == false) return;
            delete characters[cid];
          }
        };
        return characters[cid] = character;
      },
      destroy: function(){
        _.each(characters, function(character){ character.destroy(); });
        characters = undefined;
      }
    }
  }
}
function NumericSpring(xv, xt, zeta, omega){
  var f = 1.0 + 2.0 * zeta * omega;
  var oo = omega * omega;
  var detInv = 1.0 / (f + oo);
  var detX = f * xv.x + xv.v + oo * xt;
  var detV = xv.v + oo * (xt - xv.x);
  xv.x = detX * detInv;
  xv.v = detV * detInv;
}
function SpringAnimator(defaultVal, updateSpan, zeta, time, onUpdate){
  var thisObj, epsilon = 0.01;
  var xv = {x: defaultVal, v: 0};
  var omega = 2 * Math.PI * updateSpan / time;
  var animaFunc;
  var delayCount = 0, delayCallback, delayedArguments = [];
  return thisObj = {
    update: function(){
      if (animaFunc == undefined) return;
      if (animaFunc() == false) animaFunc = undefined;
    },
    setVal: function(targetVal, onEnd){
      if (delayCount > 0){ delayedArguments.push(['setVal', arguments]); return thisObj; }
      animaFunc = function(){
        if (delayCount > 0){
          delayCount -= 1;
          if (delayCount == 0){
            var tmp = delayedArguments;
            delayedArguments = [];
            _.each(tmp, function(data){ thisObj[data[0]].apply(thisObj, data[1]); });
            delayCallback();
          }
        }
        var preX = xv.x;
        NumericSpring(xv, targetVal, zeta, omega);
        if (Math.abs(preX - xv.x) < epsilon && Math.abs(targetVal - xv.x) < epsilon){
          xv.x = targetVal;
          xv.v = 0;
          if (onUpdate) onUpdate(targetVal);
          if (onEnd) onEnd();
          return false;
        }
        if (onUpdate) onUpdate(xv.x);
        return true;
      };
      return thisObj;
    },
    delay: function(time, callback){
      if (delayCount > 0){ delayedArguments.push(['delay', arguments]); return thisObj; }
      delayCount = time;
      delayCallback = callback;
      return thisObj;
    },
    remove: function(onRemove){
      if (delayCount > 0){ delayedArguments.push(['remove', arguments]); return thisObj; }
      if (onRemove) onRemove();
    }
  };
}
function drawImageWithXRepeat(canvas, viewX, ratio, path){
  var ctx = canvas.getContext("2d");
  imageCacher.ifloaded(path, function(image){
    var width = image.width * (canvas.height / image.height);
    var dx = -(viewX * ratio) % width;
    if (dx > 0) dx -= width;
    while(dx < canvas.width){
      ctx.drawImage(image, dx, 0, width, canvas.height);
      dx += width;
    }
  });
}
function FlagObject(flag){
  var thisObj, prevFlag;
  return thisObj = {
    changeTo: function(newFlag){ //回傳flag有沒有變
      if (newFlag == flag) return false;
      prevFlag = flag;
      flag = newFlag;
      return true;
    },
    toggle: function(newFlag){
      thisObj.changeTo(newFlag != undefined ? newFlag : !flag);
      return thisObj.val();
    },
    is: function(checkFlag){
      return (flag == checkFlag);
    },
    val: function(){
      return flag;
    },
    prevVal: function(){
      return prevFlag;
    }
  };
}
<|endoftext|>


<commit_before>(function(){
	'use strict';
	angular.module('moment', []).factory('moment', function () { return window.moment; });
	angular.module('underscore', []).factory('_', function () { return window._; });

	angular.module('lui.directives', ['pascalprecht.translate', 'moment', 'underscore', 'ui.select', 'ui.bootstrap']);
	angular.module('lui.filters', ['moment']);
	angular.module('lui.services', ['cgNotify']);

	// all the templates in one module
	angular.module('lui.templates.momentpicker', []); // module defined here and used in a different file so every page doesnt have to reference the right .js file
	angular.module("lui.templates.daterangepicker", []); // module defined here and used in a different file so every page doesnt have to reference the right .js file
	angular.module("lui.templates.translationsinput", []); // module defined here and used in a different file so every page doesnt have to reference the right .js file
	angular.module('lui.templates', ['lui.templates.momentpicker', "lui.templates.daterangepicker", "lui.templates.translationsinput"]);

	// all the translations in one module
	angular.module('lui.translates.userpicker', []);
	angular.module('lui.translates.daterangepicker', []);
	angular.module('lui.translates.tablegrid', ['lui.filters']);
	angular.module('lui.translates', ['pascalprecht.translate','lui.translates.userpicker','lui.translates.daterangepicker','lui.translates.tablegrid']);

	angular.module('lui', ['lui.directives','lui.services','lui.filters','lui.templates','lui.translates']);

})();
<commit_msg>FIX wrong dependency injection<commit_after>(function(){
	'use strict';
	angular.module('moment', []).factory('moment', function () { return window.moment; });
	angular.module('underscore', []).factory('_', function () { return window._; });

	angular.module('lui.directives', ['pascalprecht.translate', 'moment', 'underscore', 'ui.select', 'ui.bootstrap', 'lui.filters']);
	angular.module('lui.filters', ['moment']);
	angular.module('lui.services', ['cgNotify']);

	// all the templates in one module
	angular.module('lui.templates.momentpicker', []); // module defined here and used in a different file so every page doesnt have to reference the right .js file
	angular.module("lui.templates.daterangepicker", []); // module defined here and used in a different file so every page doesnt have to reference the right .js file
	angular.module("lui.templates.translationsinput", []); // module defined here and used in a different file so every page doesnt have to reference the right .js file
	angular.module('lui.templates', ['lui.templates.momentpicker', "lui.templates.daterangepicker", "lui.templates.translationsinput"]);

	// all the translations in one module
	angular.module('lui.translates.userpicker', []);
	angular.module('lui.translates.daterangepicker', []);
	angular.module('lui.translates.tablegrid', []);
	angular.module('lui.translates', ['pascalprecht.translate','lui.translates.userpicker','lui.translates.daterangepicker','lui.translates.tablegrid']);

	angular.module('lui', ['lui.directives','lui.services','lui.filters','lui.templates','lui.translates']);

})();
<|endoftext|>


<commit_before>$(function(){

  // Leave some room for the header and footer
  $('#map').css("height", ($(window).height() - 100));
  $('#overlay').css("height", ($(window).height() - 163));

  var map = L.mapbox.map('map', 'codeforamerica.map-hhckoiuj',
    {
      scrollWheelZoom:false
    }
    ).setView([35, -100], 3);

  map.zoomControl.setPosition('bottomright');

  cfapi = "http://civic-tech-movement.codeforamerica.org/api/organizations"
  // cfapi = "http://localhost:5000/api/organizations"

  // Custom marker type with space for Brigade data
  var BrigadeMarker = L.Marker.extend({
    options: {
      brigade : {}
    }
  });

  $.getJSON(cfapi, function(data){
    var brigades = data.objects;

    $.each(brigades, function(i, brigade){
      console.log(brigade);

      if (brigade.type == "Brigade"){
        if (brigade.latitude && brigade.longitude){
          var lat = brigade.latitude, lng = brigade.longitude;

          var marker = new BrigadeMarker(new L.LatLng(lat,lng), {
            icon: L.mapbox.marker.icon({'marker-symbol': 'town-hall'}),
            title: brigade.name,
            brigade: brigade // Add Brigade data to marker
          });

          map.addLayer(marker);

          // On click, show the Brigade data on the overlay
          marker.on('click',function(e) {
            updateOverlay(e.target.options.brigade);
          });

        }
      }
    });
  }).done( function() {
    // This uses the HTML5 geolocation API, which is available on
    // most mobile browsers and modern browsers, but not in Internet Explorer
    //
    // See this chart of compatibility for details:
    // http://caniuse.com/#feat=geolocation
    if (!navigator.geolocation) {
        console.log('geolocation is not available');
    } else {
      map.locate({setView:true, maxZoom:7});
    }
  });

  function updateOverlay(brigade){
    $("#overlay-reset").show();
    $("#brigade-name").text(brigade.name);
    $("#brigade-url").text(brigade.website).attr("href",brigade.website).show();
    $("#program-info").hide();
    $("#join-form").hide();

    // Show two stories
    if (brigade.stories.length != 0) {
      $("#stories ul").empty();
      for (var i = 0; i < 2; i++) {
        story = brigade.stories[i];
        html = "
"+story.title+"
"
        $("#stories ul").append(html);
      }
      $("#stories").show();
    } else {
      $("#stories").hide();
    }

    // Show two projects
    if (brigade.projects.length != 0) {
      $("#projects ul").empty();
      for (var i = 0; i < 2; i++) {
        project = brigade.projects[i];
        html = "
"+project.name+"";
        html += "
"+project.description+"

";
        $("#projects ul").append(html);
      };
      $("#projects").show();
    } else {
      $("#projects").hide();
    }

    // Show two events
    if (brigade.events){
      if (brigade.events.length != 0) {
        $("#events ul").empty();
        for (var i = 0; i < 2; i++) {
          event = brigade.events[i];
          html = "
"+event.title+"
"
          $("#events ul").append(html);
        }
        $("#events").show();
      } else {
        $("#events").hide();
      }
    }

  }

  // Reset overlay
  map.on('click', function(e){
    resetOverlay();
  })

  function resetOverlay(){
    $("#overlay-reset").hide();
    $("#brigade-name").text("The Code for America Brigade");
    $("#brigade-url").hide();
    $("#program-info").show();
    $("#stories").hide();
    $("#projects").hide();
    $("#events").hide();
    $("#join-form").show();
  }

});<commit_msg>Higher zoom level.<commit_after>$(function(){

  // Leave some room for the header and footer
  $('#map').css("height", ($(window).height() - 100));
  $('#overlay').css("height", ($(window).height() - 163));

  var map = L.mapbox.map('map', 'codeforamerica.map-hhckoiuj',
    {
      scrollWheelZoom:false
    }
    ).setView([35, -100], 3);

  map.zoomControl.setPosition('bottomright');

  cfapi = "http://civic-tech-movement.codeforamerica.org/api/organizations"
  // cfapi = "http://localhost:5000/api/organizations"

  // Custom marker type with space for Brigade data
  var BrigadeMarker = L.Marker.extend({
    options: {
      brigade : {}
    }
  });

  $.getJSON(cfapi, function(data){
    var brigades = data.objects;

    $.each(brigades, function(i, brigade){
      console.log(brigade);

      if (brigade.type == "Brigade"){
        if (brigade.latitude && brigade.longitude){
          var lat = brigade.latitude, lng = brigade.longitude;

          var marker = new BrigadeMarker(new L.LatLng(lat,lng), {
            icon: L.mapbox.marker.icon({'marker-symbol': 'town-hall'}),
            title: brigade.name,
            brigade: brigade // Add Brigade data to marker
          });

          map.addLayer(marker);

          // On click, show the Brigade data on the overlay
          marker.on('click',function(e) {
            updateOverlay(e.target.options.brigade);
          });

        }
      }
    });
  }).done( function() {
    // This uses the HTML5 geolocation API, which is available on
    // most mobile browsers and modern browsers, but not in Internet Explorer
    //
    // See this chart of compatibility for details:
    // http://caniuse.com/#feat=geolocation
    if (!navigator.geolocation) {
        console.log('geolocation is not available');
    } else {
      map.locate({setView:true, maxZoom:4});
    }
  });

  function updateOverlay(brigade){
    $("#overlay-reset").show();
    $("#brigade-name").text(brigade.name);
    $("#brigade-url").text(brigade.website).attr("href",brigade.website).show();
    $("#program-info").hide();
    $("#join-form").hide();

    // Show two stories
    if (brigade.stories.length != 0) {
      $("#stories ul").empty();
      for (var i = 0; i < 2; i++) {
        story = brigade.stories[i];
        html = "
"+story.title+"
"
        $("#stories ul").append(html);
      }
      $("#stories").show();
    } else {
      $("#stories").hide();
    }

    // Show two projects
    if (brigade.projects.length != 0) {
      $("#projects ul").empty();
      for (var i = 0; i < 2; i++) {
        project = brigade.projects[i];
        html = "
"+project.name+"";
        html += "
"+project.description+"

";
        $("#projects ul").append(html);
      };
      $("#projects").show();
    } else {
      $("#projects").hide();
    }

    // Show two events
    if (brigade.events){
      if (brigade.events.length != 0) {
        $("#events ul").empty();
        for (var i = 0; i < 2; i++) {
          event = brigade.events[i];
          html = "
"+event.title+"
"
          $("#events ul").append(html);
        }
        $("#events").show();
      } else {
        $("#events").hide();
      }
    }

  }

  // Reset overlay
  map.on('click', function(e){
    resetOverlay();
  })

  function resetOverlay(){
    $("#overlay-reset").hide();
    $("#brigade-name").text("The Code for America Brigade");
    $("#brigade-url").hide();
    $("#program-info").show();
    $("#stories").hide();
    $("#projects").hide();
    $("#events").hide();
    $("#join-form").show();
  }

});<|endoftext|>


<commit_before>var Map;

Map = function () {
    var map;

    map = [];

    this.setMap = function (newMap) {
        map = newMap;
    };

    this.getView = function (x, y, width, height) {
        var view, i;
        view = map.slice(y, y + height);
        width += x;
        for (i = height; i--;) {
            view[i] = view[i].slice(x, width);
        }
        return view;
    };

    this.randomMap = function (width, height) {
        var i, j, row;
        map = [];
        for (i = height; i--;) {
            row = [];
            for (j = width; j--;) {
                row.push({
                    type: Math.round(Math.random() * 2),
                    accessible: Math.round(Math.random() * 2) > 1
                });
            }
            map.push(row);
        }
    };
};<commit_msg>updated random map generating to match wiki specification<commit_after>var Map;

Map = function () {
    var map;

    map = [];

    this.setMap = function (newMap) {
        map = newMap;
    };

    this.getView = function (x, y, width, height) {
        var view, i;
        view = map.slice(y, y + height);
        width += x;
        for (i = height; i--;) {
            view[i] = view[i].slice(x, width);
        }
        return view;
    };

    this.randomMap = function (width, height) {
        var i, j, row;
        map = [];
        for (i = height; i--;) {
            row = [];
            for (j = width; j--;) {
                row.push({
                    type: Math.round(Math.random() * 2),
                    accessible: Math.round(Math.random() * 2) > 1,
                    minimap: 'rgb(' + Math.round(Math.random() * 255) + ',' +
                            Math.round(Math.random() * 255) + ',' +
                            Math.round(Math.random() * 255) + ')'
                });
            }
            map.push(row);
        }
    };
};<|endoftext|>


<commit_before>function map(data) {

    var zoom = d3.behavior.zoom()
        .scaleExtent([1, 8])
        .on("zoom", move);

    var mapDiv = $("#map");
    var partyDiv = $("#party");

    var margin = { top: 0, right: 0, bottom: 0, left: 0 },
        width = mapDiv.width() - margin.right - margin.left,
        height = partyDiv.height() - margin.top - margin.bottom;

    var legendRectSize = 18;
    var legendSpacing = 2;

    var tip = d3.tip()
        .attr('class', 'd3-map-tip')
        .offset([2, 0]);

    var projection = d3.geo.mercator()
        .center([40, 62])
        .scale(850);

    var svg = d3.select("#map").append("svg")
        .attr("width", width)
        .attr("height", height)
        .style("border", "1px solid black")
        .append("g")
        .call(zoom);

    var path = d3.geo.path()
        .projection(projection);

    g = svg.append("g");
    svg.call(tip);

    // load data and draw the map
    d3.json("data/sweden_mun.topojson", function(error, sweden) {

        var mun = topojson.feature(sweden, sweden.objects.swe_mun).features;

        draw(mun, data);
    });

    function draw(mun, electionData) {

        regiondData = d3.nest()
            .key(function(d) {
                return d.region;
            })
            .entries(electionData);
        self.electionData = electionData;

        var trueVal = $("#year").slider("value");
        var year = ELECTIONYEARSARRAY[trueVal];

        var mun = g.selectAll(".swe_mun").data(mun);
        var colorOfParty = partyColor(electionData, year);

        mun.enter().insert("path")
            .attr("class", "mun")
            .attr("d", path)

        .style("fill", function(d, i) {
                var index = 0;
                for (var l = 0; l < colorOfParty.length; ++l) {
                    // Compare region-name
                    if (d.properties.name == colorOfParty[l].reg) {
                        index = l;
                        break;
                    }

                };
                return color.get(colorOfParty[index].par);
            })
            .attr("stroke-width", 0.1)
            .attr("stroke", "black")

        .on("mouseover", function(d) {

            var trueVal = $("#year").slider("value");
            var year = ELECTIONYEARSARRAY[trueVal];

            for (var r in regiondData) {
                if (d.properties.name == regiondData[r].key) {
                    var regObj = regiondData[r];
                    break;
                }
            };
            var regArr = [];
            regObj.values.forEach(function(r) {
                regArr.push({ parti: r.parti, procent: r[year] });
            });

            tip.html(function(x) {

                var res = "" + "
 " + d.properties.name + "
";

                for (var i = 0; i < regArr.length; ++i) {
                    if (!isNaN(regArr[i].procent)) {
                        res += "
" + "" + regArr[i].parti + "" + " : " + regArr[i].procent + " %" + "
";
                    }
                }

                res += "";
                return res;
            });
            tip.show();
        })

        .on("mouseout", function(d) {
            tip.hide();
        })

        .on("click", function(d) {
            d3.selectAll(".mun")
                .style("stroke-width", .1)

            d3.select(this)
                .style("stroke-width", 1)

            var totalProcent = 0;
            for (var r in regiondData) {
                if (d.properties.name == regiondData[r].key) {
                    var regObj = regiondData[r];
                    regObj.values.forEach(function(e) {
                        if (!isNaN(e[ELECTIONYEARSARRAY[$("#year").slider("value")]])) {
                            totalProcent += e[ELECTIONYEARSARRAY[$("#year").slider("value")]];
                        }
                    })
                    break;
                }
            };

            if (totalProcent) {
                selectedMun(d.properties.name);
                $("#searchfield").attr("placeholder", d.properties.name).val("").focus().blur();
            } else {
                $("#searchfield").attr("placeholder", d.properties.name + ": saknas data").val("").focus().blur();
            }

        });

        var legend = g.selectAll(".legend")
            .data(miningArray)
            .enter()
            .append("g")
            .attr("class", "legend");
        legend.attr('transform', function(d, i) {
            var height = legendRectSize + legendSpacing;
            var offset = height * miningArray.length / 2;
            var horz = 1 * legendRectSize;
            var vert = i * height - offset + 50;
            return 'translate(' + horz + ',' + vert + ')';
        });

        legend.append('rect')
            .attr('class', 'legendRect')
            .attr('width', legendRectSize)
            .attr('height', legendRectSize)
            .style("opacity", 0)
            .style('fill', function(d, i) {

                return miningMap.get(d);
            })
            .style('stroke', function(d) {
                return miningMap.get(d);
            });

        legend.append('text')
            .attr('class', 'legendText')
            .attr('x', legendRectSize + legendSpacing)
            .attr('y', legendRectSize - legendSpacing)
            .style("opacity", 0)
            .text(function(d) {
                return d;
            });
    }

    this.colorByYear = function(electionYear) {

        g.selectAll("text.legendText")
            .style("opacity", 0);
        g.selectAll("rect.legendRect")
            .style("opacity", 0);

        year = electionYear;

        var mun;
        if ($("#searchfield").attr("placeholder") == "Municipality") {
            mun = "Upplands Väsby";
        } else {
            mun = $("#searchfield").attr("placeholder");
        }

        donut1.drawMun(mun, year);

        var colorOfParty = partyColor(electionData, year);

        g.selectAll(".mun").each(function(p) {

            var point = d3.select(this);
            point.style("fill-opacity", 1)

            point.style("fill", function(d) {

                var index = NaN;
                for (var l = 0; l < colorOfParty.length; ++l) {
                    // Compare region-name
                    if (d.properties.name == colorOfParty[l].reg) {
                        index = l;
                        break;
                    }
                };
                if (!isNaN(index)) {
                    return color.get(colorOfParty[index].par);
                } else {
                    return color.get("Odefinierad");
                }

            });
            point.attr("title", function(d) {
                var regionString = "";
                for (var r = 0; r < regiondData.length; ++r) {
                    if (regiondData[r].key == d.properties.name) {
                        regionString = regiondData[r].key;
                        regiondData[r].values.forEach(function(e) {
                            if (!isNaN(e[year])) {
                                regionString = regionString + "\n" + e.parti + ": " + e[year];
                            }
                        })
                    }
                    continue;
                };
                return regionString;
            })
        });
    }

    this.colorByParty = function(electionYear, party) {

        g.selectAll("text.legendText")
            .style("opacity", 0);
        g.selectAll("rect.legendRect")
            .style("opacity", 0);

        year = electionYear;

        var mun;
        if ($("#searchfield").attr("placeholder") == "Municipality") {
            mun = "Upplands Väsby";
        } else {
            mun = $("#searchfield").attr("placeholder");
        }

        donut1.drawMun(mun, electionYear);

        // TEMP
        if (!party) {
            var party = CURRMUN;
        };

        var nested_data = d3.nest()
            .key(function(d) {
                return d.parti;
            })
            .sortValues(function(a, b) {
                return b[year] - a[year];
            })
            .entries(electionData);

        nested_data = nested_data.filter(function(d) {
            return d.key == party;
        })

        var len = nested_data[0].values.length;

        var max, min;
        max = parseFloat(nested_data[0].values[0][year]);
        min = parseFloat(nested_data[0].values[len - 1][year]);

        g.selectAll(".mun").each(function(p) {

            var point = d3.select(this);

            point.style("fill", function(d) {
                for (var i = 0; i < len; ++i) {

                    var region = nested_data[0].values[i];

                    if (d.properties.name == region.region) {
                        return !(isNaN(region[year])) ? color.get(party) : "white";
                    }
                };
            })
            point.style("fill-opacity", function(d) {
                var opac = 0;
                for (var i = 0; i < len; ++i) {
                    var region = nested_data[0].values[i];
                    // Compare region-name
                    if (d.properties.name == region.region) {
                        opac = (parseFloat(region[year]) - min) / (max - min);
                        break;
                    }
                };
                return opac;
            });
        });

    }

    this.munBorder = function(mun) {

        d3.selectAll(".mun")
            .style("stroke-width", function(b) {
                return (b.properties.name == mun) ? 1 : 0.1;
            });
    };

    function partyColor(electionData, year) {

        var nested_data = d3.nest()
            .key(function(d) {
                return d.region;
            })
            .entries(electionData);

        var colorOfParty = [];

        nested_data.forEach(function(d) {

            d.values.sort(compare);

            colorOfParty.push({ reg: d.values[0].region, par: d.values[0].parti });
        });
        return colorOfParty;

        function compare(a, b) {

            if (isNaN(a[year]) && isNaN(b[year]))
                return 0;
            else if (isNaN(a[year]) && !(isNaN(b[year])))
                return 1;
            else if (!(isNaN(a[year])) && isNaN(b[year]))
                return -1;
            else if (a[year]  b[year])
                return -1;
            else
                return 0;
        }
    }

    function getYear(year) {
        return year;
    }

    //zoom and panning method
    function move() {

        var t = d3.event.translate;
        var s = d3.event.scale;

        zoom.translate(t);
        g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ")scale(" + s + ")");
    }

    // Sends the name of the mun to other .js-files
    function selectedMun(mun) {

        var trueVal = $("#year").slider("value");
        var year = ELECTIONYEARSARRAY[trueVal];

        if ($("#searchfield").attr("placeholder") == "Municipality") {
            mun = "Upplands Väsby";
        }

        donut1.drawMun(mun, year);
    }

    this.regionsimilarities = function(electionYear, mun) {

        //sortera efter regioner
        var nested_data = d3.nest()
            .key(function(d) {
                return d.region;
            })
            .entries(electionData);

        //beräkna för vald region spara object i variable
        var vald;
        nested_data.forEach(function(m) {
            if (m.key == mun) {
                vald = m;
            };
        });

        //beräkna för övriga regioner och jämför med vald
        //lägg in i en array
        var simmun = [];
        nested_data.forEach(function(m) {
            if (m.key != mun) {
                var mu, dif = 0;
                mu = m.key;
                m.values.forEach(function(y, i) {
                    if (!isNaN(vald.values[i][electionYear]) || !isNaN(y[electionYear])) {
                        dif += Math.sqrt(Math.pow(vald.values[i][electionYear] - y[electionYear], 2));
                    }
                });
                simmun.push({ reg: mu, value: dif });
            }
        });

        simmun.sort(function(a, b) {
            if (a.value > b.value) {
                return 1;
            }
            if (a.value < b.value) {
                return -1;
            }
            // a must be equal to b
            return 0;
        });

        var len = simmun.length;

        g.selectAll(".mun").each(function(p) {

            var point = d3.select(this);
            //OPTIMERA
            point.style("fill", function(d) {
                if (d.properties.name == vald.key) {
                    return "orange"
                }

                for (var i = 0; i < 30; ++i) {
                    var region = simmun[i];

                    if (d.properties.name == region.reg) {
                        return "green";
                    }
                };

                for (var i = len - 1; i > (len - 30); --i) {

                    var region = simmun[i];
                    if (d.properties.name == region.reg) {
                        return "red";
                    }
                }
            })
            point.style("fill-opacity", 1)
        });

        g.selectAll("rect.legendRect")
            .style("opacity", 1);
        g.selectAll("text.legendText")
            .style("opacity", 1);

    };
}<commit_msg>Static legend<commit_after>function map(data) {

    var zoom = d3.behavior.zoom()
        .scaleExtent([1, 8])
        .on("zoom", move);

    var mapDiv = $("#map");
    var partyDiv = $("#party");

    var margin = { top: 0, right: 0, bottom: 0, left: 0 },
        width = mapDiv.width() - margin.right - margin.left,
        height = partyDiv.height() - margin.top - margin.bottom;

    var legendRectSize = 18;
    var legendSpacing = 2;

    var tip = d3.tip()
        .attr('class', 'd3-map-tip')
        .offset([2, 0]);

    var projection = d3.geo.mercator()
        .center([40, 62])
        .scale(850);

    var svg = d3.select("#map").append("svg")
        .attr("width", width)
        .attr("height", height)
        .style("border", "1px solid black")
        .append("g")
        .call(zoom);

    var path = d3.geo.path()
        .projection(projection);

    g = svg.append("g");
    l = svg.append("g");
    svg.call(tip);

    // load data and draw the map
    d3.json("data/sweden_mun.topojson", function(error, sweden) {

        var mun = topojson.feature(sweden, sweden.objects.swe_mun).features;

        draw(mun, data);
    });

    function draw(mun, electionData) {

        regiondData = d3.nest()
            .key(function(d) {
                return d.region;
            })
            .entries(electionData);
        self.electionData = electionData;

        var trueVal = $("#year").slider("value");
        var year = ELECTIONYEARSARRAY[trueVal];

        var mun = g.selectAll(".swe_mun").data(mun);
        var colorOfParty = partyColor(electionData, year);

        mun.enter().insert("path")
            .attr("class", "mun")
            .attr("d", path)

        .style("fill", function(d, i) {
                var index = 0;
                for (var l = 0; l < colorOfParty.length; ++l) {
                    // Compare region-name
                    if (d.properties.name == colorOfParty[l].reg) {
                        index = l;
                        break;
                    }

                };
                return color.get(colorOfParty[index].par);
            })
            .attr("stroke-width", 0.1)
            .attr("stroke", "black")

        .on("mouseover", function(d) {

            var trueVal = $("#year").slider("value");
            var year = ELECTIONYEARSARRAY[trueVal];

            for (var r in regiondData) {
                if (d.properties.name == regiondData[r].key) {
                    var regObj = regiondData[r];
                    break;
                }
            };
            var regArr = [];
            regObj.values.forEach(function(r) {
                regArr.push({ parti: r.parti, procent: r[year] });
            });

            tip.html(function(x) {

                var res = "" + "
 " + d.properties.name + "
";

                for (var i = 0; i < regArr.length; ++i) {
                    if (!isNaN(regArr[i].procent)) {
                        res += "
" + "" + regArr[i].parti + "" + " : " + regArr[i].procent + " %" + "
";
                    }
                }

                res += "";
                return res;
            });
            tip.show();
        })

        .on("mouseout", function(d) {
            tip.hide();
        })

        .on("click", function(d) {
            d3.selectAll(".mun")
                .style("stroke-width", .1)

            d3.select(this)
                .style("stroke-width", 1)

            var totalProcent = 0;
            for (var r in regiondData) {
                if (d.properties.name == regiondData[r].key) {
                    var regObj = regiondData[r];
                    regObj.values.forEach(function(e) {
                        if (!isNaN(e[ELECTIONYEARSARRAY[$("#year").slider("value")]])) {
                            totalProcent += e[ELECTIONYEARSARRAY[$("#year").slider("value")]];
                        }
                    })
                    break;
                }
            };

            if (totalProcent) {
                selectedMun(d.properties.name);
                $("#searchfield").attr("placeholder", d.properties.name).val("").focus().blur();
            } else {
                $("#searchfield").attr("placeholder", d.properties.name + ": saknas data").val("").focus().blur();
            }

        });

        var legend = l.selectAll(".legend")
            .data(miningArray)
            .enter()
            .append("g")
            .attr("class", "legend");
        legend.attr('transform', function(d, i) {
            var height = legendRectSize + legendSpacing;
            var offset = height * miningArray.length / 2;
            var horz = 1 * legendRectSize;
            var vert = i * height - offset + 50;
            return 'translate(' + horz + ',' + vert + ')';
        });

        legend.append('rect')
            .attr('class', 'legendRect')
            .attr('width', legendRectSize)
            .attr('height', legendRectSize)
            .style("opacity", 0)
            .style('fill', function(d, i) {

                return miningMap.get(d);
            })
            .style('stroke', function(d) {
                return miningMap.get(d);
            });

        legend.append('text')
            .attr('class', 'legendText')
            .attr('x', legendRectSize + legendSpacing)
            .attr('y', legendRectSize - legendSpacing)
            .style("opacity", 0)
            .text(function(d) {
                return d;
            });
    }

    this.colorByYear = function(electionYear) {

        g.selectAll("text.legendText")
            .style("opacity", 0);
        g.selectAll("rect.legendRect")
            .style("opacity", 0);

        year = electionYear;

        var mun;
        if ($("#searchfield").attr("placeholder") == "Municipality") {
            mun = "Upplands Väsby";
        } else {
            mun = $("#searchfield").attr("placeholder");
        }

        donut1.drawMun(mun, year);

        var colorOfParty = partyColor(electionData, year);

        g.selectAll(".mun").each(function(p) {

            var point = d3.select(this);
            point.style("fill-opacity", 1)

            point.style("fill", function(d) {

                var index = NaN;
                for (var l = 0; l < colorOfParty.length; ++l) {
                    // Compare region-name
                    if (d.properties.name == colorOfParty[l].reg) {
                        index = l;
                        break;
                    }
                };
                if (!isNaN(index)) {
                    return color.get(colorOfParty[index].par);
                } else {
                    return color.get("Odefinierad");
                }

            });
            point.attr("title", function(d) {
                var regionString = "";
                for (var r = 0; r < regiondData.length; ++r) {
                    if (regiondData[r].key == d.properties.name) {
                        regionString = regiondData[r].key;
                        regiondData[r].values.forEach(function(e) {
                            if (!isNaN(e[year])) {
                                regionString = regionString + "\n" + e.parti + ": " + e[year];
                            }
                        })
                    }
                    continue;
                };
                return regionString;
            })
        });
    }

    this.colorByParty = function(electionYear, party) {

        g.selectAll("text.legendText")
            .style("opacity", 0);
        g.selectAll("rect.legendRect")
            .style("opacity", 0);

        year = electionYear;

        var mun;
        if ($("#searchfield").attr("placeholder") == "Municipality") {
            mun = "Upplands Väsby";
        } else {
            mun = $("#searchfield").attr("placeholder");
        }

        donut1.drawMun(mun, electionYear);

        // TEMP
        if (!party) {
            var party = CURRMUN;
        };

        var nested_data = d3.nest()
            .key(function(d) {
                return d.parti;
            })
            .sortValues(function(a, b) {
                return b[year] - a[year];
            })
            .entries(electionData);

        nested_data = nested_data.filter(function(d) {
            return d.key == party;
        })

        var len = nested_data[0].values.length;

        var max, min;
        max = parseFloat(nested_data[0].values[0][year]);
        min = parseFloat(nested_data[0].values[len - 1][year]);

        g.selectAll(".mun").each(function(p) {

            var point = d3.select(this);

            point.style("fill", function(d) {
                for (var i = 0; i < len; ++i) {

                    var region = nested_data[0].values[i];

                    if (d.properties.name == region.region) {
                        return !(isNaN(region[year])) ? color.get(party) : "white";
                    }
                };
            })
            point.style("fill-opacity", function(d) {
                var opac = 0;
                for (var i = 0; i < len; ++i) {
                    var region = nested_data[0].values[i];
                    // Compare region-name
                    if (d.properties.name == region.region) {
                        opac = (parseFloat(region[year]) - min) / (max - min);
                        break;
                    }
                };
                return opac;
            });
        });

    }

    this.munBorder = function(mun) {

        d3.selectAll(".mun")
            .style("stroke-width", function(b) {
                return (b.properties.name == mun) ? 1 : 0.1;
            });
    };

    function partyColor(electionData, year) {

        var nested_data = d3.nest()
            .key(function(d) {
                return d.region;
            })
            .entries(electionData);

        var colorOfParty = [];

        nested_data.forEach(function(d) {

            d.values.sort(compare);

            colorOfParty.push({ reg: d.values[0].region, par: d.values[0].parti });
        });
        return colorOfParty;

        function compare(a, b) {

            if (isNaN(a[year]) && isNaN(b[year]))
                return 0;
            else if (isNaN(a[year]) && !(isNaN(b[year])))
                return 1;
            else if (!(isNaN(a[year])) && isNaN(b[year]))
                return -1;
            else if (a[year]  b[year])
                return -1;
            else
                return 0;
        }
    }

    function getYear(year) {
        return year;
    }

    //zoom and panning method
    function move() {

        var t = d3.event.translate;
        var s = d3.event.scale;

        zoom.translate(t);
        g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ")scale(" + s + ")");
    }

    // Sends the name of the mun to other .js-files
    function selectedMun(mun) {

        var trueVal = $("#year").slider("value");
        var year = ELECTIONYEARSARRAY[trueVal];

        if ($("#searchfield").attr("placeholder") == "Municipality") {
            mun = "Upplands Väsby";
        }

        donut1.drawMun(mun, year);
    }

    this.regionsimilarities = function(electionYear, mun) {

        //sortera efter regioner
        var nested_data = d3.nest()
            .key(function(d) {
                return d.region;
            })
            .entries(electionData);

        //beräkna för vald region spara object i variable
        var vald;
        nested_data.forEach(function(m) {
            if (m.key == mun) {
                vald = m;
            };
        });

        //beräkna för övriga regioner och jämför med vald
        //lägg in i en array
        var simmun = [];
        nested_data.forEach(function(m) {
            if (m.key != mun) {
                var mu, dif = 0;
                mu = m.key;
                m.values.forEach(function(y, i) {
                    if (!isNaN(vald.values[i][electionYear]) || !isNaN(y[electionYear])) {
                        dif += Math.sqrt(Math.pow(vald.values[i][electionYear] - y[electionYear], 2));
                    }
                });
                simmun.push({ reg: mu, value: dif });
            }
        });

        simmun.sort(function(a, b) {
            if (a.value > b.value) {
                return 1;
            }
            if (a.value < b.value) {
                return -1;
            }
            // a must be equal to b
            return 0;
        });

        var len = simmun.length;

        g.selectAll(".mun").each(function(p) {

            var point = d3.select(this);
            //OPTIMERA
            point.style("fill", function(d) {
                if (d.properties.name == vald.key) {
                    return "orange"
                }

                for (var i = 0; i < 30; ++i) {
                    var region = simmun[i];

                    if (d.properties.name == region.reg) {
                        return "green";
                    }
                };

                for (var i = len - 1; i > (len - 30); --i) {

                    var region = simmun[i];
                    if (d.properties.name == region.reg) {
                        return "red";
                    }
                }
            })
            point.style("fill-opacity", 1)
        });

        l.selectAll("rect.legendRect")
            .style("opacity", 1);
        l.selectAll("text.legendText")
            .style("opacity", 1);

    };
}<|endoftext|>


<commit_before>var Map = {};
Map.markers = [];

Map.buildOption = function() {
    var bounds = Map.getMapBounds(Map.map);
    var options = new QueryOptionBuilder()
	    .setMapBounds(bounds.lat1, bounds.lng1,
			  bounds.lat2, bounds.lng2)
	    .setOrderBy('created_at', 'descend')
	    .setLimit(100)
	    .build();
    return options;
};

Map.updateMarkers = function(json, mode) {
    Map.removeMarkers(Map.markers);
    Map.markers = Map.createMarkers(Map.map, json);
    Map.setIcon(Map.markers);
    Map.changeVisibleMarkersByMode(mode);
    Map.addEventToMakers(Map.markers);
};

Map.changeVisibleMarkersByMode = function(mode) {
    if (mode == "both") {
	Map.markers.forEach(function(m) { m.setVisible(true); });
    } else if (mode == "local") {
	Map.markers.forEach(function(m) {
	    if (m.isLocal()) {
		m.setVisible(true);
	    } else {
		m.setVisible(false);
	    }
	});
    } else if (mode == "tourism") {
	Map.markers.forEach(function(m) {
	    if (m.isLocal()) {
		m.setVisible(false);
	    } else {
		m.setVisible(true);
	    }
	});
    }
};

Map.setIcon = function(markers) {
    markers.forEach(function(m, i) {
	if (m.isLocal()) {
	    m.setIcon('img/local_32.png');
	} else {
	    m.setIcon('img/tourism_32.png');
	}
    });
};

Map.createMap = function(id, lat, lng, zoom) {
    var mapOptions = {
	center: new google.maps.LatLng(lat, lng),
	zoom: zoom
    };
    var map = new google.maps.Map(document.getElementById(id), mapOptions);
    return map;
};

Map.getMapBounds = function(map) {
    var mapBounds = map.getBounds();
    var sw = mapBounds.getSouthWest();
    var ne = mapBounds.getNorthEast();
    var bounds = {
	'lat1': sw.lat(), 'lng1': sw.lng(),
	'lat2': ne.lat(), 'lng2': ne.lng()
    };
    return bounds;
};

Map.createMarker = function(map, title, lat, lng, draggable) {
    var marker = new google.maps.Marker({
	position: new google.maps.LatLng(lat, lng),
	map: map,
	title : title,
	draggable: draggable
    });
    return marker;
};

Map.createMarkers = function(map, json) {
    var markers = [];
    for (var i = 0; i < json.length; i++) {
	var marker = Map.createMarker(map, json[i].title,
				      json[i].latitude, json[i].longitude, false);

	// data binding
	marker.data = json[i];

	marker.isLocal = function() {
	    var threshold = 50;
	    return this.data.localite > threshold;
	};

	marker.setVisible = function(visible) {
	    if (visible) {
		this.setMap(Map.map);
	    } else {
		this.setMap(null);
	    }
	};

	markers.push(marker);
    }
    return markers;
};

Map.removeMarkers = function(markers) {
    markers.forEach(function(marker, i) {
	marker.setMap(null);
    });
};

Map.addEventToMakers = function(markers) {
    markers.forEach(function(m, i) {
	google.maps.event.addListener(m, 'click', function() {
	    var content = Map.jsonToContent(this.data);
	    Map.infoWindow.setContent(content);
	    Map.infoWindow.open(this.getMap(), this);

	});
    });
};

Map.jsonToContent = function(json) {
    var title = json.title;
    var created_at = utils.utcToString(json.created_at);
    var posted_by = json.posted_by;
    var comment = json.comment;

    var content =
	    '
' +
	    '
' + title + '
' +
	    '
' + created_at + '
' +

        '詳細情報を見る'+
        '
'+
        '
' + posted_by + '
'+
        '
' + comment + '
'+
        '
'+
	    '
';

    return content;
};

function showMoreInfo(){
    $('#dialog').toggleClass('active');
    $('.gm-style-iw').toggleClass('active');
    $('.gm-style-iw').parent().toggleClass('modal');
}

<commit_msg>Remove unnecessary function<commit_after>var Map = {};
Map.markers = [];

Map.buildOption = function() {
    var bounds = Map.getMapBounds(Map.map);
    var options = new QueryOptionBuilder()
	    .setMapBounds(bounds.lat1, bounds.lng1,
			  bounds.lat2, bounds.lng2)
	    .setOrderBy('created_at', 'descend')
	    .setLimit(100)
	    .build();
    return options;
};

Map.updateMarkers = function(json, mode) {
    Map.removeMarkers(Map.markers);
    Map.markers = Map.createMarkers(Map.map, json);
    Map.setIcon(Map.markers);
    Map.changeVisibleMarkersByMode(mode);
    Map.addEventToMakers(Map.markers);
};

Map.changeVisibleMarkersByMode = function(mode) {
    if (mode == "both") {
	Map.markers.forEach(function(m) { m.setVisible(true); });
    } else if (mode == "local") {
	Map.markers.forEach(function(m) {
	    if (m.isLocal()) {
		m.setVisible(true);
	    } else {
		m.setVisible(false);
	    }
	});
    } else if (mode == "tourism") {
	Map.markers.forEach(function(m) {
	    if (m.isLocal()) {
		m.setVisible(false);
	    } else {
		m.setVisible(true);
	    }
	});
    }
};

Map.setIcon = function(markers) {
    markers.forEach(function(m, i) {
	if (m.isLocal()) {
	    m.setIcon('img/local_32.png');
	} else {
	    m.setIcon('img/tourism_32.png');
	}
    });
};

Map.createMap = function(id, lat, lng, zoom) {
    var mapOptions = {
	center: new google.maps.LatLng(lat, lng),
	zoom: zoom
    };
    var map = new google.maps.Map(document.getElementById(id), mapOptions);
    return map;
};

Map.getMapBounds = function(map) {
    var mapBounds = map.getBounds();
    var sw = mapBounds.getSouthWest();
    var ne = mapBounds.getNorthEast();
    var bounds = {
	'lat1': sw.lat(), 'lng1': sw.lng(),
	'lat2': ne.lat(), 'lng2': ne.lng()
    };
    return bounds;
};

Map.createMarker = function(map, title, lat, lng, draggable) {
    var marker = new google.maps.Marker({
	position: new google.maps.LatLng(lat, lng),
	map: map,
	title : title,
	draggable: draggable
    });
    return marker;
};

Map.createMarkers = function(map, json) {
    var markers = [];
    for (var i = 0; i < json.length; i++) {
	var marker = Map.createMarker(map, json[i].title,
				      json[i].latitude, json[i].longitude, false);

	// data binding
	marker.data = json[i];

	marker.isLocal = function() {
	    var threshold = 50;
	    return this.data.localite > threshold;
	};

	markers.push(marker);
    }
    return markers;
};

Map.removeMarkers = function(markers) {
    markers.forEach(function(marker, i) {
	marker.setMap(null);
    });
};

Map.addEventToMakers = function(markers) {
    markers.forEach(function(m, i) {
	google.maps.event.addListener(m, 'click', function() {
	    var content = Map.jsonToContent(this.data);
	    Map.infoWindow.setContent(content);
	    Map.infoWindow.open(this.getMap(), this);

	});
    });
};

Map.jsonToContent = function(json) {
    var title = json.title;
    var created_at = utils.utcToString(json.created_at);
    var posted_by = json.posted_by;
    var comment = json.comment;

    var content =
	    '
' +
	    '
' + title + '
' +
	    '
' + created_at + '
' +

        '詳細情報を見る'+
        '
'+
        '
' + posted_by + '
'+
        '
' + comment + '
'+
        '
'+
	    '
';

    return content;
};

function showMoreInfo(){
    $('#dialog').toggleClass('active');
    $('.gm-style-iw').toggleClass('active');
    $('.gm-style-iw').parent().toggleClass('modal');
}

<|endoftext|>


<commit_before>function hasCoordinates(event) {
  return (
    event.location !== "virtual" &&
    typeof event.location.coordinates === "object" &&
    typeof event.location.coordinates.latitude === "number" &&
    typeof event.location.coordinates.longitude === "number"
  );
}
var clusterStyleCache = {};
var clusterStyle = function(feature) {
  var size = feature.get("features").length;
  var style = clusterStyleCache[size];
  if (!style) {
    style = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 10,
        stroke: new ol.style.Stroke({
          color: "#fff"
        }),
        fill: new ol.style.Fill({
          color: "#3399CC"
        })
      }),
      text: new ol.style.Text({
        text: size.toString(),
        fill: new ol.style.Fill({
          color: "#fff"
        })
      })
    });
    clusterStyleCache[size] = style;
  }
  return style;
};

var extractFeaturesFromEventsLayer = function(feature) {
  var features = [feature.get(property)];
  return features;
};

var extractFeaturesFromClusterLayer = function(feature) {
  var features = feature.getProperties().features;
  return features;
};

var getPopupContent = function(features) {
  var content = "";
  if (features.length == 1) {
    var eventUrl = features[0].get("urls");
    var eventName = features[0].get("name");
    content +=
      '
' + eventName + "
";
  } else {
    content += "
";
    for (var i = 0; i < features.length; i++) {
      var eventUrl = features[i].get("urls");
      var eventName = features[i].get("name");
      content +=
        '' + eventName + "
";
    }
    content += "
";
  }
  return content;
};

var mapEventsDataToMapFormat = function(data) {
  return Object.values(data)
    .filter(hasCoordinates)
    .map(function(item) {
      return {
        timeZone: item.timezone,
        offset: item.utcOffset,
        country: item.location.country,
        urls: [item.url],
        name: item.title,
        coords: [
          item.location.coordinates.latitude,
          item.location.coordinates.longitude
        ],
        city: item.location.city
      };
    });
};

var flyTo = function(map, coord, duration, resolution) {
  duration = duration || 500;
  const view = map.getView();
  view.animate({ duration: duration, center: coord, zoom: 5 });
};

var translateToMapCoords = function(coords) {
  return ol.proj.transform(coords, "EPSG:4326", "EPSG:3857");
};

var toPoint = function(loc) {
  var coords = translateToMapCoords([loc.coords[1], loc.coords[0]]);
  return new ol.geom.Point(coords);
};

var eventIconStyle = new ol.style.Style({
  image: new ol.style.Icon({
    scale: 0.05,
    anchor: [0.5, 1],
    src: "/images/map-pin.png"
  })
});

var events = new ol.layer.Vector({
  source: new ol.source.Vector(),
  style: eventIconStyle
});

// a clustered source is configured with another vector source that it
// operates on
var clusterSource = new ol.source.Cluster({
  source: events.getSource()
});

// it needs a layer too
var clusterLayer = new ol.layer.Vector({
  source: clusterSource,
  style: clusterStyle
});

var addEventsToMap = function(locations) {
  events.getSource().clear();
  $.each(locations, function() {
    events.getSource().addFeature(
      new ol.Feature({
        geometry: toPoint(this),
        name: this.name,
        urls: this.urls
      })
    );
  });
};

var initEventsOnMap = function(pathToLocationsJson) {
  $.get(pathToLocationsJson, addEventsToMap);
};

$(function() {
  var styleCache = {};
  var countriesLayer = new ol.layer.Vector({
    source: new ol.source.Vector({
      format: new ol.format.GeoJSON(),
      url: "/geodata/countries.geojson"
    }),
    style: function(feature, resolution) {
      var text = resolution < 5000 ? feature.get("name") : "";
      if (!styleCache[text]) {
        styleCache[text] = [
          new ol.style.Style({
            fill: new ol.style.Fill({ color: "#57B26E" }),
            stroke: new ol.style.Stroke({ color: "#7EC486", width: 1 })
          })
        ];
      }
      return styleCache[text];
    }
  });

  var popupElem = document.getElementById("popup");

  var popup = new ol.Overlay({
    element: popupElem,
    positioning: "top-center",
    stopEvent: true,
    insertFirst: true
  });

  var map = new ol.Map({
    interactions: ol.interaction.defaults({
      mouseWheelZoom: false
    }),
    controls: ol.control.defaults({
      attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
        collapsible: false
      })
    }),
    layers: [countriesLayer, clusterLayer],
    overlays: [popup],
    target: document.getElementById("map"),
    view: new ol.View({
      center: translateToMapCoords([0, 40]),
      zoom: 1.2,
      minZoom: 1.2,
      maxZoom: 7,
      extent: [-17400000, -6040000, 19400000, 16200000]
    })
  });

  var geocoder = new Geocoder("nominatim", {
    provider: "photon",
    lang: "en",
    placeholder: "Search for ...",
    limit: 5,
    debug: true,
    autoComplete: true,
    keepOpen: false,
    preventDefault: true
  });
  map.addControl(geocoder);

  geocoder.on("addresschosen", function(evt) {
    flyTo(map, evt.coordinate);
  });

  // display popup on click
  map.on("click", function(evt) {
    $(popupElem).popover("destroy");
    var feature = map.forEachFeatureAtPixel(evt.pixel, function(
      feature,
      layer
    ) {
      if (layer == clusterLayer) return feature;
    });
    if (feature) {
      var geometry = feature.getGeometry();
      var coord = geometry.getCoordinates();
      var features = extractFeaturesFromClusterLayer(feature);
      var content = getPopupContent(features);
      popup.setPosition(coord);
      $(popupElem).popover({
        animation: false,
        placement: "top",
        html: true,
        title: "GDCR events",
        content: content
      });
      // workaround for already displayed popovers
      $("div.popover-content").text("GDCR events");

      $(popupElem).popover("show");
    }
  });

  // change mouse cursor when over marker
  $(map.getViewport()).on("mousemove", function(e) {
    var pixel = map.getEventPixel(e.originalEvent);
    var hit = map.forEachFeatureAtPixel(pixel, function(feature, layer) {
      return layer == clusterLayer;
    });
    if (hit) {
      map.getTarget().style.cursor = "pointer";
    } else {
      map.getTarget().style.cursor = "";
    }
  });
});
<commit_msg>Events: removing the use of title on the map<commit_after>function hasCoordinates(event) {
  return (
    event.location !== "virtual" &&
    typeof event.location.coordinates === "object" &&
    typeof event.location.coordinates.latitude === "number" &&
    typeof event.location.coordinates.longitude === "number"
  );
}
var clusterStyleCache = {};
var clusterStyle = function(feature) {
  var size = feature.get("features").length;
  var style = clusterStyleCache[size];
  if (!style) {
    style = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 10,
        stroke: new ol.style.Stroke({
          color: "#fff"
        }),
        fill: new ol.style.Fill({
          color: "#3399CC"
        })
      }),
      text: new ol.style.Text({
        text: size.toString(),
        fill: new ol.style.Fill({
          color: "#fff"
        })
      })
    });
    clusterStyleCache[size] = style;
  }
  return style;
};

var extractFeaturesFromEventsLayer = function(feature) {
  var features = [feature.get(property)];
  return features;
};

var extractFeaturesFromClusterLayer = function(feature) {
  var features = feature.getProperties().features;
  return features;
};

var getPopupContent = function(features) {
  var content = "";
  if (features.length == 1) {
    var eventUrl = features[0].get("urls");
    var eventName = features[0].get("name");
    content +=
      '
' + eventName + "
";
  } else {
    content += "
";
    for (var i = 0; i < features.length; i++) {
      var eventUrl = features[i].get("urls");
      var eventName = features[i].get("name");
      content +=
        '' + eventName + "
";
    }
    content += "
";
  }
  return content;
};

var mapEventsDataToMapFormat = function(data) {
  return Object.values(data)
    .filter(hasCoordinates)
    .map(function(item) {
      return {
        timeZone: item.timezone,
        offset: item.utcOffset,
        country: item.location.country,
        urls: [item.url],
        name: item.location.city + " - " + item.moderators.map(moderator => moderator.name).join(", "),
        coords: [
          item.location.coordinates.latitude,
          item.location.coordinates.longitude
        ],
        city: item.location.city
      };
    });
};

var flyTo = function(map, coord, duration, resolution) {
  duration = duration || 500;
  const view = map.getView();
  view.animate({ duration: duration, center: coord, zoom: 5 });
};

var translateToMapCoords = function(coords) {
  return ol.proj.transform(coords, "EPSG:4326", "EPSG:3857");
};

var toPoint = function(loc) {
  var coords = translateToMapCoords([loc.coords[1], loc.coords[0]]);
  return new ol.geom.Point(coords);
};

var eventIconStyle = new ol.style.Style({
  image: new ol.style.Icon({
    scale: 0.05,
    anchor: [0.5, 1],
    src: "/images/map-pin.png"
  })
});

var events = new ol.layer.Vector({
  source: new ol.source.Vector(),
  style: eventIconStyle
});

// a clustered source is configured with another vector source that it
// operates on
var clusterSource = new ol.source.Cluster({
  source: events.getSource()
});

// it needs a layer too
var clusterLayer = new ol.layer.Vector({
  source: clusterSource,
  style: clusterStyle
});

var addEventsToMap = function(locations) {
  events.getSource().clear();
  $.each(locations, function() {
    events.getSource().addFeature(
      new ol.Feature({
        geometry: toPoint(this),
        name: this.name,
        urls: this.urls
      })
    );
  });
};

var initEventsOnMap = function(pathToLocationsJson) {
  $.get(pathToLocationsJson, addEventsToMap);
};

$(function() {
  var styleCache = {};
  var countriesLayer = new ol.layer.Vector({
    source: new ol.source.Vector({
      format: new ol.format.GeoJSON(),
      url: "/geodata/countries.geojson"
    }),
    style: function(feature, resolution) {
      var text = resolution < 5000 ? feature.get("name") : "";
      if (!styleCache[text]) {
        styleCache[text] = [
          new ol.style.Style({
            fill: new ol.style.Fill({ color: "#57B26E" }),
            stroke: new ol.style.Stroke({ color: "#7EC486", width: 1 })
          })
        ];
      }
      return styleCache[text];
    }
  });

  var popupElem = document.getElementById("popup");

  var popup = new ol.Overlay({
    element: popupElem,
    positioning: "top-center",
    stopEvent: true,
    insertFirst: true
  });

  var map = new ol.Map({
    interactions: ol.interaction.defaults({
      mouseWheelZoom: false
    }),
    controls: ol.control.defaults({
      attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
        collapsible: false
      })
    }),
    layers: [countriesLayer, clusterLayer],
    overlays: [popup],
    target: document.getElementById("map"),
    view: new ol.View({
      center: translateToMapCoords([0, 40]),
      zoom: 1.2,
      minZoom: 1.2,
      maxZoom: 7,
      extent: [-17400000, -6040000, 19400000, 16200000]
    })
  });

  var geocoder = new Geocoder("nominatim", {
    provider: "photon",
    lang: "en",
    placeholder: "Search for ...",
    limit: 5,
    debug: true,
    autoComplete: true,
    keepOpen: false,
    preventDefault: true
  });
  map.addControl(geocoder);

  geocoder.on("addresschosen", function(evt) {
    flyTo(map, evt.coordinate);
  });

  // display popup on click
  map.on("click", function(evt) {
    $(popupElem).popover("destroy");
    var feature = map.forEachFeatureAtPixel(evt.pixel, function(
      feature,
      layer
    ) {
      if (layer == clusterLayer) return feature;
    });
    if (feature) {
      var geometry = feature.getGeometry();
      var coord = geometry.getCoordinates();
      var features = extractFeaturesFromClusterLayer(feature);
      var content = getPopupContent(features);
      popup.setPosition(coord);
      $(popupElem).popover({
        animation: false,
        placement: "top",
        html: true,
        title: "GDCR events",
        content: content
      });
      // workaround for already displayed popovers
      $("div.popover-content").text("GDCR events");

      $(popupElem).popover("show");
    }
  });

  // change mouse cursor when over marker
  $(map.getViewport()).on("mousemove", function(e) {
    var pixel = map.getEventPixel(e.originalEvent);
    var hit = map.forEachFeatureAtPixel(pixel, function(feature, layer) {
      return layer == clusterLayer;
    });
    if (hit) {
      map.getTarget().style.cursor = "pointer";
    } else {
      map.getTarget().style.cursor = "";
    }
  });
});
<|endoftext|>


<commit_before>/* getElement from html files */
var onbtn_markers = document.getElementById("btn_markers");
var onbtn_redcircles = document.getElementById("btn_redcircles");
var onbtn_orangecircles = document.getElementById("btn_orangecircles");
var onbtn_yellowcircles = document.getElementById("btn_yellowcircles");
var onbtn_all = document.getElementById("btn_all");

var mymap = L.map('mapid').setView([32.7157, -117.1611], 13);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
    			maxZoom: 18,
    			id: 'your.mapbox.project.id',
    			accessToken: 'your.mapbox.public.access.token'
			}).addTo(mymap);

/*Get user's location*/

mymap.locate({setView: true, maxZoom: 14});

/* Layer as group */
var redcircles_layer = new L.LayerGroup();
var orangecircles_layer = new L.LayerGroup();
var yellowcircles_layer = new L.LayerGroup();
var markers_layer = new L.LayerGroup();

/* Elements */
var marker = L.marker([32.8801, -117.2340]);
marker.bindPopup("Hello world!
I am a popup.").openPopup();
marker.addTo(markers_layer);

var redCircle = L.circle([32.8845, -117.2386], {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5,
    radius: 500
    }).addTo(mymap);

    redCircle.bindPopup("I am a circle.");
    redCircle.addTo(redcircles_layer);

var orangeCircle = L.circle([32.8700, -117.2310], {
    color: 'orange',
    fillColor: '#DC7633',
    fillOpacity: 0.5,
    radius: 500
    }).addTo(mymap);

    orangeCircle.bindPopup("I am a circle.");
    orangeCircle.addTo(orangecircles_layer);

var yellowCircle = L.circle([32.8545, -117.2563], {
    color: 'yellow',
    fillColor: '#FFC300',
    fillOpacity: 0.5,
    radius: 500
    }).addTo(mymap);

    yellowCircle.bindPopup("I am a circle.");
    yellowCircle.addTo(yellowcircles_layer);

/* Event functions */
onbtn_markers.onclick = function() {
    markers_layer.addTo(mymap);
    redcircles_layer.remove();
    orangecircles_layer.remove();
    yellowcircles_layer.remove();
}

onbtn_redcircles.onclick = function() {
    markers_layer.remove();
    orangecircles_layer.remove();
    yellowcircles_layer.remove();
    redcircles_layer.addTo(mymap);
}

onbtn_orangecircles.onclick = function() {
    markers_layer.remove();
    redcircles_layer.remove();
    yellowcircles_layer.remove();
    orangecircles_layer.addTo(mymap);
}

onbtn_yellowcircles.onclick = function() {
    markers_layer.remove();
    redcircles_layer.remove();
    orangecircles_layer.remove();
    yellowcircles_layer.addTo(mymap);
}

onbtn_all.onclick = function() {
    markers_layer.addTo(mymap);
    redcircles_layer.addTo(mymap);
    orangecircles_layer.addTo(mymap);
    yellowcircles_layer.addTo(mymap);
}

/*Zoom on click*/

redCircle.on('click', function(event){
    mymap.fitBounds(redCircle.getBounds());
});

orangeCircle.on('click', function(event){
    mymap.fitBounds(orangeCircle.getBounds());
});

yellowCircle.on('click', function(event){
    mymap.fitBounds(yellowCircle.getBounds());
});

<commit_msg>track user's location and add marker<commit_after>/* getElement from html files */
var onbtn_markers = document.getElementById("btn_markers");
var onbtn_redcircles = document.getElementById("btn_redcircles");
var onbtn_orangecircles = document.getElementById("btn_orangecircles");
var onbtn_yellowcircles = document.getElementById("btn_yellowcircles");
var onbtn_all = document.getElementById("btn_all");

var mymap = L.map('mapid').setView([32.7157, -117.1611], 13);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
    			maxZoom: 18,
    			id: 'your.mapbox.project.id',
    			accessToken: 'your.mapbox.public.access.token'
			}).addTo(mymap);

/* Layer as group */
var redcircles_layer = new L.LayerGroup();
var orangecircles_layer = new L.LayerGroup();
var yellowcircles_layer = new L.LayerGroup();
var markers_layer = new L.LayerGroup();

/*Get user's location*/

mymap.locate({setView: true, maxZoom: 14}).on('locationfound', function(e){
    var marker = L.marker([e.latitude, e.longitude]).addTo(mymap);
    marker.bindPopup("Hello world!
I am a popup.").openPopup();
    marker.addTo(markers_layer);
});

/* Elements */

var redCircle = L.circle([32.8845, -117.2386], {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5,
    radius: 500
    }).addTo(mymap);

    redCircle.bindPopup("I am a circle.");
    redCircle.addTo(redcircles_layer);

var orangeCircle = L.circle([32.8700, -117.2310], {
    color: 'orange',
    fillColor: '#DC7633',
    fillOpacity: 0.5,
    radius: 500
    }).addTo(mymap);

    orangeCircle.bindPopup("I am a circle.");
    orangeCircle.addTo(orangecircles_layer);

var yellowCircle = L.circle([32.8600, -117.2563], {
    color: 'yellow',
    fillColor: '#FFC300',
    fillOpacity: 0.5,
    radius: 500
    }).addTo(mymap);

    yellowCircle.bindPopup("I am a circle.");
    yellowCircle.addTo(yellowcircles_layer);

/* Event functions */
onbtn_markers.onclick = function() {
    markers_layer.addTo(mymap);
    redcircles_layer.remove();
    orangecircles_layer.remove();
    yellowcircles_layer.remove();
}

onbtn_redcircles.onclick = function() {
    markers_layer.remove();
    orangecircles_layer.remove();
    yellowcircles_layer.remove();
    redcircles_layer.addTo(mymap);
}

onbtn_orangecircles.onclick = function() {
    markers_layer.remove();
    redcircles_layer.remove();
    yellowcircles_layer.remove();
    orangecircles_layer.addTo(mymap);
}

onbtn_yellowcircles.onclick = function() {
    markers_layer.remove();
    redcircles_layer.remove();
    orangecircles_layer.remove();
    yellowcircles_layer.addTo(mymap);
}

onbtn_all.onclick = function() {
    markers_layer.addTo(mymap);
    redcircles_layer.addTo(mymap);
    orangecircles_layer.addTo(mymap);
    yellowcircles_layer.addTo(mymap);
}

/*Zoom on click*/

redCircle.on('click', function(event){
    mymap.fitBounds(redCircle.getBounds());
});

orangeCircle.on('click', function(event){
    mymap.fitBounds(orangeCircle.getBounds());
});

yellowCircle.on('click', function(event){
    mymap.fitBounds(yellowCircle.getBounds());
});

<|endoftext|>


<commit_before>/**
 * UCSC Xena Client
 * http://xena.ucsc.edu
 *
 * Navigation component.
 *
 * This is a light wrapper component around React Toolbox's AppBar component.
 */

import {GENESETS_VIEWER_URL} from "./views/GeneSetViewDialog";

// Core dependencies, components
var React = require('react');
var ReactDOM = require('react-dom');
var _ = require('./underscore_ext').default;
import AppBar from 'react-toolbox/lib/app_bar';
import Navigation from 'react-toolbox/lib/navigation';
import {ThemeProvider} from 'react-css-themr';
import Link from 'react-toolbox/lib/link';
import {Menu, MenuItem} from 'react-toolbox/lib/menu';
import {Button} from 'react-toolbox/lib/button';
var navTheme = require('./navTheme');
var BookmarkMenu = require('./views/BookmarkMenu');
var {servers: {localHub}} = require('./defaultServers');
import * as store from './hiddenOpts';
import Rx from './rx';

// Styles
var compStyles = require('./nav.module.css');

// Images
import logoSantaCruzImg from '../images/logoSantaCruz.png';
import logoSantaCruz2xImg from '../images/logoSantaCruz@2x.png';
import logoSantaCruz3xImg from '../images/logoSantaCruz@3x.png';

// Locals
var links = [
	{label: 'Data Sets', nav: 'datapages'},
	{label: 'Visualization', nav: 'heatmap'},
	{label: 'Transcripts', nav: 'transcripts'},
	{label: 'Data Hubs', nav: 'hub'},
	{label: 'View My Data', nav: 'datapages', params: {addHub: localHub, host: localHub}},
];

var helproot = 'https://ucsc-xena.gitbook.io/project/';

var helpLink = {
	href: helproot,
	label: 'Help',
	target: '_blank'
};

var geneSetsLink = {
    href: GENESETS_VIEWER_URL,
    label: 'Gene Sets',
    target: '_blank'
};

var pythonLink = {
    href: helproot + 'overview-of-features/accessing-data-through-python',
    label: 'Python',
    target: '_blank'
};

var publicationLink = {
	href: 'https://ucscxena.github.io',
	label: 'Publication Page',
	target: '_blank'
};

var active = (l, activeLink) => l.nav === activeLink;

class MoreToolsMenu extends React.Component {
	state = {
		anchorEl: null,
	};

	onClick = event => {
		this.setState({ anchorEl: event.currentTarget });
	};

	handleClose = () => {
		this.setState({ anchorEl: null });
	};

	handleSelect = (url) => {
		window.open(url);
	};

	render() {
		let {anchorEl} = this.state;

		return (

					<Button
						onClick={this.onClick}>
						More Tools
					</Button>
					<Menu position='topLeft'
						active={Boolean(anchorEl)}
						onHide={this.handleClose}
						className={compStyles.menu}
					>
						<MenuItem onClick={this.handleSelect.bind(this, publicationLink.href)} caption={publicationLink.label}/>
						<MenuItem onClick={this.handleSelect.bind(this, pythonLink.href)} caption={pythonLink.label}/>
						<MenuItem onClick={this.handleSelect.bind(this, geneSetsLink.href)} caption={geneSetsLink.label}/>
					 </Menu>

		);
	}
}

var hiddenOptsSub;
var hiddenOpts;
if (module.hot && module.hot.data) {
	hiddenOptsSub = module.hot.data.hiddenOptsSub;
	hiddenOpts = module.hot.data.hiddenOpts;
} else {
	hiddenOptsSub = new Rx.Subject();
	hiddenOpts = hiddenOptsSub.scan((acc, f) => f(acc), {}).shareReplay(1);
}

if (module.hot) {
	module.hot.dispose(data => {
		_.extend(data, {hiddenOptsSub, hiddenOpts});
	});
}

// XXX can we use connect instead?
hiddenOpts.subscribe(() => {}); // stupid rx hack for laziness

// caller API
// var initVal = hidden.create(key, label, {onChange, localStorage, default})
// hidden.create(key, label, {onClick})
// hidden.delete(key);

export var hidden = {
	create: (key, label, opts) => {
		if (opts.onChange) {
			opts = {...opts, value: store.get(key, opts.default, opts.local)};
		}
		hiddenOptsSub.next(ho => _.assoc(ho, key, {label, ...opts}));
		return opts.value;
	},
	delete: key => {
		hiddenOptsSub.next(ho => _.dissoc(ho, key));
	},
	update: key => {
		hiddenOptsSub.next(ho => {
			var v = !ho[key].value;
			ho[key].onChange(v);              // XXX side effect
			store.set(key, v, ho[key].local); // XXX side effect
			return _.assocIn(ho, [key, 'value'], v);
		});
	}
};

class XenaNav extends React.Component {
	state = {
		options: {}
	}
	componentDidMount() {
		this.sub = hiddenOpts.subscribe(options => {
			this.setState({options});
		});
		hidden.create('noga', 'Disable analytics', {
			onChange: () => { setTimeout(() => location.reload(), 100); },
			default: false,
			local: true
		});
	}
	componentWillUnmount() {
		hidden.delete('noga');
		this.sub.unsubscribe();
	}

	// have to early-bind id because MenuItem
	// events are broken in prod.
	onToggle = id => () => {
		hidden.update(id);
	}

	setMenuRef = ref => {
		this.menuRef = ref;
	}

	// RT MenuItem identity check fails in dev, leaving the
	// menu open after selection. Force it closed here.
	forceClose = cb => process.env.NODE_ENV === 'production' ? cb :
		(...args) => {
			this.menuRef.hide();
			return cb(...args);
		}

	hiddenMenu(items) {
		return (
			<Menu innerRef={this.setMenuRef} theme={{menu: compStyles.menu}} position='topLeft'>
				{_.map(items, ({label, onClick, onChange, value}, key) =>
					onChange ? <MenuItem key={key}
						className={value ? compStyles.selected : ''}
						onClick={this.forceClose(this.onToggle(key))} caption={label}/> :
					<MenuItem key={key} onClick={this.forceClose(onClick)} caption={label}/>)}
			</Menu>);
	}

	onClick = ev => {
		if (ev.shiftKey && ev.ctrlKey) {
			ev.preventDefault();
			this.menuRef.show();
		}
	}
	render() {
		var {isPublic, activeLink, getState, onImport} = this.props;
		var routes = _.map(links, l => {
			var {nav, params, ...others} = l,
			onClick = nav ? () => this.props.onNavigate(nav, params) : undefined;
			return {...others, onClick, active: active(l, activeLink)};
		});
		var logoSrcSet = `${logoSantaCruz2xImg} 2x, ${logoSantaCruz3xImg} 3x`;
		return (
			<AppBar className={compStyles.NavAppBar}>

				{this.hiddenMenu(this.state.options)}
				<Navigation type="horizontal" routes={routes}>
					{getState ? <BookmarkMenu isPublic={isPublic} getState={getState} onImport={onImport}/> : null}
					<Link {...helpLink} />
					<MoreToolsMenu/>
				</Navigation>
			</AppBar>
		);
	}
}

class ThemedNav extends React.Component {
	render() {
		return (
			<ThemeProvider theme={navTheme}>
				<XenaNav {...this.props}/>
			</ThemeProvider>);
	}
}

var nav = document.getElementById('navMenuMain');

var comp;

var render = props => comp = ReactDOM.render(<ThemedNav {...props} />, nav);

export var addMenuItem = item => {
	comp.setState(state => ({items: state.items.append([item])}));
};

export var removeItem = item => {
	comp.setState(state => ({items: state.items.append([item])}));
};

export default render;
<commit_msg>Use os-specific meta key for hidden menu<commit_after>/**
 * UCSC Xena Client
 * http://xena.ucsc.edu
 *
 * Navigation component.
 *
 * This is a light wrapper component around React Toolbox's AppBar component.
 */

import {GENESETS_VIEWER_URL} from "./views/GeneSetViewDialog";

// Core dependencies, components
var React = require('react');
var ReactDOM = require('react-dom');
var _ = require('./underscore_ext').default;
import AppBar from 'react-toolbox/lib/app_bar';
import Navigation from 'react-toolbox/lib/navigation';
import {ThemeProvider} from 'react-css-themr';
import Link from 'react-toolbox/lib/link';
import {Menu, MenuItem} from 'react-toolbox/lib/menu';
import {Button} from 'react-toolbox/lib/button';
var navTheme = require('./navTheme');
var BookmarkMenu = require('./views/BookmarkMenu');
var {servers: {localHub}} = require('./defaultServers');
import * as store from './hiddenOpts';
import Rx from './rx';
var meta = require('./meta');

// Styles
var compStyles = require('./nav.module.css');

// Images
import logoSantaCruzImg from '../images/logoSantaCruz.png';
import logoSantaCruz2xImg from '../images/logoSantaCruz@2x.png';
import logoSantaCruz3xImg from '../images/logoSantaCruz@3x.png';

// Locals
var links = [
	{label: 'Data Sets', nav: 'datapages'},
	{label: 'Visualization', nav: 'heatmap'},
	{label: 'Transcripts', nav: 'transcripts'},
	{label: 'Data Hubs', nav: 'hub'},
	{label: 'View My Data', nav: 'datapages', params: {addHub: localHub, host: localHub}},
];

var helproot = 'https://ucsc-xena.gitbook.io/project/';

var helpLink = {
	href: helproot,
	label: 'Help',
	target: '_blank'
};

var geneSetsLink = {
    href: GENESETS_VIEWER_URL,
    label: 'Gene Sets',
    target: '_blank'
};

var pythonLink = {
    href: helproot + 'overview-of-features/accessing-data-through-python',
    label: 'Python',
    target: '_blank'
};

var publicationLink = {
	href: 'https://ucscxena.github.io',
	label: 'Publication Page',
	target: '_blank'
};

var active = (l, activeLink) => l.nav === activeLink;

class MoreToolsMenu extends React.Component {
	state = {
		anchorEl: null,
	};

	onClick = event => {
		this.setState({ anchorEl: event.currentTarget });
	};

	handleClose = () => {
		this.setState({ anchorEl: null });
	};

	handleSelect = (url) => {
		window.open(url);
	};

	render() {
		let {anchorEl} = this.state;

		return (

					<Button
						onClick={this.onClick}>
						More Tools
					</Button>
					<Menu position='topLeft'
						active={Boolean(anchorEl)}
						onHide={this.handleClose}
						className={compStyles.menu}
					>
						<MenuItem onClick={this.handleSelect.bind(this, publicationLink.href)} caption={publicationLink.label}/>
						<MenuItem onClick={this.handleSelect.bind(this, pythonLink.href)} caption={pythonLink.label}/>
						<MenuItem onClick={this.handleSelect.bind(this, geneSetsLink.href)} caption={geneSetsLink.label}/>
					 </Menu>

		);
	}
}

var hiddenOptsSub;
var hiddenOpts;
if (module.hot && module.hot.data) {
	hiddenOptsSub = module.hot.data.hiddenOptsSub;
	hiddenOpts = module.hot.data.hiddenOpts;
} else {
	hiddenOptsSub = new Rx.Subject();
	hiddenOpts = hiddenOptsSub.scan((acc, f) => f(acc), {}).shareReplay(1);
}

if (module.hot) {
	module.hot.dispose(data => {
		_.extend(data, {hiddenOptsSub, hiddenOpts});
	});
}

// XXX can we use connect instead?
hiddenOpts.subscribe(() => {}); // stupid rx hack for laziness

// caller API
// var initVal = hidden.create(key, label, {onChange, localStorage, default})
// hidden.create(key, label, {onClick})
// hidden.delete(key);

export var hidden = {
	create: (key, label, opts) => {
		if (opts.onChange) {
			opts = {...opts, value: store.get(key, opts.default, opts.local)};
		}
		hiddenOptsSub.next(ho => _.assoc(ho, key, {label, ...opts}));
		return opts.value;
	},
	delete: key => {
		hiddenOptsSub.next(ho => _.dissoc(ho, key));
	},
	update: key => {
		hiddenOptsSub.next(ho => {
			var v = !ho[key].value;
			ho[key].onChange(v);              // XXX side effect
			store.set(key, v, ho[key].local); // XXX side effect
			return _.assocIn(ho, [key, 'value'], v);
		});
	}
};

class XenaNav extends React.Component {
	state = {
		options: {}
	}
	componentDidMount() {
		this.sub = hiddenOpts.subscribe(options => {
			this.setState({options});
		});
		hidden.create('noga', 'Disable analytics', {
			onChange: () => { setTimeout(() => location.reload(), 100); },
			default: false,
			local: true
		});
	}
	componentWillUnmount() {
		hidden.delete('noga');
		this.sub.unsubscribe();
	}

	// have to early-bind id because MenuItem
	// events are broken in prod.
	onToggle = id => () => {
		hidden.update(id);
	}

	setMenuRef = ref => {
		this.menuRef = ref;
	}

	// RT MenuItem identity check fails in dev, leaving the
	// menu open after selection. Force it closed here.
	forceClose = cb => process.env.NODE_ENV === 'production' ? cb :
		(...args) => {
			this.menuRef.hide();
			return cb(...args);
		}

	hiddenMenu(items) {
		return (
			<Menu innerRef={this.setMenuRef} theme={{menu: compStyles.menu}} position='topLeft'>
				{_.map(items, ({label, onClick, onChange, value}, key) =>
					onChange ? <MenuItem key={key}
						className={value ? compStyles.selected : ''}
						onClick={this.forceClose(this.onToggle(key))} caption={label}/> :
					<MenuItem key={key} onClick={this.forceClose(onClick)} caption={label}/>)}
			</Menu>);
	}

	onClick = ev => {
		if (ev.shiftKey && ev[meta.key]) {
			ev.preventDefault();
			this.menuRef.show();
		}
	}
	render() {
		var {isPublic, activeLink, getState, onImport} = this.props;
		var routes = _.map(links, l => {
			var {nav, params, ...others} = l,
			onClick = nav ? () => this.props.onNavigate(nav, params) : undefined;
			return {...others, onClick, active: active(l, activeLink)};
		});
		var logoSrcSet = `${logoSantaCruz2xImg} 2x, ${logoSantaCruz3xImg} 3x`;
		return (
			<AppBar className={compStyles.NavAppBar}>

				{this.hiddenMenu(this.state.options)}
				<Navigation type="horizontal" routes={routes}>
					{getState ? <BookmarkMenu isPublic={isPublic} getState={getState} onImport={onImport}/> : null}
					<Link {...helpLink} />
					<MoreToolsMenu/>
				</Navigation>
			</AppBar>
		);
	}
}

class ThemedNav extends React.Component {
	render() {
		return (
			<ThemeProvider theme={navTheme}>
				<XenaNav {...this.props}/>
			</ThemeProvider>);
	}
}

var nav = document.getElementById('navMenuMain');

var comp;

var render = props => comp = ReactDOM.render(<ThemedNav {...props} />, nav);

export var addMenuItem = item => {
	comp.setState(state => ({items: state.items.append([item])}));
};

export var removeItem = item => {
	comp.setState(state => ({items: state.items.append([item])}));
};

export default render;
<|endoftext|>