<commit_before>/* imageCover | fullScreen | typeScale | middlize | ResImg | epicGrid | Paul Browne | GNU License | 2015 */
function helperize(){var a=window.innerWidth,b=document.getElementsByTagName("body")[0].style;for(b.fontSize=a/375+15+"px",b.lineHeight=a/8e3+1.4,a=document.querySelectorAll(".fullscreen, .fullheight"),b=0;b<a.length;b++)a[b].style.height=window.innerHeight+"px";for(a=document.querySelectorAll(".middlize, .vmid"),b=0;b<a.length;b++)a[b].style.top=(a[b].parentNode.offsetHeight-a[b].offsetHeight)/2+"px",a[b].parentNode.style.position="relative";for(a=document.getElementsByClassName("icovr"),b=0;b<a.length;b++){var c=a[b].offsetWidth,d=a[b].offsetHeight,e=c/d,f=a[b].children[0].naturalWidth,g=a[b].children[0].naturalHeight,h=f/g,i=a[b].children[0].style;e>=h&&(i.width="100%",i.height="auto",i.top=(d-g/(f/c))/2+"px",i.left=0),h>e&&(i.width="auto",i.height="100%",i.top=0,i.left=(c-f/(g/d))/2+"px")}}function ResImg(){var a=document.getElementsByTagName("body")[0].getElementsByTagName("img");if(0!==a.length){var b;b=a[0].hasAttribute?function(a,b){return a.hasAttribute(b)}:function(a,b){return null!==a.getAttribute(b)};for(var c=window.devicePixelRatio?window.devicePixelRatio:1,d=0;d<a.length;d++){var e=a[d],f=c*e.parentNode.offsetWidth;if(b(e,"data-src")){for(var g=b(e,"data-src-base")?e.getAttribute("data-src-base"):"",h=e.getAttribute("data-src").split(","),i=0;i<h.length;i++){var j,k=h[i].replace(":","||").split("||");if(j=k[0],k=k[1],-1!==j.indexOf("<"))if(j=j.split("<"),h[i-1]){var l=h[i-1].split(/:(.+)/)[0].split("<");j=f<=j[1]&&f>l[1]}else j=f<=j[1];else j=j.split(">"),h[i+1]?(l=h[i+1].split(/:(.+)/)[0].split(">"),j=f>=j[1]&&f<l[1]):j=f>=j[1];if(j){f=1===(-1!==k.indexOf("//")?1:0)?k:g+k,e.src!==f&&e.setAttribute("src",f);break}}a[d].addEventListener("load",helperize)}}}}function epicGrid(){for(var a=window.innerWidth,b=document.getElementsByTagName("*"),c=document.getElementsByClassName("egcf"),d=document.querySelectorAll('[class*="-col-"],[class*="-center-"]');0<c.length;)c[0].parentNode.removeChild(c[0]);for(c=0;c<d.length;++c){var e=d[c].style;e["float"]="none",e.width="100%",e.marginLeft=0,e.marginRight=0,e.position="relative",e.display="block"}for(d=0;d<b.length;++d)for(var c=b[d].children,f=e=0;f<c.length;++f){var g=RegExp("h-col-|h-center-","g"),h=RegExp("l-col-|l-center-","g"),i=RegExp("m-col-|m-center-","g"),j=RegExp("s-col-|s-center-","g"),k="x";a>320&&j.test(c[f].className)&&(k="s"),a>656&&i.test(c[f].className)&&(k="m"),a>1024&&h.test(c[f].className)&&(k="l"),a>1440&&g.test(c[f].className)&&(k="h");var j=new RegExp(k+"-center-\\d+-\\d+","g"),g=new RegExp(k+"-left-\\d+-\\d+","g"),h=new RegExp(k+"-right-\\d+-\\d+","g"),l=new RegExp(k+"-offset-\\d+-\\d+","g"),m=new RegExp(k+"-col-\\d+-\\d+|"+k+"-offset-\\d+-\\d+","g"),n=new RegExp(k+"-col-\\d+-\\d+|"+k+"-center-\\d+-\\d+","g"),i=new RegExp(k+"-left-\\d+-\\d+|"+k+"-right-\\d+-\\d+","g");if(!new RegExp(k+"-col-\\d+-\\d+","g").test(c[f].className)||g.test(c[f].className)||h.test(c[f].className)||(k=c[f].className.match(m).toString().match(/\d+/g),1<=Math.round(1e4*e)/1e4&&(e+=-1),0==Math.round(1e4*e)/1e4&&(c[f].className+=" eg-first"),e=2<k.length?e+(k[0]/k[1]+k[2]/k[3]):e+k[0]/k[1],0==Math.round(1e4*e)/1e4%1&&(k=document.createElement("br"),k.style.clear="both",k.className="egcf",c[f].parentNode.insertBefore(k,c[f].nextSibling))),n.test(c[f].className))for(k=c[f].className.match(n).toString().match(/\d+/g),c[f].style.width=k[0]/k[1]*(104-4*k[1])+4*k[0]-4+"%",c[f].style.marginLeft="4%",c[f].style["float"]="left",c[f].className.match(/eg\-first/g)&&(c[f].style.marginLeft=0),c[f].className.match(j)&&(c[f].style["float"]="none",c[f].style.marginLeft="auto",c[f].style.marginRight="auto"),c[f].className.match(l)&&(k=c[f].className.match(l).toString().match(/\d+/g),k=k[0]/k[1]*(104-4*k[1])+4*k[0]-4,c[f].style.marginLeft=k+8+"%",c[f].className.match(/eg\-first/g)&&(c[f].style.marginLeft=k+4+"%")),i.test(c[f].className)&&(i=c[f].className.match(i).toString().match(/\d+/g),i=i[0]/i[1]*(104-4*i[1])+4*i[0]-4,k=parseFloat(c[f].parentNode.style.width),c[f].className.match(g)&&(c[f].style.marginLeft=100/k*-(i+4)+"%",c[f].style.marginRight="4%",c[f].style["float"]="left"),c[f].className.match(h)&&(c[f].style["float"]="right",c[f].style.marginRight=100/k*-(i+4)+"%",c[f].style.marginLeft="4%")),g=document.getElementsByClassName("eg-first"),h=0;h<g.length;++h)g[0].className=g[0].className.replace(/\seg-first/,"")}a=new CustomEvent("eg-ready"),window.dispatchEvent(a)}window.addEventListener("resize",epicGrid),window.addEventListener("eg-ready",helperize),window.addEventListener("eg-ready",ResImg);
<commit_msg>Update compiled.js<commit_after>/*! imageCover | fullScreen | typeScale | middlize | ResImg | epicGrid | Paul Browne | GNU License | 2015 */
!function(){function a(a,b){var c=[window.innerWidth];return onresize=function(){var d=window.innerWidth,e=c.length;c.push(d),c[e]!==c[e-1]&&(clearTimeout(b),b=setTimeout(a,250))},a}helperize=function(){var a=window.innerWidth,b=document.getElementsByTagName("body")[0].style;for(b.fontSize=a/500+14+"px",b.lineHeight=a/8e3+1.4,a=document.querySelectorAll(".fullscreen, .fullheight"),b=0;b<a.length;b++)a[b].style.height=window.innerHeight+"px";for(a=document.querySelectorAll(".middlize, .vmid"),b=0;b<a.length;b++)a[b].style.top=(a[b].parentNode.offsetHeight-a[b].offsetHeight)/2+"px",a[b].parentNode.style.position="relative";for(a=document.getElementsByClassName("icovr"),b=0;b<a.length;b++){var c=a[b].offsetWidth,d=a[b].offsetHeight,e=c/d,f=a[b].children[0].naturalWidth,g=a[b].children[0].naturalHeight,h=f/g,i=a[b].children[0].style;e>=h&&(i.width="100%",i.height="auto",i.top=(d-g/(f/c))/2+"px",i.left=0),h>e&&(i.width="auto",i.height="100%",i.top=0,i.left=(c-f/(g/d))/2+"px")}},ResImg=function(){var a=document.getElementsByTagName("body")[0].getElementsByTagName("img");if(0!==a.length){var b;b=a[0].hasAttribute?function(a,b){return a.hasAttribute(b)}:function(a,b){return null!==a.getAttribute(b)};for(var c=window.devicePixelRatio?window.devicePixelRatio:1,d=0;d<a.length;d++){var e=a[d],f=c*e.parentNode.offsetWidth;if(b(e,"data-src")){for(var g=b(e,"data-src-base")?e.getAttribute("data-src-base"):"",h=e.getAttribute("data-src").split(","),i=0;i<h.length;i++){var j,k=h[i].replace(":","||").split("||");if(j=k[0],k=k[1],-1!==j.indexOf("<"))if(j=j.split("<"),h[i-1]){var l=h[i-1].split(/:(.+)/)[0].split("<");j=f<=j[1]&&f>l[1]}else j=f<=j[1];else j=j.split(">"),h[i+1]?(l=h[i+1].split(/:(.+)/)[0].split(">"),j=f>=j[1]&&f<l[1]):j=f>=j[1];if(j){f=1===(-1!==k.indexOf("//")?1:0)?k:g+k,e.src!==f&&e.setAttribute("src",f);break}}a[d].addEventListener("load",helperize)}}}},epicGrid=function(){for(var a=window.innerWidth,b=document.getElementsByTagName("*"),c=document.getElementsByClassName("egcf"),d=document.querySelectorAll('[class*="-col-"],[class*="-center-"]');0<c.length;)c[0].parentNode.removeChild(c[0]);for(c=0;c<d.length;++c){var e=d[c].style;e["float"]="none",e.width="100%",e.marginLeft=0,e.marginRight=0,e.position="relative",e.display="block"}for(d=0;d<b.length;++d)for(var c=b[d].children,f=e=0;f<c.length;++f){var g=RegExp("h-col-|h-center-","g"),h=RegExp("l-col-|l-center-","g"),i=RegExp("m-col-|m-center-","g"),j=RegExp("s-col-|s-center-","g"),k="x";a>320&&j.test(c[f].className)&&(k="s"),a>656&&i.test(c[f].className)&&(k="m"),a>1024&&h.test(c[f].className)&&(k="l"),a>1440&&g.test(c[f].className)&&(k="h");var j=new RegExp(k+"-center-\\d+-\\d+","g"),g=new RegExp(k+"-left-\\d+-\\d+","g"),h=new RegExp(k+"-right-\\d+-\\d+","g"),l=new RegExp(k+"-offset-\\d+-\\d+","g"),m=new RegExp(k+"-col-\\d+-\\d+|"+k+"-offset-\\d+-\\d+","g"),n=new RegExp(k+"-col-\\d+-\\d+|"+k+"-center-\\d+-\\d+","g"),i=new RegExp(k+"-left-\\d+-\\d+|"+k+"-right-\\d+-\\d+","g");if(!new RegExp(k+"-col-\\d+-\\d+","g").test(c[f].className)||g.test(c[f].className)||h.test(c[f].className)||(k=c[f].className.match(m).toString().match(/\d+/g),1<=Math.round(1e4*e)/1e4&&(e+=-1),0==Math.round(1e4*e)/1e4&&(c[f].className+=" eg-first"),e=2<k.length?e+(k[0]/k[1]+k[2]/k[3]):e+k[0]/k[1],0==Math.round(1e4*e)/1e4%1&&(k=document.createElement("br"),k.style.clear="both",k.className="egcf",c[f].parentNode.insertBefore(k,c[f].nextSibling))),n.test(c[f].className))for(k=c[f].className.match(n).toString().match(/\d+/g),c[f].style.width=k[0]/k[1]*(104-4*k[1])+4*k[0]-4+"%",c[f].style.marginLeft="4%",c[f].style["float"]="left",c[f].className.match(/eg\-first/g)&&(c[f].style.marginLeft=0),c[f].className.match(j)&&(c[f].style["float"]="none",c[f].style.marginLeft="auto",c[f].style.marginRight="auto"),c[f].className.match(l)&&(k=c[f].className.match(l).toString().match(/\d+/g),k=k[0]/k[1]*(104-4*k[1])+4*k[0]-4,c[f].style.marginLeft=k+8+"%",c[f].className.match(/eg\-first/g)&&(c[f].style.marginLeft=k+4+"%")),i.test(c[f].className)&&(i=c[f].className.match(i).toString().match(/\d+/g),i=i[0]/i[1]*(104-4*i[1])+4*i[0]-4,k=parseFloat(c[f].parentNode.style.width),c[f].className.match(g)&&(c[f].style.marginLeft=100/k*-(i+4)+"%",c[f].style.marginRight="4%",c[f].style["float"]="left"),c[f].className.match(h)&&(c[f].style["float"]="right",c[f].style.marginRight=100/k*-(i+4)+"%",c[f].style.marginLeft="4%")),g=document.getElementsByClassName("eg-first"),h=0;h<g.length;++h)g[0].className=g[0].className.replace(/\seg-first/,"")}ResImg(),helperize()},a(function(){epicGrid()})}();

/* === add your scripts here === */

<|endoftext|>


<commit_before>var map;
var epsg4326, epsg900913;
var lat = parseFloat(geoip_latitude());
var lon = parseFloat(geoip_longitude());
var zoom = 16;
var layer;
var layers = {};
var places = [];
var mapnik;

//var allAmenities = 'arts-centre atm audiologist baby-hatch bank bar bench bicycle-parking bicycle-rental biergarten brothel bureau-de-change bus-station cafe car-rental car-sharing cinema clock coast-guard college community-centre courthouse crematorium drinking-water embassy emergency-phone fast-food ferry-terminal fire-hydrant fire-station fountain fuel grave-yard grit-bin hospital hunting-stand kindergarten library marketplace milk-dispenser nightclub parking pharmacy place-of-worship police post-box post-office prison pub public-building recycling register-office restaurant sauna school stripclub studio taxi telephone theatre toilets townhall university vending-machine veterinary waste-basket waste-disposal subway'.split(' ');
var amenitiesGrouped = {
  'Nahverkehr': ['subway', 'light_rail', 'tram_stop', 'bus_stop', 'ferry_terminal'],
  'Essen & Trinken': ['fast_food', 'restaurant', 'biergarten', 'cafe', 'bar', 'pub'],
  'Freizeit': ['cinema', 'arts_centre', 'nightclub', 'sauna', 'theatre'],
  'Geld': ['bank', 'atm', 'bureau_de_change'],
  'Post': ['post_box', 'post_office'],
  'Botschaften & Behörden': ['embassy', 'courthouse', 'police', 'fire_station', 'public_building', 'register_office', 'townhall', 'community_centre'],
  'Medizin': ['hospital', 'pharmacy'],
  'Auto & Fahrrad': ['fuel', 'car_rental', 'car_sharing', 'parking', 'bicycle_parking', 'bicycle_rental'],
  'Kinder & Bildung': ['kindergarten', 'school', 'college', 'university', 'library'],
  'Sonstiges': ['marketplace', 'telephone', 'toilets', 'grave_yard', 'place_of_worship']
}

var amenities = [];
$.each(amenitiesGrouped, function(i, group) {
  amenities = $.merge(amenities, group);
});

var typeVisibilities = {};
$.each(amenities, function(i, type) {
  typeVisibilities[type] = { display: 'none' };
});
$.each(object_types, function(i, type) {
  // alert(type);
  typeVisibilities[type].display = 'block';
});

var states = {
  yes: true,
  no: true,
  limited: true,
  unknown: true
};

var counts = { yes: 0, no: 0, limited: 0, unknown: 0 };

function drawmap() {
  OpenLayers.Lang.setCode('de');

  epsg900913 = new OpenLayers.Projection("EPSG:900913");
  epsg4326 = new OpenLayers.Projection("EPSG:4326");
  map = new OpenLayers.Map('map', {
    projection: epsg900913,
    displayProjection: epsg4326,
    controls: [
      new OpenLayers.Control.MouseDefaults(),
      new OpenLayers.Control.KeyboardDefaults(),
      new OpenLayers.Control.PanZoomBar(),
      new OpenLayers.Control.MouseToolbar(),
      // new OpenLayers.Control.LayerSwitcher()
    ],
    maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
    numZoomLevels: 10,
    maxResolution: 156543,
    units: 'meters'
  });

  mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
  map.addLayer(mapnik);

  checkForPermalink();
  jumpTo(lon, lat, zoom);

  createLayer();
  createDraggableLayer();

  map.events.register('moveend', null, loadPlaces);
  setTimeout(loadPlaces, 1000);
}

function onCompleteDrag(feature)
{
  if(feature)
  {
    // replace coordinate values in feature attributes
    var pointX = feature.geometry.x;
    var pointY = feature.geometry.y;
    alert(pointY);
  }
};

function toggleLayers(type, show) {
  var visibility = false;
  visibility = typeof(show) == 'undefined' ? !$('.' + type).parent().hasClass('visible') : show;
  $('.' + type).parent().removeClass(visibility ? 'hidden' : 'visible').addClass(visibility ? 'visible' : 'hidden');
  typeVisibilities[type].display = visibility ? 'block' : 'none';
  add_or_remove_type_from_object_types(type, visibility);
  showStates();
  return false;
}

function add_or_remove_type_from_object_types(type, add){

  if(add == true){
    if(!object_types_contains(type)){
      object_types.push(type);
      loadPlaces();
    }
  }else{
    if(object_types_contains(type) == true){
      index = object_types.indexOf(type);
      object_types.splice(index,1);
    }
  }
}

function object_types_contains(type){
  return (object_types.indexOf(type) != -1)
}

function mapBBOX() {
  var box = map.getExtent().clone();
  var latlon = map.getLonLatFromViewPortPx({ x: 380, y: 80 });
  box.left = latlon.lon;
  box.top = latlon.lat;
  latlon = map.getLonLatFromViewPortPx({ x: $(document).width() - 80, y: $(document).height() - 80 });
  box.right = latlon.lon;
  box.bottom = latlon.lat;
  return box.transform(map.getProjectionObject(), epsg4326);
}

drawmap();

function eachState(f) {
  $.each(['unknown', 'no', 'limited', 'yes'], function(i, state) { f(state); });
}

function showStates() {
  $.each(layers, function(state, layer) {
    layer.styleMap.addUniqueValueRules("default", "type", typeVisibilities);
    layer.redraw();
    layer.setVisibility(states[state]);
  });
}

$(function() {
  $('.wheelchair input').click(function() {
    var state = this.id.replace(/wheelchair-/, '');
    states[state] = this.checked;
    showStates();
  });
});

function loadPlaces() {
  $('#spinner').show();
  counts = { yes: 0, no: 0, limited: 0, unknown: 0 };

  var bbox = mapBBOX().toBBOX();
  $.getJSON('/nodes?bbox=' + bbox + '&object_types=' + object_types.join(','), function(data) {
    var features = { yes: [], no: [], limited: [], unknown: [] };
    $.each(data, function(i, place) {
      if (place.type) {
        var lonLat = lonLatToMercator({ lon: place.lon * 1.0, lat: place.lat * 1.0 });
        var point = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
        var feature = new OpenLayers.Feature.Vector(point,place);
        feature.attributes.icon = iconForType[place.type];
        try {
          features[place.wheelchair].push(feature);
        }
        catch (e) {}
        counts[place.wheelchair]++;
        places[place.id] = place;
        $('*[data-osm-id=' + place.id + ']').addClass(place.type);
      }
    });
    $.each(layers, function(state, layer) {
      layer.removeFeatures(layer.features);
      layer.addFeatures(features[state]);
      layer.redraw();
      $('.wheelchair .' + state + ' span').html(counts[state]);
    });
    showStates();
    $('#spinner').hide();
  });
}

function markerStyle(){
  return new OpenLayers.StyleMap({
    externalGraphic: "/images/icons/${icon}.png",
    graphicWidth: 16,
    graphicHeight: 16,
    backgroundGraphic: "/images/marker-${wheelchair}.png",
    backgroundWidth: 36,
    backgroundHeight: 28,
    backgroundXOffset: -12,
    backgroundYOffset: -26,
    graphicXOffset: -8,
    graphicYOffset: -22,
    graphicZIndex: 10,
    backgroundGraphicZIndex: 10
  });
}

function needleStyle(){
  return new OpenLayers.StyleMap({
    externalGraphic: "/images/icons/${icon}.png",
    graphicWidth: 16,
    graphicHeight: 16,
    backgroundGraphic: "/images/marker-${wheelchair}.png",
    backgroundWidth: 36,
    backgroundHeight: 28,
    backgroundXOffset: -12,
    backgroundYOffset: -26,
    graphicXOffset: -8,
    graphicYOffset: -22,
    graphicZIndex: 10,
    backgroundGraphicZIndex: 10,
    cursor: 'move'
  });
}

function createLayer() {
  var style = markerStyle();

  eachState(function(state) {
    var strategy = new OpenLayers.Strategy.Cluster({distance: 15, threshold: 2});
    layers[state] = new OpenLayers.Layer.Vector(
      "Places " + state,
      {
        styleMap: style,
        rendererOptions: { yOrdering: true },
        visibility: states[state],
        strategies: [strategy]
      }
    );

    map.addLayer(layers[state]);
    selectControl = new OpenLayers.Control.SelectFeature(layers[state],
      { onSelect:openPopup, onUnselect:closePopup });
    map.addControl(selectControl);
    selectControl.activate();

  });
}

function createDraggableLayer() {
  var style = needleStyle();
  var draggable_layer = new OpenLayers.Layer.Vector(
    "Draggable",
    {
      styleMap: style,
      rendererOptions: { yOrdering: true },
      visibility: true,
    });
    map.addLayer(draggable_layer);
    createDragControl(draggable_layer);
    // addPin(draggable_layer);
}

function createDragControl(layer){
   var dragControl = new OpenLayers.Control.DragFeature(
    layer,
    {'onComplete': onCompleteDrag}
    );
    map.addControl(dragControl);
    dragControl.activate();
}

function addPin(layer){
  var features = [];
  layer.removeFeatures(layer.features);
  var center = centerCoordinates();
  var lonLat = lonLatToMercator({ lon: center.lon * 1.0, lat: center.lat * 1.0 });
  var point = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);

  var feature = new OpenLayers.Feature.Vector(point);
  feature.attributes.icon = iconForType['sfsdf'];
  feature.attributes.type = 'Subway';
  feature.attributes.wheelchair = 'no';
  feature.attributes.name = 'Neuer Ort';
  feature.attributes.tags = {"railway":"subway","osm_id":"46095762","ref":"U5","construction":"yes","synthesized_name":"Subway"};
  feature.attributes.osmid = 1234;
  features.push(feature);
  layer.addFeatures(features);
  layer.redraw();
}

function lonLatToMercator(ll) {
  // var lon = ll.lon * 20037508.34 / 180;
  var lon = ll.lon * 111319.49077777777;
  // var lat = Math.log(Math.tan((90 + ll.lat) * Math.PI / 360)) / (Math.PI / 180);
  var lat = Math.log(Math.tan((90 + ll.lat) * 0.008726646259971648)) / (0.017453292519943295);
  // lat = lat * 20037508.34 / 180;
  lat = lat * 111319.49077777777;
  return new OpenLayers.LonLat(lon, lat);
}

function centerCoordinates() {
  return map.getCenter().clone().transform(map.getProjectionObject(), epsg4326);
}

function permalink() {
  var ll = centerCoordinates();
  var query = '#lat=' + ll.lat + '&lon=' + ll.lon + '&zoom=' + map.zoom;
  return location.protocol + '//' + location.host + '/' + query;
}

$(function() {
  $('a[data-show]').click(function() {
    $($(this).attr('data-show')).fadeIn();
    return false;
  });
  $('a[data-hide]').click(function() {
    $($(this).attr('data-hide')).fadeOut();
    return false;
  });
});

function $w(string) {
  return string.split(' ');
}
<commit_msg>moved all markers into on single layer<commit_after>var map;
var epsg4326, epsg900913;
var lat = parseFloat(geoip_latitude());
var lon = parseFloat(geoip_longitude());
var zoom = 16;
var places = [];
var mapnik;
var places;
var draggable;

//var allAmenities = 'arts-centre atm audiologist baby-hatch bank bar bench bicycle-parking bicycle-rental biergarten brothel bureau-de-change bus-station cafe car-rental car-sharing cinema clock coast-guard college community-centre courthouse crematorium drinking-water embassy emergency-phone fast-food ferry-terminal fire-hydrant fire-station fountain fuel grave-yard grit-bin hospital hunting-stand kindergarten library marketplace milk-dispenser nightclub parking pharmacy place-of-worship police post-box post-office prison pub public-building recycling register-office restaurant sauna school stripclub studio taxi telephone theatre toilets townhall university vending-machine veterinary waste-basket waste-disposal subway'.split(' ');
var amenitiesGrouped = {
  'Nahverkehr': ['subway', 'light_rail', 'tram_stop', 'bus_stop', 'ferry_terminal'],
  'Essen & Trinken': ['fast_food', 'restaurant', 'biergarten', 'cafe', 'bar', 'pub'],
  'Freizeit': ['cinema', 'arts_centre', 'nightclub', 'sauna', 'theatre'],
  'Geld': ['bank', 'atm', 'bureau_de_change'],
  'Post': ['post_box', 'post_office'],
  'Botschaften & Behörden': ['embassy', 'courthouse', 'police', 'fire_station', 'public_building', 'register_office', 'townhall', 'community_centre'],
  'Medizin': ['hospital', 'pharmacy'],
  'Auto & Fahrrad': ['fuel', 'car_rental', 'car_sharing', 'parking', 'bicycle_parking', 'bicycle_rental'],
  'Kinder & Bildung': ['kindergarten', 'school', 'college', 'university', 'library'],
  'Sonstiges': ['marketplace', 'telephone', 'toilets', 'grave_yard', 'place_of_worship']
}

var amenities = [];
$.each(amenitiesGrouped, function(i, group) {
  amenities = $.merge(amenities, group);
});

var typeVisibilities = {};
$.each(amenities, function(i, type) {
  typeVisibilities[type] = { display: 'none' };
});
$.each(object_types, function(i, type) {
  // alert(type);
  typeVisibilities[type].display = 'block';
});

var states = {
  yes: true,
  no: true,
  limited: true,
  unknown: true
};

var counts = { yes: 0, no: 0, limited: 0, unknown: 0 };

function markerLayer(name){
  $.each(map.layers, function(i, layer){
    if(layer.name == name) {
      alert('Match: ' + layer.name);
      return i;
    }
  });
}

function drawmap() {
  OpenLayers.Lang.setCode('de');

  epsg900913 = new OpenLayers.Projection("EPSG:900913");
  epsg4326 = new OpenLayers.Projection("EPSG:4326");
  map = new OpenLayers.Map('map', {
    projection: epsg900913,
    displayProjection: epsg4326,
    controls: [
      new OpenLayers.Control.MouseDefaults(),
      new OpenLayers.Control.KeyboardDefaults(),
      new OpenLayers.Control.PanZoomBar(),
      new OpenLayers.Control.MouseToolbar(),
      // new OpenLayers.Control.LayerSwitcher()

    ],
    maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
    numZoomLevels: 10,
    maxResolution: 156543,
    units: 'meters'
  });

  mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
  map.addLayer(mapnik);

  checkForPermalink();
  jumpTo(lon, lat, zoom);

  createLayer();
  // createDraggableLayer();

  map.events.register('moveend', null, loadPlaces);
  setTimeout(loadPlaces, 1000);
}

function onCompleteDrag(feature)
{
  if(feature)
  {
    // replace coordinate values in feature attributes
    var pointX = feature.geometry.x;
    var pointY = feature.geometry.y;
    alert(pointY);
  }
};

function toggleLayers(type, show) {
  var visibility = false;
  visibility = typeof(show) == 'undefined' ? !$('.' + type).parent().hasClass('visible') : show;
  $('.' + type).parent().removeClass(visibility ? 'hidden' : 'visible').addClass(visibility ? 'visible' : 'hidden');
  typeVisibilities[type].display = visibility ? 'block' : 'none';
  add_or_remove_type_from_object_types(type, visibility);
  showStates();
  return false;
}

function add_or_remove_type_from_object_types(type, add){

  if(add == true){
    if(!object_types_contains(type)){
      object_types.push(type);
      loadPlaces();
    }
  }else{
    if(object_types_contains(type) == true){
      index = object_types.indexOf(type);
      object_types.splice(index,1);
    }
  }
}

function object_types_contains(type){
  return (object_types.indexOf(type) != -1)
}

function mapBBOX() {
  var box = map.getExtent().clone();
  var latlon = map.getLonLatFromViewPortPx({ x: 380, y: 80 });
  box.left = latlon.lon;
  box.top = latlon.lat;
  latlon = map.getLonLatFromViewPortPx({ x: $(document).width() - 80, y: $(document).height() - 80 });
  box.right = latlon.lon;
  box.bottom = latlon.lat;
  return box.transform(map.getProjectionObject(), epsg4326);
}

drawmap();

function eachState(f) {
  $.each(['unknown', 'no', 'limited', 'yes'], function(i, state) { f(state); });
}

function showStates() {
  places.styleMap.addUniqueValueRules("default", "type", typeVisibilities);
  places.redraw();
  places.setVisibility(true);
}

$(function() {
  $('.wheelchair input').click(function() {
    var state = this.id.replace(/wheelchair-/, '');
    states[state] = this.checked;
    showStates();
  });
});

function loadPlaces() {
  $('#spinner').show();
  counts = { yes: 0, no: 0, limited: 0, unknown: 0 };

  var bbox = mapBBOX().toBBOX();
  $.getJSON('/nodes?bbox=' + bbox + '&object_types=' + object_types.join(','), function(data) {
    var features = [];
    $.each(data, function(i, place) {
      if (place.type) {
        var lonLat = lonLatToMercator({ lon: place.lon * 1.0, lat: place.lat * 1.0 });
        var point = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
        var feature = new OpenLayers.Feature.Vector(point,place);
        feature.attributes.icon = iconForType[place.type];
        try {
          features.push(feature);
        }
        catch (e) {}
        counts[place.wheelchair]++;
        places[place.id] = place;
        $('*[data-osm-id=' + place.id + ']').addClass(place.type);
      }
    });
    places.removeFeatures(places.features);
    places.addFeatures(features);
    places.redraw();
    $.each(states, function(i,state){
      $('.wheelchair .' + state + ' span').html(counts[state]);
    });
    showStates();
    $('#spinner').hide();
  });
}

function markerStyle(){
  return new OpenLayers.StyleMap({
    externalGraphic: "/images/icons/${icon}.png",
    graphicWidth: 16,
    graphicHeight: 16,
    backgroundGraphic: "/images/marker-${wheelchair}.png",
    backgroundWidth: 36,
    backgroundHeight: 28,
    backgroundXOffset: -12,
    backgroundYOffset: -26,
    graphicXOffset: -8,
    graphicYOffset: -22,
    graphicZIndex: 10,
    backgroundGraphicZIndex: 10
  });
}

function needleStyle(){
  return new OpenLayers.StyleMap({
    externalGraphic: "/images/icons/${icon}.png",
    graphicWidth: 16,
    graphicHeight: 16,
    backgroundGraphic: "/images/marker-${wheelchair}.png",
    backgroundWidth: 36,
    backgroundHeight: 28,
    backgroundXOffset: -12,
    backgroundYOffset: -26,
    graphicXOffset: -8,
    graphicYOffset: -22,
    graphicZIndex: 10,
    backgroundGraphicZIndex: 10,
    cursor: 'move'
  });
}

function createLayer() {
  var style = markerStyle();

  var strategy = new OpenLayers.Strategy.Cluster({distance: 15, threshold: 2});
  places = new OpenLayers.Layer.Vector(
    "Places ",
    {
      styleMap: style,
      rendererOptions: { yOrdering: true },
      visibility: true,
      strategies: [strategy]
    });

  map.addLayer(places);
  selectControl = new OpenLayers.Control.SelectFeature(places,
    { onSelect:openPopup, onUnselect:closePopup });
  map.addControl(selectControl);
  selectControl.activate();
}

function createDraggableLayer() {
  var style = needleStyle();
  var draggable_layer = new OpenLayers.Layer.Vector(
    "Draggable",
    {
      styleMap: style,
      rendererOptions: { yOrdering: true },
      visibility: true,
    });
    map.addLayer(draggable_layer);
    createDragControl(draggable_layer);
    // addPin(draggable_layer);
}

function createDragControl(layer){
   var dragControl = new OpenLayers.Control.DragFeature(
    layer,
    {'onComplete': onCompleteDrag}
    );
    map.addControl(dragControl);
    dragControl.activate();
}

function addPin(layer){
  var features = [];
  layer.removeFeatures(layer.features);
  var center = centerCoordinates();
  var lonLat = lonLatToMercator({ lon: center.lon * 1.0, lat: center.lat * 1.0 });
  var point = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);

  var feature = new OpenLayers.Feature.Vector(point);
  feature.attributes.icon = iconForType['sfsdf'];
  feature.attributes.type = 'Subway';
  feature.attributes.wheelchair = 'no';
  feature.attributes.name = 'Neuer Ort';
  feature.attributes.tags = {"railway":"subway","osm_id":"46095762","ref":"U5","construction":"yes","synthesized_name":"Subway"};
  feature.attributes.osmid = 1234;
  features.push(feature);
  layer.addFeatures(features);
  layer.redraw();
}

function lonLatToMercator(ll) {
  // var lon = ll.lon * 20037508.34 / 180;
  var lon = ll.lon * 111319.49077777777;
  // var lat = Math.log(Math.tan((90 + ll.lat) * Math.PI / 360)) / (Math.PI / 180);
  var lat = Math.log(Math.tan((90 + ll.lat) * 0.008726646259971648)) / (0.017453292519943295);
  // lat = lat * 20037508.34 / 180;
  lat = lat * 111319.49077777777;
  return new OpenLayers.LonLat(lon, lat);
}

function centerCoordinates() {
  return map.getCenter().clone().transform(map.getProjectionObject(), epsg4326);
}

function permalink() {
  var ll = centerCoordinates();
  var query = '#lat=' + ll.lat + '&lon=' + ll.lon + '&zoom=' + map.zoom;
  return location.protocol + '//' + location.host + '/' + query;
}

$(function() {
  $('a[data-show]').click(function() {
    $($(this).attr('data-show')).fadeIn();
    return false;
  });
  $('a[data-hide]').click(function() {
    $($(this).attr('data-hide')).fadeOut();
    return false;
  });
});

function $w(string) {
  return string.split(' ');
}
<|endoftext|>


<commit_before>import { Component } from 'react'
import PropTypes from 'prop-types'
import { Flex, Box } from 'grid-styled'

import Layout from '../components/Layout'
import Page from '../components/Page'
import MediumPost from '../components/MediumPost'
import { goldenRatio } from '../components/dimensions'

import 'isomorphic-fetch'

export default class Writings extends Component {
  static propTypes = {
    url: PropTypes.object.isRequired,
    posts: PropTypes.arrayOf(
      PropTypes.shape({
        title: PropTypes.string.isRequired,
        url: PropTypes.string.isRequired,
        image: PropTypes.string.isRequired,
      }).isRequired
    ).isRequired
  }

  static async getInitialProps() {
    return {
      posts: [
        {
          title: 'Testing with Jest: 15 Awesome Tips and Tricks',
          url:
            'https://medium.com/@stipsan/testing-with-jest-15-awesome-tips-and-tricks-42150ec4c262',
          image:
            'https://cdn-images-1.medium.com/max/2000/1*YwGUh_DRzHKRLEjHspRIcQ.jpeg',
        },
        {
          title: 'Best kept Jest secret: Testing only changed files with coverage reports',
          url:
            'https://medium.com/@stipsan/best-kept-jest-secret-testing-only-changed-files-with-coverage-reports-3affc8b4d30f',
          image:
            'https://cdn-images-1.medium.com/max/1600/1*mOZlz7BwrFkGIruaRTg5yA.png',
        },
      ],
    }
  }

  render() {
    return (
      <Layout url={this.props.url}>
        <Page>
          <Flex wrap>
            {this.props.posts.map(({ title, url, image }, i) =>
              <Box
                key={url}
                p={1}
                width={[
                  1,
                  i % 4 === 1 || i % 4 === 2 ? 1 - goldenRatio : goldenRatio,
                ]}
              >
                <MediumPost title={title} url={url} image={image} />
              </Box>
            )}
          </Flex>
        </Page>
      </Layout>
    )
  }
}
<commit_msg>Update index.js<commit_after>import { Component } from 'react'
import PropTypes from 'prop-types'
import { Flex, Box } from 'grid-styled'

import Layout from '../components/Layout'
import Page from '../components/Page'
import MediumPost from '../components/MediumPost'
import { goldenRatio } from '../components/dimensions'

import 'isomorphic-fetch'

export default class Writings extends Component {
  static propTypes = {
    url: PropTypes.object.isRequired,
    posts: PropTypes.arrayOf(
      PropTypes.shape({
        title: PropTypes.string.isRequired,
        url: PropTypes.string.isRequired,
        image: PropTypes.string.isRequired,
      }).isRequired
    ).isRequired
  }

  static async getInitialProps() {
    return {
      posts: [
        {
          title: 'Best kept Jest secret: Testing only changed files with coverage reports',
          url:
            'https://medium.com/@stipsan/best-kept-jest-secret-testing-only-changed-files-with-coverage-reports-3affc8b4d30f',
          image:
            'https://cdn-images-1.medium.com/max/1600/1*mOZlz7BwrFkGIruaRTg5yA.png',
        },
        {
          title: 'Testing with Jest: 15 Awesome Tips and Tricks',
          url:
            'https://medium.com/@stipsan/testing-with-jest-15-awesome-tips-and-tricks-42150ec4c262',
          image:
            'https://cdn-images-1.medium.com/max/2000/1*YwGUh_DRzHKRLEjHspRIcQ.jpeg',
        },
      ],
    }
  }

  render() {
    return (
      <Layout url={this.props.url}>
        <Page>
          <Flex wrap>
            {this.props.posts.map(({ title, url, image }, i) =>
              <Box
                key={url}
                p={1}
                width={[
                  1,
                  i % 4 === 1 || i % 4 === 2 ? 1 - goldenRatio : goldenRatio,
                ]}
              >
                <MediumPost title={title} url={url} image={image} />
              </Box>
            )}
          </Flex>
        </Page>
      </Layout>
    )
  }
}
<|endoftext|>


<commit_before>define(module, (exports, require) => {

  var qp = require('qp-utility');
  var log = require('qp-library/log');

  qp.make(exports, {

    ns: 'qp-library/postgres',

    connection: null,

    select: function(config) {
      config.select = true;
      this.execute(this.prepare(config), this.handlers(config));
    },

    select_all: function(config) {
      config.select = true;
      config.select_all = true;
      this.execute(this.prepare(config), this.handlers(config));
    },

    insert: function(config) {
      config.insert = true;
      this.execute(this.prepare(config), this.handlers(config));
    },

    update: function(config) {
      config.update = true;
      this.execute(this.prepare(config), this.handlers(config));
    },

    delete: function(config) {
      config.delete = true;
      this.execute(this.prepare(config), this.handlers(config));
    },

    execute: function(cmd, handlers) {
      this.connection.query(cmd, (error, pg_result) => {
        if ((cmd.select && !cmd.select_all) && pg_result.rowCount > 1) {
          error = new Error('Select cannot return multiple rows');
        }

        if (error) {
          log(cmd.text);
          log.error(error);
          qp.call(handlers.failure, error);
          qp.call(handlers.done, error);
        } else if (cmd.non_query) {
          var rows = pg_result.rows;
          let result = { row_count: pg_result.rowCount, rows: rows };
          if (cmd.insert) result.id = rows[0].id;
          if (cmd.delete) result.count = rows[0].count;
          qp.call(handlers.success, result);
          qp.call(handlers.done, null, result);
        } else if (cmd.select) {
          let result = cmd.select_all ? pg_result.rows : pg_result.rows[0];
          qp.call(handlers.success, result);
          qp.call(handlers.done, null, result);
        }
      });
    },

    handlers: function(config) {
      return { success: config.success, failure: config.failure, done: config.done };
    },

    prepare: function(config) {
      var text = qp.is(config.text, 'array') ? config.text.join(' ') : config.text;
      var cmd = {
        name: config.name || null,
        non_query: config.insert || config.update || config.delete,
        select: config.select || false,
        select_all: config.select_all || false,
        insert: config.insert || false,
        update: config.update || false,
        delete: config.delete || false,
        text: text,
        values: config.values || []
      };
      return cmd;
    }

  });

});
<commit_msg>postgres; guard code<commit_after>define(module, (exports, require) => {

  var qp = require('qp-utility');
  var log = require('qp-library/log');

  qp.make(exports, {

    ns: 'qp-library/postgres',

    connection: null,

    select: function(config) {
      config.select = true;
      this.execute(this.prepare(config), this.handlers(config));
    },

    select_all: function(config) {
      config.select = true;
      config.select_all = true;
      this.execute(this.prepare(config), this.handlers(config));
    },

    insert: function(config) {
      config.insert = true;
      this.execute(this.prepare(config), this.handlers(config));
    },

    update: function(config) {
      config.update = true;
      this.execute(this.prepare(config), this.handlers(config));
    },

    delete: function(config) {
      config.delete = true;
      this.execute(this.prepare(config), this.handlers(config));
    },

    execute: function(cmd, handlers) {
      this.connection.query(cmd, (error, pg_result) => {
        if ((cmd.select && !cmd.select_all) && pg_result && pg_result.rowCount > 1) {
          error = new Error('Select cannot return multiple rows');
        }

        if (error) {
          log(cmd.text);
          log.error(error);
          qp.call(handlers.failure, error);
          qp.call(handlers.done, error);
        } else if (cmd.non_query) {
          var rows = pg_result.rows;
          let result = { row_count: pg_result.rowCount, rows: rows };
          if (cmd.insert) result.id = rows[0].id;
          if (cmd.delete) result.count = rows[0].count;
          qp.call(handlers.success, result);
          qp.call(handlers.done, null, result);
        } else if (cmd.select) {
          let result = cmd.select_all ? pg_result.rows : pg_result.rows[0];
          qp.call(handlers.success, result);
          qp.call(handlers.done, null, result);
        }
      });
    },

    handlers: function(config) {
      return { success: config.success, failure: config.failure, done: config.done };
    },

    prepare: function(config) {
      var text = qp.is(config.text, 'array') ? config.text.join(' ') : config.text;
      var cmd = {
        name: config.name || null,
        non_query: config.insert || config.update || config.delete,
        select: config.select || false,
        select_all: config.select_all || false,
        insert: config.insert || false,
        update: config.update || false,
        delete: config.delete || false,
        text: text,
        values: config.values || []
      };
      return cmd;
    }

  });

});
<|endoftext|>


<commit_before>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(document).ready(function() {
  alert("hello world!");
});
<commit_msg>jquery hello world pt2 (p137)<commit_after>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(document).ready(function() {
  $("#notice").text("hello world!");
});
<|endoftext|>


<commit_before>'use strict';

angular.module('aux.controllers', []).
  controller('AppCtrl', function ($scope, persona, $rootScope, $http, $location) {
    var YOUTUBE = /(youtube.com(?:\/#)?\/watch\?)|(youtu\.be\/[A-Z0-9-_]+)/i;
    var VIMEO = /vimeo.com\/[0-9]+/i;

    $rootScope.isVimeo = function (post) {
      return (post && !!post.content.urls[0].url.match(VIMEO));
    };

    $rootScope.isYoutube = function (post) {
      return (post && !!post.content.urls[0].url.match(YOUTUBE));
    };

    $rootScope.isSecondary = false;

    $rootScope.isAuthenticated = false;

    if (localStorage.getItem('personaEmail')) {
      $rootScope.isAuthenticated = true;

      if (!$rootScope.email) {
        $http({
          url: '/login',
          method: 'GET'
        }).success(function (data) {

          $rootScope.email = data.email;
        }).error(function (data) {

          console.log('Login failed because ' + data);
        });
      }
    }

    $rootScope.getVideoId = function (p) {
      // Try youtube's long url
      var url = p.content.urls[0].url.split('watch?v=')[1];

      if ($scope.isVimeo(p)) {

        url = p.content.urls[0].url.split('/');
        p.videoId = url[url.length - 1];
      } else if (!url) {

        url = p.content.urls[0].url.split('/');
        p.videoId = url[url.length - 1].split('&list')[0];
      } else {

        url = url.split('&list')[0];
        p.videoId = url;
      }

      return p.videoId;
    };

    $rootScope.login = function () {
      persona.login();
    };

    $rootScope.logout = function () {
      persona.logout();
    }
  }).
  controller('HomeCtrl', function ($scope, $http, $routeParams, $rootScope) {
    var POST_LIMIT = 12;

    $rootScope.isSecondary = false;
    $scope.posts = [];

    $scope.secondaryPage = function () {
      console.log(parseInt($routeParams.page, 10))
      return parseInt($routeParams.page, 10) > 0;
    };

    var getPreview = function (p) {
      var url = $rootScope.getVideoId(p);

      if ($rootScope.isVimeo(p)) {
        $http.jsonp('http://vimeo.com/api/v2/video/' + p.videoId + '.json?callback=JSON_CALLBACK'
        ).success(function (data) {
          p.src = data[0].thumbnail_large;
        }).error(function (err, data) {
          console.log('could not get vimeo image');
        });
      } else {
        p.src = 'http://img.youtube.com/vi/' + p.videoId + '/0.jpg';
      }

      return p;
    };

    socket.on('connect', function () {
      socket.on('feed', function (data) {
        data.post = getPreview(data.post);

        $scope.$apply(function () {
          $scope.posts.unshift(data.post);

          if ($scope.posts.length > 12) {
            $scope.posts.pop();
          }
        });
      });
    });

    $http({
      url: '/api/recent?page=' + ($routeParams.page || 0),
      method: 'GET'
    }).success(function (data) {
      $scope.posts = data.posts;
      $scope.prev = data.prev;
      $scope.next = data.next;

      $scope.posts.forEach(function (p) {
        p = getPreview(p);
      });

    }).error(function (data) {

      console.log('could not retrieve posts');
    });
  }).
  controller('MediaCtrl', function ($scope, $http, $routeParams, $rootScope, $sce, $location) {
    $scope.id = parseInt($routeParams.id, 10);

    $scope.trustSrc = function (src) {
      return $sce.trustAsResourceUrl(src);
    }

    $scope.deletePost = function (post) {
      $http({
        url: '/api/v/' + post.id,
        method: 'DELETE'
      }).success(function (data) {

        $location.path('/');
      }).error(function (data) {

        console.log('could not delete');
      });
    };

    $rootScope.isSecondary = true;

    $http({
      url: '/api/v/' + $scope.id,
      method: 'GET'
    }).success(function (data) {
      var url = $rootScope.getVideoId(data.post);

      $scope.title = data.post.content.urls[0].title;
      $scope.data = data;
    }).error(function (data) {

      console.log('id not found');
    });
  }).
  controller('ErrorLoginCtrl', function ($rootScope) {
    $rootScope.isAuthenticated = false;
    $rootScope.email = null;
  });
<commit_msg>fixed pagination default<commit_after>'use strict';

angular.module('aux.controllers', []).
  controller('AppCtrl', function ($scope, persona, $rootScope, $http, $location) {
    var YOUTUBE = /(youtube.com(?:\/#)?\/watch\?)|(youtu\.be\/[A-Z0-9-_]+)/i;
    var VIMEO = /vimeo.com\/[0-9]+/i;

    $rootScope.isVimeo = function (post) {
      return (post && !!post.content.urls[0].url.match(VIMEO));
    };

    $rootScope.isYoutube = function (post) {
      return (post && !!post.content.urls[0].url.match(YOUTUBE));
    };

    $rootScope.isSecondary = false;

    $rootScope.isAuthenticated = false;

    if (localStorage.getItem('personaEmail')) {
      $rootScope.isAuthenticated = true;

      if (!$rootScope.email) {
        $http({
          url: '/login',
          method: 'GET'
        }).success(function (data) {

          $rootScope.email = data.email;
        }).error(function (data) {

          console.log('Login failed because ' + data);
        });
      }
    }

    $rootScope.getVideoId = function (p) {
      // Try youtube's long url
      var url = p.content.urls[0].url.split('watch?v=')[1];

      if ($scope.isVimeo(p)) {

        url = p.content.urls[0].url.split('/');
        p.videoId = url[url.length - 1];
      } else if (!url) {

        url = p.content.urls[0].url.split('/');
        p.videoId = url[url.length - 1].split('&list')[0];
      } else {

        url = url.split('&list')[0];
        p.videoId = url;
      }

      return p.videoId;
    };

    $rootScope.login = function () {
      persona.login();
    };

    $rootScope.logout = function () {
      persona.logout();
    }
  }).
  controller('HomeCtrl', function ($scope, $http, $routeParams, $rootScope) {
    var POST_LIMIT = 12;

    $rootScope.isSecondary = false;
    $scope.posts = [];

    $scope.secondaryPage = function () {
      if (isNaN(parseInt($routeParams.page, 10))) {
        return 0;
      } else {
        return parseInt($routeParams.page, 10) > 0;
      }
    };

    var getPreview = function (p) {
      var url = $rootScope.getVideoId(p);

      if ($rootScope.isVimeo(p)) {
        $http.jsonp('http://vimeo.com/api/v2/video/' + p.videoId + '.json?callback=JSON_CALLBACK'
        ).success(function (data) {
          p.src = data[0].thumbnail_large;
        }).error(function (err, data) {
          console.log('could not get vimeo image');
        });
      } else {
        p.src = 'http://img.youtube.com/vi/' + p.videoId + '/0.jpg';
      }

      return p;
    };

    socket.on('connect', function () {
      socket.on('feed', function (data) {
        data.post = getPreview(data.post);

        $scope.$apply(function () {
          $scope.posts.unshift(data.post);

          if ($scope.posts.length > 12) {
            $scope.posts.pop();
          }
        });
      });
    });

    $http({
      url: '/api/recent?page=' + ($routeParams.page || 0),
      method: 'GET'
    }).success(function (data) {
      $scope.posts = data.posts;
      $scope.prev = data.prev;
      $scope.next = data.next;

      $scope.posts.forEach(function (p) {
        p = getPreview(p);
      });

    }).error(function (data) {

      console.log('could not retrieve posts');
    });
  }).
  controller('MediaCtrl', function ($scope, $http, $routeParams, $rootScope, $sce, $location) {
    $scope.id = parseInt($routeParams.id, 10);

    $scope.trustSrc = function (src) {
      return $sce.trustAsResourceUrl(src);
    }

    $scope.deletePost = function (post) {
      $http({
        url: '/api/v/' + post.id,
        method: 'DELETE'
      }).success(function (data) {

        $location.path('/');
      }).error(function (data) {

        console.log('could not delete');
      });
    };

    $rootScope.isSecondary = true;

    $http({
      url: '/api/v/' + $scope.id,
      method: 'GET'
    }).success(function (data) {
      var url = $rootScope.getVideoId(data.post);

      $scope.title = data.post.content.urls[0].title;
      $scope.data = data;
    }).error(function (data) {

      console.log('id not found');
    });
  }).
  controller('ErrorLoginCtrl', function ($rootScope) {
    $rootScope.isAuthenticated = false;
    $rootScope.email = null;
  });
<|endoftext|>


<commit_before>// register the directive with your app module
var app = angular.module('ddApp', ['lvl.services', 'ngAnimate', 'ui.bootstrap', 'rzModule']);

// function referenced by the drop target
app.controller('ddController', ['$scope', '$uibModal', '$log','$http', function($scope, $uibModal, $log, $http){

    $scope.rotateTile = function(x,y){
        // If the tile doesn't exists yet
        if(!$scope.tiles[x+','+y+','+$scope.z])
            return;
        $scope.tiles[x+','+y+','+$scope.z].rot += 90;
        if($scope.tiles[x+','+y+','+$scope.z].rot >= 360)
            $scope.tiles[x+','+y+','+$scope.z].rot = 0;
    }

    $scope.numberOfDropTiles = 0;
    $scope.height = 4;
    $scope.width = 4;
    $scope.length = 7;
    $scope.name = "";
    $scope.range = function(n){
        arr = [];
        for (var i=0; i < n; i++) {
            arr.push(i);
        }
        return arr;
    }

    $http.get("dummy.json").then(function(response){
        var tiles = {};
        for(var i = 0; i < response.data.length; i++){
            tiles[response.data[i]._id] = response.data[i];
        }
        $scope.tileBox = tiles;
        console.log("Huhu" , $scope.tileBox);
    }, function(response){
        console.log("Error: " + response.statusText);
    });

    $scope.z = 0;
    $scope.tiles = {};

    $scope.tiles = {
        "2,2,0": {
            "image": "tiles/tile-7.png",
            "rot": 0,
            "tileType": "5708b98454deddcd27756aaa",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "2,3,0": {
            "image": "tiles/tile-13.png",
            "rot": 90,
            "tileType": "5708b9f354deddcd27756ab0",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "2,4,0": {
            "image": "tiles/tile-24.png",
            "rot": 180,
            "tileType": "5708bb0154deddcd27756abb",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "1,4,0": {
            "image": "tiles/tile-22.png",
            "rot": 270,
            "tileType": "5708bacf54deddcd27756ab9",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "1,3,0": {
            "image": "tiles/tile-16.png",
            "rot": 270,
            "tileType": "5708ba4d54deddcd27756ab3",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "0,3,0": {
            "image": "tiles/tile-12.png",
            "rot": 270,
            "tileType": "5708b9d254deddcd27756aaf",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "0,1,0": {
            "image": "tiles/tile-6.png",
            "rot": 270,
            "tileType": "5708b97754deddcd27756aa9",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "0,2,0": {
            "image": "tiles/tile-0.png",
            "rot": 90,
            "tileType": "5708b8ff54deddcd27756aa3",
            "items": {
                "obstacles": 1,
                "speedbumps": 0
            }
        },
        "1,1,0": {
            "image": "tiles/tile-19.png",
            "rot": 0,
            "tileType": "5708ba9f54deddcd27756ab6",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "2,1,0": {
            "image": "tiles/tile-3.png",
            "rot": 0,
            "tileType": "5708b93754deddcd27756aa6",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "1,2,0": {
            "image": "tiles/tile-0.png",
            "rot": 90,
            "tileType": "5708b8ff54deddcd27756aa3",
            "items": {
                "obstacles": 0,
                "speedbumps": 1
            }
        },
        "1,0,0": {
            "image": "tiles/tile-22.png",
            "rot": 0,
            "tileType": "5708bacf54deddcd27756ab9",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            },
            levelUp: "right"
        },
        "2,0,0": {
            "image": "tiles/tile-11.png",
            "rot": 0,
            "tileType": "5708b9c354deddcd27756aae",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            },
            levelDown: "left"
        },
        "3,0,0": {
            "image": "tiles/tile-29.png",
            "rot": 0,
            "tileType": "5708bbba54deddcd27756ac0",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "3,1,0": {
            "image": "tiles/tile-20.png",
            "rot": 90,
            "tileType": "5708bab454deddcd27756ab7",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            },
            levelDown: "top"
        }
    };

    $scope.sliderOptions = {
        floor: 0,
        ceil: $scope.height-1,
        vertical: true,
        showSelectionBar: true,
        showTicksValues: true,
        ticksValuesTooltip: function (v) {
            return 'Level ' + v;
        }
    };

    $scope.open = function(x,y) {
        console.log(x+','+y+','+$scope.z);
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'line_editor_modal.html?c',
            controller: 'ModalInstanceCtrl',
            size: 'sm',
            resolve: {
                tile: function () {
                    console.log($scope.tiles[x+','+y+','+$scope.z]);
                    return $scope.tiles[x+','+y+','+$scope.z];
                }
            }
        });

        modalInstance.result.then(function (selectedItem) {
            $scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };

    $scope.toggleAnimation = function () {
        $scope.animationsEnabled = !$scope.animationsEnabled;
    };

}]);

// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.

app.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, tile) {
    $scope.tile = tile;
    console.log(tile);
    $scope.ok = function () {
        $uibModalInstance.close($scope.tile);
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});

app.directive('ngRightClick', function($parse) {
    return function(scope, element, attrs) {
        var fn = $parse(attrs.ngRightClick);
        element.bind('contextmenu', function(event) {
            scope.$apply(function() {
                event.preventDefault();
                fn(scope, {$event:event});
            });
        });
    };
});

app.directive('tile', function() {
    return {
        scope: {
            tile: '='
        },
        restrict: 'E',
        templateUrl: 'tile.html',
        link: function(scope, element, attrs) {
            scope.rotateRamp = function(direction){
                switch(direction){
                case "bottom":
                    return "rot0";
                case "top":
                    return "rot180";
                case "left":
                    return "rot90";
                case "right":
                    return "rot270";
                }
            }
        }
    };
});

app.directive('rotateOnClick', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var deg = 0;
            element.bind('click', function() {
                element.removeClass('rot'+deg);
                deg += 90;
                if(deg >= 360)
                    deg = 0;
                element.addClass('rot'+deg);
                element.attr("rot",deg);
                console.log(deg);
            });
        }
    };
});

app.directive('lvlDraggable', ['$rootScope', 'uuid', function ($rootScope, uuid) {
    return {
        restrict: 'A',
        link: function (scope, el, attrs, controller) {
            console.log("linking draggable element");
            angular.element(el).attr("draggable", "true");

            var id = angular.element(el).attr("id");

            if (!id) {
                id = uuid.new();
                angular.element(el).attr("id", id);
            }
            //console.log(id);
            el.bind("dragstart", function (e) {
                e.dataTransfer.setData('text', id);
                console.log('drag');
                $rootScope.$emit("LVL-DRAG-START");
            });

            el.bind("dragend", function (e) {
                $rootScope.$emit("LVL-DRAG-END");
            });
        }
    };
}]);

app.directive('lvlDropTarget', ['$rootScope', 'uuid', function ($rootScope, uuid) {
    return {
        restrict: 'A',
        link: function (scope, el, attrs, controller) {
            var id = angular.element(el).attr("id");
            if (!id) {
                id = uuid.new();
                angular.element(el).attr("id", id);
            }

            el.bind("dragover", function (e) {
                if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                }

                e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
                return false;
            });

            el.bind("dragenter", function (e) {
                // this / e.target is the current hover target.
                angular.element(e.target).addClass('lvl-over');
            });

            el.bind("dragleave", function (e) {
                angular.element(e.target).removeClass('lvl-over');  // this / e.target is previous target element.
            });

            el.bind("drop", function (e) {
                if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                }

                if (e.stopPropagation) {
                    e.stopPropagation(); // Necessary. Allows us to drop.
                }
                var data = e.dataTransfer.getData("text");
                var dest = document.getElementById(id);
                var src = document.getElementById(data);
                var drop = angular.element(dest); // The div where i dropped the tile
                var drag = angular.element(src); // The div where I lifted this tile

                // If we dropped something on an image this is back to the tool box
                if(drop[0].tagName == "IMG"){
                    // Remove the element from where we dragged it
                    scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")] = {};
                }else if(drag[0].tagName == "IMG"){// If we drag out an image, this is a new tile
                    console.log(drag.attr("id"));
                    scope.tiles[drop.attr("x")+","+drop.attr("y")+","+drop.attr("z")] = {image: drag.attr("src"),
                                                                                rot: +drag.attr("rot"),
                                                                                tileType: drag.attr("tile-id"),
                                                                                items:{obstacles: 0,
                                                                                speedbumps: 0}};
                    // We dragged an non-existing tile
                }else if(!scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")]){
                    // Just ignore!
                    ;
                }else if(drag.attr("x") != drop.attr("x") ||
                         drag.attr("y") != drop.attr("y") ||
                         drag.attr("z") != drop.attr("z")){
                    scope.tiles[drop.attr("x")+","+drop.attr("y")+","+drop.attr("z")] =
                        scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")];
                    // Remove the element from where we dragged it
                    scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")] = {};
                }
                console.log(scope.tiles);
                scope.$apply();

            });

            $rootScope.$on("LVL-DRAG-START", function () {
                var el = document.getElementById(id);
                angular.element(el).addClass("lvl-target");
            });

            $rootScope.$on("LVL-DRAG-END", function () {
                var el = document.getElementById(id);
                angular.element(el).removeClass("lvl-target");
                angular.element(el).removeClass("lvl-over");
            });
        }
    };
}]);
<commit_msg>Read tilebox from server<commit_after>// register the directive with your app module
var app = angular.module('ddApp', ['lvl.services', 'ngAnimate', 'ui.bootstrap', 'rzModule']);

// function referenced by the drop target
app.controller('ddController', ['$scope', '$uibModal', '$log','$http', function($scope, $uibModal, $log, $http){

    $scope.rotateTile = function(x,y){
        // If the tile doesn't exists yet
        if(!$scope.tiles[x+','+y+','+$scope.z])
            return;
        $scope.tiles[x+','+y+','+$scope.z].rot += 90;
        if($scope.tiles[x+','+y+','+$scope.z].rot >= 360)
            $scope.tiles[x+','+y+','+$scope.z].rot = 0;
    }

    $scope.numberOfDropTiles = 0;
    $scope.height = 4;
    $scope.width = 4;
    $scope.length = 7;
    $scope.name = "";
    $scope.range = function(n){
        arr = [];
        for (var i=0; i < n; i++) {
            arr.push(i);
        }
        return arr;
    }

    $scope.tileBox = {};
    $http.get("/api/maps/tiletypes").then(function(response){
        for(var i = 0; i < response.data.length; i++){
            $scope.tileBox[response.data[i]._id] = response.data[i];
        }
    }, function(response){
        console.log("Error: " + response.statusText);
    });

    $scope.z = 0;
    $scope.tiles = {};

    $scope.tiles = {
        "2,2,0": {
            "image": "tiles/tile-7.png",
            "rot": 0,
            "tileType": "5708b98454deddcd27756aaa",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "2,3,0": {
            "image": "tiles/tile-13.png",
            "rot": 90,
            "tileType": "5708b9f354deddcd27756ab0",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "2,4,0": {
            "image": "tiles/tile-24.png",
            "rot": 180,
            "tileType": "5708bb0154deddcd27756abb",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "1,4,0": {
            "image": "tiles/tile-22.png",
            "rot": 270,
            "tileType": "5708bacf54deddcd27756ab9",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "1,3,0": {
            "image": "tiles/tile-16.png",
            "rot": 270,
            "tileType": "5708ba4d54deddcd27756ab3",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "0,3,0": {
            "image": "tiles/tile-12.png",
            "rot": 270,
            "tileType": "5708b9d254deddcd27756aaf",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "0,1,0": {
            "image": "tiles/tile-6.png",
            "rot": 270,
            "tileType": "5708b97754deddcd27756aa9",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "0,2,0": {
            "image": "tiles/tile-0.png",
            "rot": 90,
            "tileType": "5708b8ff54deddcd27756aa3",
            "items": {
                "obstacles": 1,
                "speedbumps": 0
            }
        },
        "1,1,0": {
            "image": "tiles/tile-19.png",
            "rot": 0,
            "tileType": "5708ba9f54deddcd27756ab6",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "2,1,0": {
            "image": "tiles/tile-3.png",
            "rot": 0,
            "tileType": "5708b93754deddcd27756aa6",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "1,2,0": {
            "image": "tiles/tile-0.png",
            "rot": 90,
            "tileType": "5708b8ff54deddcd27756aa3",
            "items": {
                "obstacles": 0,
                "speedbumps": 1
            }
        },
        "1,0,0": {
            "image": "tiles/tile-22.png",
            "rot": 0,
            "tileType": "5708bacf54deddcd27756ab9",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            },
            levelUp: "right"
        },
        "2,0,0": {
            "image": "tiles/tile-11.png",
            "rot": 0,
            "tileType": "5708b9c354deddcd27756aae",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            },
            levelDown: "left"
        },
        "3,0,0": {
            "image": "tiles/tile-29.png",
            "rot": 0,
            "tileType": "5708bbba54deddcd27756ac0",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            }
        },
        "3,1,0": {
            "image": "tiles/tile-20.png",
            "rot": 90,
            "tileType": "5708bab454deddcd27756ab7",
            "items": {
                "obstacles": 0,
                "speedbumps": 0
            },
            levelDown: "top"
        }
    };

    $scope.sliderOptions = {
        floor: 0,
        ceil: $scope.height-1,
        vertical: true,
        showSelectionBar: true,
        showTicksValues: true,
        ticksValuesTooltip: function (v) {
            return 'Level ' + v;
        }
    };

    $scope.open = function(x,y) {
        console.log(x+','+y+','+$scope.z);
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'line_editor_modal.html?c',
            controller: 'ModalInstanceCtrl',
            size: 'sm',
            resolve: {
                tile: function () {
                    console.log($scope.tiles[x+','+y+','+$scope.z]);
                    return $scope.tiles[x+','+y+','+$scope.z];
                }
            }
        });

        modalInstance.result.then(function (selectedItem) {
            $scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };

    $scope.toggleAnimation = function () {
        $scope.animationsEnabled = !$scope.animationsEnabled;
    };

}]);

// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.

app.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, tile) {
    $scope.tile = tile;
    console.log(tile);
    $scope.ok = function () {
        $uibModalInstance.close($scope.tile);
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});

app.directive('ngRightClick', function($parse) {
    return function(scope, element, attrs) {
        var fn = $parse(attrs.ngRightClick);
        element.bind('contextmenu', function(event) {
            scope.$apply(function() {
                event.preventDefault();
                fn(scope, {$event:event});
            });
        });
    };
});

app.directive('tile', function() {
    return {
        scope: {
            tile: '='
        },
        restrict: 'E',
        templateUrl: 'tile.html',
        link: function(scope, element, attrs) {
            scope.rotateRamp = function(direction){
                switch(direction){
                case "bottom":
                    return "rot0";
                case "top":
                    return "rot180";
                case "left":
                    return "rot90";
                case "right":
                    return "rot270";
                }
            }
        }
    };
});

app.directive('rotateOnClick', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var deg = 0;
            element.bind('click', function() {
                element.removeClass('rot'+deg);
                deg += 90;
                if(deg >= 360)
                    deg = 0;
                element.addClass('rot'+deg);
                element.attr("rot",deg);
                console.log(deg);
            });
        }
    };
});

app.directive('lvlDraggable', ['$rootScope', 'uuid', function ($rootScope, uuid) {
    return {
        restrict: 'A',
        link: function (scope, el, attrs, controller) {
            console.log("linking draggable element");
            angular.element(el).attr("draggable", "true");

            var id = angular.element(el).attr("id");

            if (!id) {
                id = uuid.new();
                angular.element(el).attr("id", id);
            }
            //console.log(id);
            el.bind("dragstart", function (e) {
                e.dataTransfer.setData('text', id);
                console.log('drag');
                $rootScope.$emit("LVL-DRAG-START");
            });

            el.bind("dragend", function (e) {
                $rootScope.$emit("LVL-DRAG-END");
            });
        }
    };
}]);

app.directive('lvlDropTarget', ['$rootScope', 'uuid', function ($rootScope, uuid) {
    return {
        restrict: 'A',
        link: function (scope, el, attrs, controller) {
            var id = angular.element(el).attr("id");
            if (!id) {
                id = uuid.new();
                angular.element(el).attr("id", id);
            }

            el.bind("dragover", function (e) {
                if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                }

                e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
                return false;
            });

            el.bind("dragenter", function (e) {
                // this / e.target is the current hover target.
                angular.element(e.target).addClass('lvl-over');
            });

            el.bind("dragleave", function (e) {
                angular.element(e.target).removeClass('lvl-over');  // this / e.target is previous target element.
            });

            el.bind("drop", function (e) {
                if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                }

                if (e.stopPropagation) {
                    e.stopPropagation(); // Necessary. Allows us to drop.
                }
                var data = e.dataTransfer.getData("text");
                var dest = document.getElementById(id);
                var src = document.getElementById(data);
                var drop = angular.element(dest); // The div where i dropped the tile
                var drag = angular.element(src); // The div where I lifted this tile

                // If we dropped something on an image this is back to the tool box
                if(drop[0].tagName == "IMG"){
                    // Remove the element from where we dragged it
                    scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")] = {};
                }else if(drag[0].tagName == "IMG"){// If we drag out an image, this is a new tile
                    console.log(drag.attr("id"));
                    scope.tiles[drop.attr("x")+","+drop.attr("y")+","+drop.attr("z")] = {image: drag.attr("src"),
                                                                                rot: +drag.attr("rot"),
                                                                                tileType: drag.attr("tile-id"),
                                                                                items:{obstacles: 0,
                                                                                speedbumps: 0}};
                    // We dragged an non-existing tile
                }else if(!scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")]){
                    // Just ignore!
                    ;
                }else if(drag.attr("x") != drop.attr("x") ||
                         drag.attr("y") != drop.attr("y") ||
                         drag.attr("z") != drop.attr("z")){
                    scope.tiles[drop.attr("x")+","+drop.attr("y")+","+drop.attr("z")] =
                        scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")];
                    // Remove the element from where we dragged it
                    scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")] = {};
                }
                console.log(scope.tiles);
                scope.$apply();

            });

            $rootScope.$on("LVL-DRAG-START", function () {
                var el = document.getElementById(id);
                angular.element(el).addClass("lvl-target");
            });

            $rootScope.$on("LVL-DRAG-END", function () {
                var el = document.getElementById(id);
                angular.element(el).removeClass("lvl-target");
                angular.element(el).removeClass("lvl-over");
            });
        }
    };
}]);
<|endoftext|>


<commit_before>/* global dojo, djConfig, console, esri  */
{% extends "javascript/softgis_client.commons.js" %}

{% block library_specific_block %}
	{% for client in softgis_clients %}
	{{ client }}
	{% endfor %}
{% endblock %}
<commit_msg>just some cleanup<commit_after>/* global dojo, djConfig, console, esri  */
{% extends "javascript/softgis_client.commons.js" %}

{% block library_specific_block %}
    {% for client in softgis_clients %}
    {{ client }}
    {% endfor %}
{% endblock %}
<|endoftext|>


<commit_before>// register the directive with your app module
var app = angular.module('ddApp', ['lvl.services', 'ngAnimate', 'ui.bootstrap', 'rzModule']);

// function referenced by the drop target
app.controller('ddController', ['$scope', '$uibModal', '$log','$http', function($scope, $uibModal, $log, $http){

    $scope.tileBox = {};

    $scope.tileSets = [];
    $scope.tileSet = {};
    $http.get("/api/maps/line/tilesets?populate=true").then(function(response){
	$scope.tileSets = response.data
	$scope.tileSet = $scope.tileSets[0]
    }, function(response){
        console.log("Error: " + response.statusText);
    });

    $scope.sliderOptions = {
        floor: 0,
        ceil: 0,
        vertical: true,
        showSelectionBar: true,
        showTicksValues: true,
        ticksValuesTooltip: function (v) {
            return 'Level ' + v;
        }
    };
    $scope.z = 0;
    $scope.tiles = {};
    $scope.startTile = {x: 0, y: 0, z: 0};
    $scope.numberOfDropTiles = 0;
    $scope.height = 1;
    $scope.sliderOptions.ceil = $scope.height - 1;
    $scope.width = 1;
    $scope.length = 1;
    $scope.name = "Awesome Testbana";

    if(mapId){
        $http.get("/api/maps/" + mapId + "?populate=true").then(function(response){
            for(var i = 0; i < response.data.tiles.length; i++){
                $scope.tiles[response.data.tiles[i].x + ',' +
                             response.data.tiles[i].y + ',' +
                             response.data.tiles[i].z] = response.data.tiles[i];
            }
            $scope.startTile = response.data.startTile;
            $scope.numberOfDropTiles = response.data.numberOfDropTiles;
            $scope.height = response.data.height;
            $scope.sliderOptions.ceil = $scope.height - 1;
            $scope.width = response.data.width;
            $scope.length = response.data.length;
            $scope.name = response.data.name;

        }, function(response){
            console.log("Error: " + response.statusText);
        });
    }

    $scope.range = function(n){
        arr = [];
        for (var i=0; i < n; i++) {
            arr.push(i);
        }
        return arr;
    }

    $scope.rotateTile = function(x,y){
        // If the tile doesn't exists yet
        if(!$scope.tiles[x+','+y+','+$scope.z])
            return;
        $scope.tiles[x+','+y+','+$scope.z].rot += 90;
        if($scope.tiles[x+','+y+','+$scope.z].rot >= 360)
            $scope.tiles[x+','+y+','+$scope.z].rot = 0;
    }

    $scope.saveMap = function(){
        var map = {
            name: $scope.name,
            length: $scope.length,
            height: $scope.height,
            width: $scope.width,
            numberOfDropTiles: $scope.numberOfDropTiles,
            startTile: $scope.startTile,
            tiles: $scope.tiles
        };

        console.log(map);
        $http.post("/api/maps/createmap/", map).then(function(response){
            alert("Success!");
            console.log(response.data);
            window.location.replace("/line/editor/" + response.data.id)
        }, function(response){
            console.log(response);
            console.log("Error: " + response.statusText);
        });
    }

    $scope.open = function(x,y) {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: '/templates/line_editor_modal.html?gs',
            controller: 'ModalInstanceCtrl',
            size: 'sm',
            resolve: {
                tile: function () {
                    return $scope.tiles[x+','+y+','+$scope.z];
                },
                start: function(){
                    return $scope.startTile.x == x && $scope.startTile.y == y && $scope.startTile.z == $scope.z;
                }
            }
        });

        modalInstance.result.then(function (response) {
            if(response){
                $scope.startTile.x = x;
                $scope.startTile.y = y;
                $scope.startTile.z = $scope.z;
            }

        }, function () {
            console.log('Modal dismissed at: ' + new Date());
        });
    };

}]);

// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.

app.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, tile, start) {
    $scope.tile = tile;
    $scope.start = start;
    $scope.ok = function () {
        $uibModalInstance.close($scope.start);
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});

app.directive('ngRightClick', function($parse) {
    return function(scope, element, attrs) {
        var fn = $parse(attrs.ngRightClick);
        element.bind('contextmenu', function(event) {
            scope.$apply(function() {
                event.preventDefault();
                fn(scope, {$event:event});
            });
        });
    };
});

app.directive('tile', function() {
    return {
        scope: {
            tile: '='
        },
        restrict: 'E',
        templateUrl: '/templates/tile.html',
        link: function(scope, element, attrs) {
            scope.rotateRamp = function(direction){
                switch(direction){
                case "bottom":
                    return "rot0";
                case "top":
                    return "rot180";
                case "left":
                    return "rot90";
                case "right":
                    return "rot270";
                }
            }
        }
    };
});

app.directive('rotateOnClick', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var deg = 0;
            element.bind('click', function() {
                element.removeClass('rot'+deg);
                deg += 90;
                if(deg >= 360)
                    deg = 0;
                element.addClass('rot'+deg);
                element.attr("rot",deg);
            });
        }
    };
});

app.directive('lvlDraggable', ['$rootScope', 'uuid', function ($rootScope, uuid) {
    return {
        restrict: 'A',
        link: function (scope, el, attrs, controller) {
            console.log("linking draggable element");
            angular.element(el).attr("draggable", "true");

            var id = angular.element(el).attr("id");

            if (!id) {
                id = uuid.new();
                angular.element(el).attr("id", id);
            }
            //console.log(id);
            el.bind("dragstart", function (e) {
                e.dataTransfer.setData('text', id);
                console.log('drag');
                $rootScope.$emit("LVL-DRAG-START");
            });

            el.bind("dragend", function (e) {
                $rootScope.$emit("LVL-DRAG-END");
            });
        }
    };
}]);

app.directive('lvlDropTarget', ['$rootScope', 'uuid', function ($rootScope, uuid) {
    return {
        restrict: 'A',
        link: function (scope, el, attrs, controller) {
            var id = angular.element(el).attr("id");
            if (!id) {
                id = uuid.new();
                angular.element(el).attr("id", id);
            }

            el.bind("dragover", function (e) {
                if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                }

                e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
                return false;
            });

            el.bind("dragenter", function (e) {
                // this / e.target is the current hover target.
                angular.element(e.target).addClass('lvl-over');
            });

            el.bind("dragleave", function (e) {
                angular.element(e.target).removeClass('lvl-over');  // this / e.target is previous target element.
            });

            el.bind("drop", function (e) {
                if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                }

                if (e.stopPropagation) {
                    e.stopPropagation(); // Necessary. Allows us to drop.
                }
                var data = e.dataTransfer.getData("text");
                var dest = document.getElementById(id);
                var src = document.getElementById(data);
                var drop = angular.element(dest); // The div where i dropped the tile
                var drag = angular.element(src); // The div where I lifted this tile

                // If we dropped something on an image this is back to the tool box
                if(drop[0].tagName == "IMG"){
                    // Remove the element from where we dragged it
                    delete scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")];
                }else if(drag[0].tagName == "IMG"){// If we drag out an image, this is a new tile
                    console.log(drag.attr("id"));
                    scope.tiles[drop.attr("x")+","+drop.attr("y")+","+drop.attr("z")] = {image: drag.attr("src"),
                                                                                rot: +drag.attr("rot"),
                                                                                tileType: scope.tileBox[drag.attr("tile-id")],
                                                                                items:{obstacles: 0,
                                                                                speedbumps: 0}};
                    // We dragged an non-existing tile
                }else if(!scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")]){
                    // Just ignore!
                    ;
                }else if(drag.attr("x") != drop.attr("x") ||
                         drag.attr("y") != drop.attr("y") ||
                         drag.attr("z") != drop.attr("z")){
                    scope.tiles[drop.attr("x")+","+drop.attr("y")+","+drop.attr("z")] =
                        scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")];
                    // Remove the element from where we dragged it
                    delete scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")];
                }
                scope.$apply();

            });

            $rootScope.$on("LVL-DRAG-START", function () {
                var el = document.getElementById(id);
                angular.element(el).addClass("lvl-target");
            });

            $rootScope.$on("LVL-DRAG-END", function () {
                var el = document.getElementById(id);
                angular.element(el).removeClass("lvl-target");
                angular.element(el).removeClass("lvl-over");
            });
        }
    };
}]);
<commit_msg>Fix dropping of tile<commit_after>// register the directive with your app module
var app = angular.module('ddApp', ['lvl.services', 'ngAnimate', 'ui.bootstrap', 'rzModule']);

// function referenced by the drop target
app.controller('ddController', ['$scope', '$uibModal', '$log','$http', function($scope, $uibModal, $log, $http){

    $scope.tileSets = [];
    $scope.tileSet = {};
    $http.get("/api/maps/line/tilesets?populate=true").then(function(response){
	$scope.tileSets = response.data
	$scope.tileSet = $scope.tileSets[0]
    }, function(response){
        console.log("Error: " + response.statusText);
    });

    $scope.sliderOptions = {
        floor: 0,
        ceil: 0,
        vertical: true,
        showSelectionBar: true,
        showTicksValues: true,
        ticksValuesTooltip: function (v) {
            return 'Level ' + v;
        }
    };
    $scope.z = 0;
    $scope.tiles = {};
    $scope.startTile = {x: 0, y: 0, z: 0};
    $scope.numberOfDropTiles = 0;
    $scope.height = 1;
    $scope.sliderOptions.ceil = $scope.height - 1;
    $scope.width = 1;
    $scope.length = 1;
    $scope.name = "Awesome Testbana";

    if(mapId){
        $http.get("/api/maps/" + mapId + "?populate=true").then(function(response){
            for(var i = 0; i < response.data.tiles.length; i++){
                $scope.tiles[response.data.tiles[i].x + ',' +
                             response.data.tiles[i].y + ',' +
                             response.data.tiles[i].z] = response.data.tiles[i];
            }
            $scope.startTile = response.data.startTile;
            $scope.numberOfDropTiles = response.data.numberOfDropTiles;
            $scope.height = response.data.height;
            $scope.sliderOptions.ceil = $scope.height - 1;
            $scope.width = response.data.width;
            $scope.length = response.data.length;
            $scope.name = response.data.name;

        }, function(response){
            console.log("Error: " + response.statusText);
        });
    }

    $scope.range = function(n){
        arr = [];
        for (var i=0; i < n; i++) {
            arr.push(i);
        }
        return arr;
    }

    $scope.rotateTile = function(x,y){
        // If the tile doesn't exists yet
        if(!$scope.tiles[x+','+y+','+$scope.z])
            return;
        $scope.tiles[x+','+y+','+$scope.z].rot += 90;
        if($scope.tiles[x+','+y+','+$scope.z].rot >= 360)
            $scope.tiles[x+','+y+','+$scope.z].rot = 0;
    }

    $scope.saveMap = function(){
        var map = {
            name: $scope.name,
            length: $scope.length,
            height: $scope.height,
            width: $scope.width,
            numberOfDropTiles: $scope.numberOfDropTiles,
            startTile: $scope.startTile,
            tiles: $scope.tiles
        };

        console.log(map);
        $http.post("/api/maps/createmap/", map).then(function(response){
            alert("Success!");
            console.log(response.data);
            window.location.replace("/line/editor/" + response.data.id)
        }, function(response){
            console.log(response);
            console.log("Error: " + response.statusText);
        });
    }

    $scope.open = function(x,y) {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: '/templates/line_editor_modal.html?gs',
            controller: 'ModalInstanceCtrl',
            size: 'sm',
            resolve: {
                tile: function () {
                    return $scope.tiles[x+','+y+','+$scope.z];
                },
                start: function(){
                    return $scope.startTile.x == x && $scope.startTile.y == y && $scope.startTile.z == $scope.z;
                }
            }
        });

        modalInstance.result.then(function (response) {
            if(response){
                $scope.startTile.x = x;
                $scope.startTile.y = y;
                $scope.startTile.z = $scope.z;
            }

        }, function () {
            console.log('Modal dismissed at: ' + new Date());
        });
    };

}]);

// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.

app.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, tile, start) {
    $scope.tile = tile;
    $scope.start = start;
    $scope.ok = function () {
        $uibModalInstance.close($scope.start);
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});

app.directive('ngRightClick', function($parse) {
    return function(scope, element, attrs) {
        var fn = $parse(attrs.ngRightClick);
        element.bind('contextmenu', function(event) {
            scope.$apply(function() {
                event.preventDefault();
                fn(scope, {$event:event});
            });
        });
    };
});

app.directive('tile', function() {
    return {
        scope: {
            tile: '='
        },
        restrict: 'E',
        templateUrl: '/templates/tile.html',
        link: function(scope, element, attrs) {
            scope.rotateRamp = function(direction){
                switch(direction){
                case "bottom":
                    return "rot0";
                case "top":
                    return "rot180";
                case "left":
                    return "rot90";
                case "right":
                    return "rot270";
                }
            }
        }
    };
});

app.directive('rotateOnClick', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var deg = 0;
            element.bind('click', function() {
                element.removeClass('rot'+deg);
                deg += 90;
                if(deg >= 360)
                    deg = 0;
                element.addClass('rot'+deg);
                element.attr("rot",deg);
            });
        }
    };
});

app.directive('lvlDraggable', ['$rootScope', 'uuid', function ($rootScope, uuid) {
    return {
        restrict: 'A',
        link: function (scope, el, attrs, controller) {
            console.log("linking draggable element");
            angular.element(el).attr("draggable", "true");

            var id = angular.element(el).attr("id");

            if (!id) {
                id = uuid.new();
                angular.element(el).attr("id", id);
            }
            //console.log(id);
            el.bind("dragstart", function (e) {
                e.dataTransfer.setData('text', id);
                $rootScope.$emit("LVL-DRAG-START");
            });

            el.bind("dragend", function (e) {
                $rootScope.$emit("LVL-DRAG-END");
            });
        }
    };
}]);

app.directive('lvlDropTarget', ['$rootScope', 'uuid', function ($rootScope, uuid) {
    return {
        restrict: 'A',
        link: function (scope, el, attrs, controller) {
            var id = angular.element(el).attr("id");
            if (!id) {
                id = uuid.new();
                angular.element(el).attr("id", id);
            }

            el.bind("dragover", function (e) {
                if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                }

                e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
                return false;
            });

            el.bind("dragenter", function (e) {
                // this / e.target is the current hover target.
                angular.element(e.target).addClass('lvl-over');
            });

            el.bind("dragleave", function (e) {
                angular.element(e.target).removeClass('lvl-over');  // this / e.target is previous target element.
            });

            el.bind("drop", function (e) {
                if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                }

                if (e.stopPropagation) {
                    e.stopPropagation(); // Necessary. Allows us to drop.
                }
                var data = e.dataTransfer.getData("text");
                var dest = document.getElementById(id);
                var src = document.getElementById(data);
                var drop = angular.element(dest); // The div where i dropped the tile
                var drag = angular.element(src); // The div where I lifted this tile

                // If we dropped something on an image this is back to the tool box
                if(drop[0].tagName == "IMG"){
                    // Remove the element from where we dragged it
                    delete scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")];
                }else if(drag[0].tagName == "IMG"){// If we drag out an image, this is a new tile

                    scope.tiles[drop.attr("x")+","+drop.attr("y")+","+drop.attr("z")] = {rot: +drag.attr("rot"),
                                                                                tileType: scope.tileSet.tiles.find(function(t){return t.tileType._id == drag.attr("tile-id")}).tileType,
                                                                                items:{obstacles: 0,
                                                                                speedbumps: 0}};
                    // We dragged an non-existing tile
                }else if(!scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")]){
                    // Just ignore!
                    ;
                }else if(drag.attr("x") != drop.attr("x") ||
                         drag.attr("y") != drop.attr("y") ||
                         drag.attr("z") != drop.attr("z")){
                    scope.tiles[drop.attr("x")+","+drop.attr("y")+","+drop.attr("z")] =
                        scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")];
                    // Remove the element from where we dragged it
                    delete scope.tiles[drag.attr("x")+","+drag.attr("y")+","+drag.attr("z")];
                }
                scope.$apply();

            });

            $rootScope.$on("LVL-DRAG-START", function () {
                var el = document.getElementById(id);
                angular.element(el).addClass("lvl-target");
            });

            $rootScope.$on("LVL-DRAG-END", function () {
                var el = document.getElementById(id);
                angular.element(el).removeClass("lvl-target");
                angular.element(el).removeClass("lvl-over");
            });
        }
    };
}]);
<|endoftext|>