<commit_before>// WARNING this is not a production code, this is only a draft !
require(['esri/map', 'esri/symbols/PictureMarkerSymbol', 'esri/layers/GraphicsLayer',
  'esri/geometry/Point', 'esri/SpatialReference', 'esri/graphic', 'esri/geometry/webMercatorUtils',
  'app/bootstrapmap', 'esri/dijit/Search', 'esri/dijit/LocateButton',
  'esri/layers/WebTiledLayer', 'dojo/_base/array', 'spin-js/spin',
  'dojo/domReady!'
], function(Map, PictureMarkerSymbol, GraphicsLayer, Point, SpatialReference,
  Graphic, webMercatorUtils, BootstrapMap, Search, LocateButton, WebTiledLayer,
  array, Spinner) {
  var lang = 'en'; // default language
  var key = 'Q4M51WJZ'; // this is my key !
  // default position is downtown Grenoble, France
  // var w3wmarker = {
  //   lat: 45.188996,
  //   lng: 5.724614
  // };
  // default position at San Diego Convention Center
  var w3wmarker = {
    lat: 32.706514,
    lng: -117.163384
  };
  var initialWords = null;
  if (window.location.search) {
    initialWords = getInitalWords(window.location.search);
    if (initialWords) {
      initPosition(initialWords, function() {
        updateW3w();
        updateMarkerWithLatLng();
      });
    }
  }
  // sets up and shows the spinner
  var opts = {
    lines: 13 // The number of lines to draw
      ,
    length: 14 // The length of each line
      ,
    width: 7 // The line thickness
      ,
    radius: 21 // The radius of the inner circle
      ,
    scale: 1 // Scales overall size of the spinner
      ,
    corners: 1 // Corner roundness (0..1)
      ,
    color: '#000' // #rgb or #rrggbb or array of colors
      ,
    opacity: 0.25 // Opacity of the lines
      ,
    rotate: 0 // The rotation offset
      ,
    direction: 1 // 1: clockwise, -1: counterclockwise
      ,
    speed: 1 // Rounds per second
      ,
    trail: 60 // Afterglow percentage
      ,
    fps: 20 // Frames per second when using setTimeout() as a fallback for CSS
      ,
    zIndex: 2e9 // The z-index (defaults to 2000000000)
      ,
    className: 'spinner' // The CSS class to assign to the spinner
      ,
    top: '50%' // Top position relative to parent
      ,
    left: '50%' // Left position relative to parent
      ,
    shadow: false // Whether to render a shadow
      ,
    hwaccel: false // Whether to use hardware acceleration
      ,
    position: 'absolute' // Element positioning
  }
  var spinnerTarget = document.getElementById('spinner')
  var spinner = new Spinner(opts).spin(spinnerTarget);
  // init with three words
  function getInitalWords(str) {
    return str.substr(1);
  }
  var graphic, selectedLng, selectedBasemap;
  var map = BootstrapMap.create('mapDiv', {
    center: [w3wmarker.lng, w3wmarker.lat],
    zoom: 18,
    scrollWheelZoom: true,
    basemap: 'satellite'
  });
  // handle map click to update w3w marker and words
  map.on('click', handleMapClick);
  // map.on('update-start', function() {
  //   spinner.spin(spinnerTarget);
  // });
  // map.on('update-end', function(){
  //   spinner.stop();
  // });

  // picture symbol
  var w3wmarkerSymbol = new PictureMarkerSymbol('./img/w3wmarker.png', 35, 35);
  var markerLayer = new GraphicsLayer();
  map.addLayer(markerLayer);
  // w3w graphic marker
  graphic = new Graphic(new Point(w3wmarker.lng, w3wmarker.lat, new SpatialReference({
    wkid: 4326
  })), w3wmarkerSymbol);
  markerLayer.add(graphic);
  // search Widget (geocoder)
  var s = new Search({
    map: map,
    enableHighlight: false,
    enableInfoWindow: false
  }, 'search');
  s.startup();
  // handle search result to update w3w marker and words
  s.on('select-result', function(e) {
    updateMarker(e.result.feature.geometry);
  });
  // geolocate widget
  var geoLocate = new LocateButton({
    map: map,
    highlightLocation: false,
    useTracking: false
  }, 'LocateButton');
  geoLocate.startup();
  // handle search result to update w3w marker and words
  geoLocate.on('locate', function(e) {
    //spinner.stop();
    //console.log(e);
    updateMarker(e.graphic.geometry);
  });

  $(document).ready(jQueryReady);

  function handleMapClick(event) {
    updateMarker(event.mapPoint);
  }

  function updateMarkerWithLatLng() {
    var p = new Point(w3wmarker.lng, w3wmarker.lat, new SpatialReference({
      wkid: 4326
    }));
    if (graphic) {
      graphic.setGeometry(p);
    } else {
      graphic = new Graphic(p, markerSymbol);
      map.graphics.add(graphic);
    }
    map.centerAt(p);
  }

  function updateMarker(mapPoint) {
    if (!mapPoint) {
      return;
    }
    if (graphic) {
      graphic.setGeometry(mapPoint);
    } else {
      graphic = new Graphic(mapPoint, markerSymbol);
      map.graphics.add(graphic);
    }
    var p = webMercatorUtils.webMercatorToGeographic(mapPoint);
    w3wmarker.lat = p.y;
    w3wmarker.lng = p.x;
    updateW3w();
  }

  function jQueryReady() {
    getLangs();
    updateW3w();

    $('#LocateButton').click(function(e) {
      spinner.spin(spinnerTarget);
    });
    $('#basemapList li').click(function(e) {
      clearBasemap();
      //  WebTiledLayers => http://leaflet-extras.github.io/leaflet-providers/preview/
      switch (e.target.text) {
        case 'Imagery':
          map.setBasemap('satellite');
          break;
        case 'Hybrid':
          map.setBasemap('hybrid');
          break;
        case 'National Geographic':
          map.setBasemap('national-geographic');
          break;
        case 'Topographic':
          map.setBasemap('topo');
          break;
        case 'Gray':
          map.setBasemap('gray');
          break;
        case 'DarkGray':
          map.setBasemap('dark-gray');
          break;
        case 'Open Street Map':
          map.setBasemap('osm');
          break;
        case 'MapBox Space':
          var mbs = new WebTiledLayer('http://${subDomain}.tiles.mapbox.com/v3/eleanor.ipncow29/${level}/${col}/${row}.jpg', {
            copyright: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
            id: 'mapbox-space',
            subDomains: ['a', 'b', 'c', 'd']
          });
          map.addLayer(mbs);
          break;
        case 'Pinterest':
          var pinterest = new WebTiledLayer('http://${subDomain}.tiles.mapbox.com/v3/pinterest.map-ho21rkos/${level}/${col}/${row}.jpg', {
            copyright: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Pinterest & Mapbox',
            id: 'pinterest',
            subDomains: ['a', 'b', 'c', 'd']
          });
          map.addLayer(pinterest);
          break;
        case 'Water Color':
          var waterColor = new WebTiledLayer('http://${subDomain}.tile.stamen.com/watercolor/${level}/${col}/${row}.jpg', {
            copyright: 'Stamen',
            id: 'water-color',
            subDomains: ['a', 'b', 'c', 'd']
          });
          map.addLayer(waterColor);
          break;
        case 'Toner':
          var toner = new WebTiledLayer('http://${subDomain}.tile.stamen.com/toner/${level}/${col}/${row}.jpg', {
            copyright: 'Stamen',
            id: 'toner',
            subDomains: ['a', 'b', 'c', 'd']
          });
          map.addLayer(toner);
          break;
        case 'MapQuest':
          var mapQuest = new WebTiledLayer('http://otile${subDomain}.mqcdn.com/tiles/1.0.0/map/${level}/${col}/${row}.jpg', {
            copyright: 'Tiles Courtesy of MapQuest — Map data © OpenStreetMap',
            id: 'mapquest',
            subDomains: ['1', '2', '3', '4']
          });
          map.addLayer(mapQuest);
          break;
        case 'Cycle Map':
          var cycleMap = new WebTiledLayer('http://${subDomain}.tile.opencyclemap.org/cycle/${level}/${col}/${row}.png', {
            'copyright': 'Open Cycle Map, map data © OpenStreetMap contributors, CC-BY-SA',
            'id': 'Open Cycle Map',
            'subDomains': ['a', 'b', 'c']
          });
          map.addLayer(cycleMap);
          break;
      }
      e.target.parentNode.className = 'active';
      if (selectedBasemap) {
        selectedBasemap.className = '';
      }
      selectedBasemap = e.target.parentNode;
      if ($('.navbar-collapse.in').length > 0) {
        $('.navbar-toggle').click();
      }
    });

  }

  function clearBasemap() {
    if (map.basemapLayerIds && map.basemapLayerIds.length > 0) {
      array.forEach(map.basemapLayerIds, function(lid) {
        map.removeLayer(map.getLayer(lid));
      });
      map.basemapLayerIds = [];
    } else {
      map.removeLayer(map.getLayer(map.layerIds[0]));
    }
  }

  function getLangs() {
    data = {
      'key': key
    };
    //var langs = $('#lang'); // tant que cela fonctionne pas avec la navbar !
    var w3wul = $('#languagesList ul');
    $.post('https://api.what3words.com/get-languages', data, function(response) {
      //console.log(response);
      $.each(response.languages, function() {
        // if (this.code === 'fr') {
        //   langs.append($('<option />').val(this.code).text(this.name_display).prop('selected', true));
        //   w3wul.append($('
').prop('class', 'active').append($('').attr('href', '#'+this.code).text(this.name_display)));
        //   $('#languagesHref').text('[fr]');
        //} else {
        //langs.append($('<option />').val(this.code).text(this.name_display));
        w3wul.append($('
').append($('').attr('href', '#' + this.code).text(this.name_display)));
        //}
      });
      $('#languagesList li').click(function(e) {
        lang = e.target.hash.substr(1);
        $('#languagesHref').text('[' + lang + ']');
        e.target.parentNode.className = 'active';
        if (selectedLng) {
          selectedLng.className = '';
        }
        selectedLng = e.target.parentNode;
        updateW3w();
        if ($('.navbar-collapse.in').length > 0) {
          $('.navbar-toggle').click();
        }

      });

    });
  }

  function updateW3w() {
    data = {
      'key': key,
      'lang': lang,
      'position': '\'' + w3wmarker.lat + ',' + w3wmarker.lng + '\''
    };
    spinner.spin(spinnerTarget);
    $.post('http://api.what3words.com/position', data, function(response) {
      spinner.stop();
      //console.log(response);
      var w3w = response.words[0] + '.' + response.words[1] + '.' + response.words[2];
      $('#w3Words').text(w3w);
      $('#w3wlink').attr('href', 'http://w3w.co/' + w3w);
      $('#w3wPosition').text(response.position[0] + ', ' + response.position[1]);
    });
  }

  function initPosition(words, callback) {
    data = {
      'key': key,
      'string': decodeURIComponent(words)
    };

    $.post('http://api.what3words.com/w3w', data, function(response) {
      if (!response.error) {
        w3wmarker.lat = response.position[0];
        w3wmarker.lng = response.position[1];
        callback('ok');
      } else {
        console.log(response);
        spinner.stop();
      }
    });
  }

});
<commit_msg>w3w search<commit_after>// WARNING this is not a production code, this is only a draft !
require(['esri/map', 'esri/symbols/PictureMarkerSymbol', 'esri/layers/GraphicsLayer',
  'esri/geometry/Point', 'esri/SpatialReference', 'esri/graphic', 'esri/geometry/webMercatorUtils',
  'app/bootstrapmap', 'esri/dijit/Search', 'esri/dijit/LocateButton',
  'esri/layers/WebTiledLayer', 'dojo/_base/array', 'spin-js/spin',
  'dojo/domReady!'
], function(Map, PictureMarkerSymbol, GraphicsLayer, Point, SpatialReference,
  Graphic, webMercatorUtils, BootstrapMap, Search, LocateButton, WebTiledLayer,
  array, Spinner) {
  var lang = 'en'; // default language
  var key = 'Q4M51WJZ'; // this is my key !
  // default position is downtown Grenoble, France
  // var w3wmarker = {
  //   lat: 45.188996,
  //   lng: 5.724614
  // };
  // default position at San Diego Convention Center
  var w3wmarker = {
    lat: 32.706514,
    lng: -117.163384
  };
  var initialWords = null;
  if (window.location.search) {
    initialWords = getInitalWords(window.location.search);
    if (initialWords) {
      initPosition(initialWords, function() {
        updateW3w();
        updateMarkerWithLatLng();
      });
    }
  }
  // sets up and shows the spinner
  var opts = {
    lines: 13 // The number of lines to draw
      ,
    length: 14 // The length of each line
      ,
    width: 7 // The line thickness
      ,
    radius: 21 // The radius of the inner circle
      ,
    scale: 1 // Scales overall size of the spinner
      ,
    corners: 1 // Corner roundness (0..1)
      ,
    color: '#000' // #rgb or #rrggbb or array of colors
      ,
    opacity: 0.25 // Opacity of the lines
      ,
    rotate: 0 // The rotation offset
      ,
    direction: 1 // 1: clockwise, -1: counterclockwise
      ,
    speed: 1 // Rounds per second
      ,
    trail: 60 // Afterglow percentage
      ,
    fps: 20 // Frames per second when using setTimeout() as a fallback for CSS
      ,
    zIndex: 2e9 // The z-index (defaults to 2000000000)
      ,
    className: 'spinner' // The CSS class to assign to the spinner
      ,
    top: '50%' // Top position relative to parent
      ,
    left: '50%' // Left position relative to parent
      ,
    shadow: false // Whether to render a shadow
      ,
    hwaccel: false // Whether to use hardware acceleration
      ,
    position: 'absolute' // Element positioning
  }
  var spinnerTarget = document.getElementById('spinner')
  var spinner = new Spinner(opts).spin(spinnerTarget);
  // init with three words
  function getInitalWords(str) {
    return str.substr(1);
  }
  var graphic, selectedLng, selectedBasemap;
  var map = BootstrapMap.create('mapDiv', {
    center: [w3wmarker.lng, w3wmarker.lat],
    zoom: 18,
    scrollWheelZoom: true,
    basemap: 'satellite'
  });
  // handle map click to update w3w marker and words
  map.on('click', handleMapClick);
  // map.on('update-start', function() {
  //   spinner.spin(spinnerTarget);
  // });
  // map.on('update-end', function(){
  //   spinner.stop();
  // });

  // picture symbol
  var w3wmarkerSymbol = new PictureMarkerSymbol('./img/w3wmarker.png', 35, 35);
  var markerLayer = new GraphicsLayer();
  map.addLayer(markerLayer);
  // w3w graphic marker
  graphic = new Graphic(new Point(w3wmarker.lng, w3wmarker.lat, new SpatialReference({
    wkid: 4326
  })), w3wmarkerSymbol);
  markerLayer.add(graphic);
  // search Widget (geocoder)
  var s = new Search({
    map: map,
    enableHighlight: false,
    enableInfoWindow: false
  }, 'search');
  s.startup();
  // handle search result to update w3w marker and words
  s.on('select-result', function(e) {
    updateMarker(e.result.feature.geometry);
  });
  s.on('search-results', function(e) {
    console.log(e);
  });
  s.on('suggest-results', function (e) {
    console.log(e);
    // is it a w3w ? two dots and no space
    var w3wSearch = (e.value.split('.').length === 3) && (e.value.split(' ').length=== 1 );
    if( w3wSearch ) {
      initPosition(e.value, function() {
        spinner.spin(spinnerTarget);
        updateW3w();
        updateMarkerWithLatLng();
      });
    }
  });
  // geolocate widget
  var geoLocate = new LocateButton({
    map: map,
    highlightLocation: false,
    useTracking: false
  }, 'LocateButton');
  geoLocate.startup();
  // handle search result to update w3w marker and words
  geoLocate.on('locate', function(e) {
    //console.log(e);
    updateMarker(e.graphic.geometry);
  });

  $(document).ready(jQueryReady);

  function handleMapClick(event) {
    updateMarker(event.mapPoint);
  }

  function updateMarkerWithLatLng() {
    var p = new Point(w3wmarker.lng, w3wmarker.lat, new SpatialReference({
      wkid: 4326
    }));
    if (graphic) {
      graphic.setGeometry(p);
    } else {
      graphic = new Graphic(p, markerSymbol);
      map.graphics.add(graphic);
    }
    map.centerAt(p);
  }

  function updateMarker(mapPoint) {
    if (!mapPoint) {
      return;
    }
    if (graphic) {
      graphic.setGeometry(mapPoint);
    } else {
      graphic = new Graphic(mapPoint, markerSymbol);
      map.graphics.add(graphic);
    }
    var p = webMercatorUtils.webMercatorToGeographic(mapPoint);
    w3wmarker.lat = p.y;
    w3wmarker.lng = p.x;
    updateW3w();
  }

  function jQueryReady() {
    getLangs();
    updateW3w();

    $('#LocateButton').click(function(e) {
      spinner.spin(spinnerTarget);
    });
    $('#basemapList li').click(function(e) {
      clearBasemap();
      //  WebTiledLayers => http://leaflet-extras.github.io/leaflet-providers/preview/
      switch (e.target.text) {
        case 'Imagery':
          map.setBasemap('satellite');
          break;
        case 'Hybrid':
          map.setBasemap('hybrid');
          break;
        case 'National Geographic':
          map.setBasemap('national-geographic');
          break;
        case 'Topographic':
          map.setBasemap('topo');
          break;
        case 'Gray':
          map.setBasemap('gray');
          break;
        case 'DarkGray':
          map.setBasemap('dark-gray');
          break;
        case 'Open Street Map':
          map.setBasemap('osm');
          break;
        case 'MapBox Space':
          var mbs = new WebTiledLayer('http://${subDomain}.tiles.mapbox.com/v3/eleanor.ipncow29/${level}/${col}/${row}.jpg', {
            copyright: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
            id: 'mapbox-space',
            subDomains: ['a', 'b', 'c', 'd']
          });
          map.addLayer(mbs);
          break;
        case 'Pinterest':
          var pinterest = new WebTiledLayer('http://${subDomain}.tiles.mapbox.com/v3/pinterest.map-ho21rkos/${level}/${col}/${row}.jpg', {
            copyright: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Pinterest & Mapbox',
            id: 'pinterest',
            subDomains: ['a', 'b', 'c', 'd']
          });
          map.addLayer(pinterest);
          break;
        case 'Water Color':
          var waterColor = new WebTiledLayer('http://${subDomain}.tile.stamen.com/watercolor/${level}/${col}/${row}.jpg', {
            copyright: 'Stamen',
            id: 'water-color',
            subDomains: ['a', 'b', 'c', 'd']
          });
          map.addLayer(waterColor);
          break;
        case 'Toner':
          var toner = new WebTiledLayer('http://${subDomain}.tile.stamen.com/toner/${level}/${col}/${row}.jpg', {
            copyright: 'Stamen',
            id: 'toner',
            subDomains: ['a', 'b', 'c', 'd']
          });
          map.addLayer(toner);
          break;
        case 'MapQuest':
          var mapQuest = new WebTiledLayer('http://otile${subDomain}.mqcdn.com/tiles/1.0.0/map/${level}/${col}/${row}.jpg', {
            copyright: 'Tiles Courtesy of MapQuest — Map data © OpenStreetMap',
            id: 'mapquest',
            subDomains: ['1', '2', '3', '4']
          });
          map.addLayer(mapQuest);
          break;
        case 'Cycle Map':
          var cycleMap = new WebTiledLayer('http://${subDomain}.tile.opencyclemap.org/cycle/${level}/${col}/${row}.png', {
            'copyright': 'Open Cycle Map, map data © OpenStreetMap contributors, CC-BY-SA',
            'id': 'Open Cycle Map',
            'subDomains': ['a', 'b', 'c']
          });
          map.addLayer(cycleMap);
          break;
      }
      e.target.parentNode.className = 'active';
      if (selectedBasemap) {
        selectedBasemap.className = '';
      }
      selectedBasemap = e.target.parentNode;
      if ($('.navbar-collapse.in').length > 0) {
        $('.navbar-toggle').click();
      }
    });

  }

  function clearBasemap() {
    if (map.basemapLayerIds && map.basemapLayerIds.length > 0) {
      array.forEach(map.basemapLayerIds, function(lid) {
        map.removeLayer(map.getLayer(lid));
      });
      map.basemapLayerIds = [];
    } else {
      map.removeLayer(map.getLayer(map.layerIds[0]));
    }
  }

  function getLangs() {
    data = {
      'key': key
    };
    //var langs = $('#lang'); // tant que cela fonctionne pas avec la navbar !
    var w3wul = $('#languagesList ul');
    $.post('https://api.what3words.com/get-languages', data, function(response) {
      //console.log(response);
      $.each(response.languages, function() {
        // if (this.code === 'fr') {
        //   langs.append($('<option />').val(this.code).text(this.name_display).prop('selected', true));
        //   w3wul.append($('
').prop('class', 'active').append($('').attr('href', '#'+this.code).text(this.name_display)));
        //   $('#languagesHref').text('[fr]');
        //} else {
        //langs.append($('<option />').val(this.code).text(this.name_display));
        w3wul.append($('
').append($('').attr('href', '#' + this.code).text(this.name_display)));
        //}
      });
      $('#languagesList li').click(function(e) {
        lang = e.target.hash.substr(1);
        $('#languagesHref').text('[' + lang + ']');
        e.target.parentNode.className = 'active';
        if (selectedLng) {
          selectedLng.className = '';
        }
        selectedLng = e.target.parentNode;
        updateW3w();
        if ($('.navbar-collapse.in').length > 0) {
          $('.navbar-toggle').click();
        }

      });

    });
  }

  function updateW3w() {
    data = {
      'key': key,
      'lang': lang,
      'position': '\'' + w3wmarker.lat + ',' + w3wmarker.lng + '\''
    };
    spinner.spin(spinnerTarget);
    $.post('http://api.what3words.com/position', data, function(response) {
      spinner.stop();
      //console.log(response);
      var w3w = response.words[0] + '.' + response.words[1] + '.' + response.words[2];
      $('#w3Words').text(w3w);
      $('#w3wlink').attr('href', 'http://w3w.co/' + w3w);
      $('#w3wPosition').text(response.position[0] + ', ' + response.position[1]);
    });
  }

  function initPosition(words, callback) {
    data = {
      'key': key,
      'string': decodeURIComponent(words)
    };

    $.post('http://api.what3words.com/w3w', data, function(response) {
      if (!response.error) {
        w3wmarker.lat = response.position[0];
        w3wmarker.lng = response.position[1];
        callback('ok');
      } else {
        console.log(response);
        spinner.stop();
      }
    });
  }

});
<|endoftext|>


<commit_before>/**
This is a JS version of https://github.com/gabinante/TitleCreator
*/

var jobCategories = ['Solutions', 'Systems', 'Network', 'Security', 'Compliance', 'Information', 'Scalability', 'Cloud'];

var possessivePrefixes = ['Viceroy','Commandant', 'Grand Poo-Bah', 'Archon', 'Duke', 'Chancellor', 'President', 'Marquis', 'Earl', 'Director', 'Chair', 'Head', 'Senior Director'];
var possessiveSuffixes = ['Engineering', 'Management', 'Development', 'Deployment', 'Technical Training', 'Operations', 'Architecture', 'Infrastructure', 'Technology', 'Administration', 'Management', 'Computational Analytics', 'Database Administration'];

var adjectivePrefixes = ['Principal','Chief','Head','Lead', 'Senior', 'Master'];
var adjectiveSuffixes = ['Engineer', 'Architect', 'Designer', 'Consultant', 'Manager', 'Officer', 'Janitor'];

var romanGrades = ['I', 'II', 'III', 'IV'];

/**
 * Utility to wrap the different behaviors between W3C-compliant browsers
 * and IE when adding event handlers.
 *
 * @param {Object} element Object on which to attach the event listener.
 * @param {string} type A string representing the event type to listen for
 *     (e.g. load, click, etc.).
 * @param {function()} callback The function that receives the notification.
 */
function addListener(element, type, callback) {
 if (element.addEventListener) element.addEventListener(type, callback);
 else if (element.attachEvent) element.attachEvent('on' + type, callback);
}

function randomBool() {
  return Math.random()<.5;
}

function randomElement(array) {
  return array[Math.floor(Math.random() * array.length)];
}

function generateTitle() {
  if (randomBool()) {
    title = randomElement(possessivePrefixes) + ' of ' + randomElement(jobCategories) + ' ' + randomElement(possessiveSuffixes)
  } else {
    title = randomElement(adjectivePrefixes) + ' ' + randomElement(jobCategories) + ' ' + randomElement(adjectiveSuffixes)
  }

  if (randomBool()) {
    title = title + ' ' + randomElement(romanGrades)
  }

  return title;
}

function updateTitle() {
  document.getElementById("name").innerHTML = generateTitle();
}

updateTitle();

var newTitleLink = document.getElementById('again');

addListener(newTitleLink, 'click', function() {
  updateTitle();
});
<commit_msg>[#1] Some titles should never have Roman grade suffixes<commit_after>/**
This is a JS version of https://github.com/gabinante/TitleCreator
*/

var jobCategories = ['Solutions', 'Systems', 'Network', 'Security', 'Compliance', 'Information', 'Scalability', 'Cloud'];

var possessivePrefixes = ['Viceroy', 'Commandant', 'Grand Poo-Bah', 'Archon', 'Duke', 'Chancellor', 'President', 'Marquis', 'Earl', 'Director', 'Chair', 'Head', 'Senior Director'];
var possessiveSuffixes = ['Engineering', 'Management', 'Development', 'Deployment', 'Technical Training', 'Operations', 'Architecture', 'Infrastructure', 'Technology', 'Administration', 'Management', 'Computational Analytics', 'Database Administration'];

var adjectivePrefixes = ['Principal', 'Chief', 'Head', 'Lead', 'Senior', 'Master'];
var adjectiveSuffixes = ['Engineer', 'Architect', 'Designer', 'Consultant', 'Manager', 'Officer', 'Janitor'];

var romanGrades = ['I', 'II', 'III', 'IV'];

// Certain prefixes are singleton roles and should never have a grade suffix
var ungradablePrefixes = ['Chair', 'Chief', 'Chancellor', 'Commandant', 'Director', 'Head', 'Lead', 'President']

/**
 * Utility to wrap the different behaviors between W3C-compliant browsers
 * and IE when adding event handlers.
 *
 * @param {Object} element Object on which to attach the event listener.
 * @param {string} type A string representing the event type to listen for
 *     (e.g. load, click, etc.).
 * @param {function()} callback The function that receives the notification.
 */
function addListener(element, type, callback) {
 if (element.addEventListener) element.addEventListener(type, callback);
 else if (element.attachEvent) element.attachEvent('on' + type, callback);
}

function maybe(percentage) {
  return Math.random() < (percentage/100);
}

function randomBool() {
  return maybe(50);
}

function randomElement(array) {
  return array[Math.floor(Math.random() * array.length)];
}

function generateTitle() {
  if (randomBool()) {
    title = randomElement(possessivePrefixes) + ' of ' + randomElement(jobCategories) + ' ' + randomElement(possessiveSuffixes)
  } else {
    title = randomElement(adjectivePrefixes) + ' ' + randomElement(jobCategories) + ' ' + randomElement(adjectiveSuffixes)
  }

  // Add a Roman numeral grade suffix 25% of the time, unless the title is ungradable.
  if (!ungradablePrefixes.some(prefix => title.includes(prefix)) && maybe(25)) {
    title = title + ' ' + randomElement(romanGrades)
  }

  return title;
}

function updateTitle() {
  document.getElementById("name").innerHTML = generateTitle();
}

updateTitle();

var newTitleLink = document.getElementById('again');

addListener(newTitleLink, 'click', function() {
  updateTitle();
});
<|endoftext|>


<commit_before>// //closing tab upon click elsewhere
//
// $(document).click(function () {
//     $("#dropdown-content").hide();
// });
//
// /* Clicks within the dropdown won't make
//  it past the dropdown itself */
// $("#dropdown-content").click(function (e) {
//     e.stopPropagation();
// });

$('.dropdown').click(function (e) {
    e.preventDefault();
    $(this).parent().toggleClass('tap');
});

//Images
function openPage(event, pageName) {
    // Variables in tabs code
    var i, tabcontent, tablinks;

    // Hiding tab content until tab is clicked
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    // Removing the automatic active setting of the class of tab links
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    // Displaying only the tab that was clicked on
    document.getElementById(pageName).style.display = "block";
    event.currentTarget.className += " active";

}

//Allison's Grad-1

var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('grad');
var modalImg = document.getElementById("gen1");
var captionText = document.getElementById("caption");
img.onclick = function () {
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function () {
    modal.style.display = "none";
};

//Brewery Festival- 2

var modal2 = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img2 = document.getElementById('brewery');
var modalImg2 = document.getElementById("gen1");
var captionText2 = document.getElementById("caption");
img2.onclick = function () {
    modal2.style.display = "block";
    modalImg2.src = this.src;
    captionText2.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span2 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span2.onclick = function () {
    modal2.style.display = "none";
};

//Mom's Grad-3

var modal3 = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img3 = document.getElementById('momgrad');
var modalImg3 = document.getElementById("gen1");
var captionText3 = document.getElementById("caption");
img3.onclick = function () {
    modal3.style.display = "block";
    modalImg3.src = this.src;
    captionText3.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span3 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span3.onclick = function () {
    modal3.style.display = "none";
};

//Covered Bridges-4

var modal4 = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img4 = document.getElementById('running');
var modalImg4 = document.getElementById("gen1");
var captionText4 = document.getElementById("caption");
img4.onclick = function () {
    modal4.style.display = "block";
    modalImg4.src = this.src;
    captionText4.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span4 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span4.onclick = function () {
    modal4.style.display = "none";
};

//Flight picture-5

var modal5 = document.getElementById('myModal');

var img5 = document.getElementById('flight');
var modalImg5 = document.getElementById("gen1");
var captionText5 = document.getElementById("caption");
img5.onclick = function () {
    modal5.style.display = "block";
    modalImg5.src = this.src;
    captionText5.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span5 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span5.onclick = function () {
    modal5.style.display = "none";
};

//Picture from Chelsea & Sam's wedding-6

var modal6 = document.getElementById('myModal');

var img6 = document.getElementById('wedding');
var modalImg6 = document.getElementById("gen1");
var captionText6 = document.getElementById("caption");
img6.onclick = function () {
    modal6.style.display = "block";
    modalImg6.src = this.src;
    captionText6.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span6 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span6.onclick = function () {
    modal6.style.display = "none";
};

//Picture TWO from Chelsea & Sam's wedding-7

var modal7 = document.getElementById('myModal');

var img7 = document.getElementById('wedding2');
var modalImg7 = document.getElementById("gen1");
var captionText7 = document.getElementById("caption");
img7.onclick = function () {
    modal7.style.display = "block";
    modalImg7.src = this.src;
    captionText7.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span7 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span7.onclick = function () {
    modal7.style.display = "none";
};

//Christmas 2016 picture-8
var modal8 = document.getElementById('myModal');

var img8 = document.getElementById('xmas');
var modalImg8 = document.getElementById("gen1");
var captionText8 = document.getElementById("caption");
img8.onclick = function () {
    modal8.style.display = "block";
    modalImg8.src = this.src;
    captionText8.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span8 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span8.onclick = function () {
    modal8.style.display = "none";
};

//Happy engagement picture-9
var modal9 = document.getElementById('myModal');

var img9 = document.getElementById('happyeng');
var modalImg9 = document.getElementById("gen1");
var captionText9 = document.getElementById("caption");
img9.onclick = function () {
    modal9.style.display = "block";
    modalImg9.src = this.src;
    captionText9.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span9 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span9.onclick = function () {
    modal9.style.display = "none";
};

//Bench engagement picture-10
var modal10 = document.getElementById('myModal');

var img10 = document.getElementById('bencheng');
var modalImg10 = document.getElementById("gen1");
var captionText10 = document.getElementById("caption");
img10.onclick = function () {
    modal10.style.display = "block";
    modalImg10.src = this.src;
    captionText10.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span10 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span10.onclick = function () {
    modal10.style.display = "none";
};

//Ring engagement picture-11
var modal11 = document.getElementById('myModal');

var img11 = document.getElementById('ringeng');
var modalImg11 = document.getElementById("gen1");
var captionText11 = document.getElementById("caption");
img11.onclick = function () {
    modal11.style.display = "block";
    modalImg11.src = this.src;
    captionText11.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span11 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span11.onclick = function () {
    modal11.style.display = "none";
};

//hug engagement picture-12
var modal12 = document.getElementById('myModal');

var img12 = document.getElementById('hugeng');
var modalImg12 = document.getElementById("gen1");
var captionText12 = document.getElementById("caption");
img12.onclick = function () {
    modal12.style.display = "block";
    modalImg12.src = this.src;
    captionText12.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span12 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span12.onclick = function () {
    modal12.style.display = "none";
};

//eyes engagement picture-13
var modal13 = document.getElementById('myModal');

var img13 = document.getElementById('eyeseng');
var modalImg13 = document.getElementById("gen1");
var captionText13 = document.getElementById("caption");
img13.onclick = function () {
    modal13.style.display = "block";
    modalImg13.src = this.src;
    captionText13.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span13 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span13.onclick = function () {
    modal13.style.display = "none";
};

<commit_msg>responsive<commit_after>//closing tab upon click elsewhere

$(document).click(function () {
    $("#dropdown-content").hide();
});

/* Clicks within the dropdown won't make
 it past the dropdown itself */
$("#dropdown-content").click(function (e) {
    e.stopPropagation();
});

//Images
function openPage(event, pageName) {
    // Variables in tabs code
    var i, tabcontent, tablinks;

    // Hiding tab content until tab is clicked
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    // Removing the automatic active setting of the class of tab links
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    // Displaying only the tab that was clicked on
    document.getElementById(pageName).style.display = "block";
    event.currentTarget.className += " active";

}

//Allison's Grad-1

var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('grad');
var modalImg = document.getElementById("gen1");
var captionText = document.getElementById("caption");
img.onclick = function () {
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function () {
    modal.style.display = "none";
};

//Brewery Festival- 2

var modal2 = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img2 = document.getElementById('brewery');
var modalImg2 = document.getElementById("gen1");
var captionText2 = document.getElementById("caption");
img2.onclick = function () {
    modal2.style.display = "block";
    modalImg2.src = this.src;
    captionText2.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span2 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span2.onclick = function () {
    modal2.style.display = "none";
};

//Mom's Grad-3

var modal3 = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img3 = document.getElementById('momgrad');
var modalImg3 = document.getElementById("gen1");
var captionText3 = document.getElementById("caption");
img3.onclick = function () {
    modal3.style.display = "block";
    modalImg3.src = this.src;
    captionText3.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span3 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span3.onclick = function () {
    modal3.style.display = "none";
};

//Covered Bridges-4

var modal4 = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img4 = document.getElementById('running');
var modalImg4 = document.getElementById("gen1");
var captionText4 = document.getElementById("caption");
img4.onclick = function () {
    modal4.style.display = "block";
    modalImg4.src = this.src;
    captionText4.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span4 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span4.onclick = function () {
    modal4.style.display = "none";
};

//Flight picture-5

var modal5 = document.getElementById('myModal');

var img5 = document.getElementById('flight');
var modalImg5 = document.getElementById("gen1");
var captionText5 = document.getElementById("caption");
img5.onclick = function () {
    modal5.style.display = "block";
    modalImg5.src = this.src;
    captionText5.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span5 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span5.onclick = function () {
    modal5.style.display = "none";
};

//Picture from Chelsea & Sam's wedding-6

var modal6 = document.getElementById('myModal');

var img6 = document.getElementById('wedding');
var modalImg6 = document.getElementById("gen1");
var captionText6 = document.getElementById("caption");
img6.onclick = function () {
    modal6.style.display = "block";
    modalImg6.src = this.src;
    captionText6.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span6 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span6.onclick = function () {
    modal6.style.display = "none";
};

//Picture TWO from Chelsea & Sam's wedding-7

var modal7 = document.getElementById('myModal');

var img7 = document.getElementById('wedding2');
var modalImg7 = document.getElementById("gen1");
var captionText7 = document.getElementById("caption");
img7.onclick = function () {
    modal7.style.display = "block";
    modalImg7.src = this.src;
    captionText7.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span7 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span7.onclick = function () {
    modal7.style.display = "none";
};

//Christmas 2016 picture-8
var modal8 = document.getElementById('myModal');

var img8 = document.getElementById('xmas');
var modalImg8 = document.getElementById("gen1");
var captionText8 = document.getElementById("caption");
img8.onclick = function () {
    modal8.style.display = "block";
    modalImg8.src = this.src;
    captionText8.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span8 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span8.onclick = function () {
    modal8.style.display = "none";
};

//Happy engagement picture-9
var modal9 = document.getElementById('myModal');

var img9 = document.getElementById('happyeng');
var modalImg9 = document.getElementById("gen1");
var captionText9 = document.getElementById("caption");
img9.onclick = function () {
    modal9.style.display = "block";
    modalImg9.src = this.src;
    captionText9.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span9 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span9.onclick = function () {
    modal9.style.display = "none";
};

//Bench engagement picture-10
var modal10 = document.getElementById('myModal');

var img10 = document.getElementById('bencheng');
var modalImg10 = document.getElementById("gen1");
var captionText10 = document.getElementById("caption");
img10.onclick = function () {
    modal10.style.display = "block";
    modalImg10.src = this.src;
    captionText10.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span10 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span10.onclick = function () {
    modal10.style.display = "none";
};

//Ring engagement picture-11
var modal11 = document.getElementById('myModal');

var img11 = document.getElementById('ringeng');
var modalImg11 = document.getElementById("gen1");
var captionText11 = document.getElementById("caption");
img11.onclick = function () {
    modal11.style.display = "block";
    modalImg11.src = this.src;
    captionText11.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span11 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span11.onclick = function () {
    modal11.style.display = "none";
};

//hug engagement picture-12
var modal12 = document.getElementById('myModal');

var img12 = document.getElementById('hugeng');
var modalImg12 = document.getElementById("gen1");
var captionText12 = document.getElementById("caption");
img12.onclick = function () {
    modal12.style.display = "block";
    modalImg12.src = this.src;
    captionText12.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span12 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span12.onclick = function () {
    modal12.style.display = "none";
};

//eyes engagement picture-13
var modal13 = document.getElementById('myModal');

var img13 = document.getElementById('eyeseng');
var modalImg13 = document.getElementById("gen1");
var captionText13 = document.getElementById("caption");
img13.onclick = function () {
    modal13.style.display = "block";
    modalImg13.src = this.src;
    captionText13.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span13 = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span13.onclick = function () {
    modal13.style.display = "none";
};

<|endoftext|>


<commit_before>if (!Detector.webgl) {
  document.body.classList.add("no-ui");
  Detector.addGetWebGLMessage({id: "webgl-error"});
}

var _tempVector = new THREE.Vector3();

var Simulation = {
  init: function init()
  {
    this.initScene();
    this.initGL();
    this.initDom();
    this.initControls();
  },

  initGL: function()
  {
    var self = this;

    // Init THREE.js stuff
    this.camera = new THREE.OrthographicCamera(-1, 1, -1, 1, 0, 1);

    this.camera.lookAt(this.wormholePositionSize);

    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    this.renderer.sortObjects = false;

    this.renderer.autoClear = false;

    this.quadScene = new THREE.Scene();
    this.quadCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);

    this.quadScene.add(new THREE.Mesh(new THREE.PlaneBufferGeometry(2, 2), new THREE.ShaderMaterial({
      uniforms: this.uniforms,

      vertexShader: document.getElementById("vertexShader").textContent,
      fragmentShader: document.getElementById("fragmentShader").textContent,
    })));

    this.renderPasses = [
      new THREE.RenderPass(this.quadScene, this.quadCam),
      new THREE.BloomPass(1.25),
      new THREE.ShaderPass(THREE.CopyShader)
    ];

    this.renderPasses[this.renderPasses.length - 1].renderToScreen = true;

    this.composer = new THREE.EffectComposer(this.renderer);

    this.renderPasses.forEach(function(pass) {
      self.composer.addPass(pass);
    });

    this.rayMatrix = new THREE.Matrix4();
  },

  initDom: function()
  {
    var self = this;

    // Init some DOM stuff
    this.container = document.getElementById("container");
    this.container.appendChild(this.renderer.domElement);

    this.stats = new Stats();
    this.stats.domElement.style.position = "absolute";
    this.stats.domElement.style.top = 0;
    this.stats.domElement.style.zIndex = 100;
    document.body.appendChild(this.stats.domElement);

    var uiToggle = document.querySelector(".ui-toggle input");

    var onUIToggle = function() {
      if (uiToggle.checked) {
        document.body.classList.add("no-ui");
      }
      else {
        document.body.classList.remove("no-ui");
      }
      uiToggle.blur();
    };

    uiToggle.addEventListener("change", onUIToggle);

    onUIToggle();

    var updateResolution = function()
    {
      var size = parseInt(document.querySelector("[name=resolution]:checked").value),
          width = Math.floor(window.innerWidth / size),
          height = Math.floor(window.innerHeight / size);

      self.composer.setSize(width, height);
    };

    this.zoom = 1;

    var onWindowResize = function()
    {
      self.renderer.setSize(window.innerWidth, window.innerHeight);

      var vx, vy;
      if (window.innerWidth > window.innerHeight)
      {
        vx = 1;
        vy = window.innerHeight / window.innerWidth;
      }
      else
      {
        vx = window.innerWidth / window.innerHeight;
        vy = 1;
      }
      self.rayMatrix.set(vx, 0, 0, 0,
                         0, vy, 0, 0,
                         0, 0, -self.zoom, 0,
                         0, 0, 0, 1);

      updateResolution();
    };

    var onWheel = function(e) {
      e.preventDefault();

      var delta = e.delta || (e.deltaX + e.deltaY + e.deltaZ);
      if (delta < 0)
      {
        self.zoom *= 1.06;
      }
      else
      {
        self.zoom /= 1.06;
      }
      self.rayMatrix.elements[10] = -self.zoom;
    };

    window.addEventListener("resize", onWindowResize, false);
    onWindowResize();

    document.querySelector("#resolution").addEventListener("change", function(event) {
      updateResolution();
      event.target.blur();
    }, false);

    window.addEventListener("wheel", onWheel, false);
  },

  initControls: function()
  {
    var self = this;

    // Init the controls
    this.tabletControls = new TabletControls(this.camera, this.container);
    this.tabletControls.movementSpeed = 1.3;

    this.keyboardControls = new THREE.FlyControls(this.camera, this.container);
    this.keyboardControls.movementSpeed = 1;
    this.keyboardControls.domElement = this.container;
    this.keyboardControls.rollSpeed = Math.PI / 3;
    this.keyboardControls.autoForward = false;
    this.keyboardControls.dragToLook = false;

    var keypress = function(event)
    {
      if (event.charCode == 32)
      {
        if (!self.keyboardControls.dragToLook)
        {
          self.keyboardControls.moveState.yawLeft = 0;
          self.keyboardControls.moveState.pitchDown = 0;
        }
        self.keyboardControls.dragToLook = !self.keyboardControls.dragToLook;
      }

      // Pretty sure we don't need tablet controls when a keyboard event is triggered.
      self.tabletControls.disconnect();

      document.body.classList.remove("tablet");
    };

    window.addEventListener("keypress", keypress, false);

    // Disable tablet controls until we get some indication that we're on a tablet
    this.tabletControls.disconnect();

    var deviceListener = function(event) {
      if (event.alpha === null) return;

      self.tabletControls.connect();

      window.removeEventListener("deviceorientation", deviceListener, false);

      document.body.classList.add("tablet");
    };

    window.addEventListener("deviceorientation", deviceListener, false);
  },

  initScene: function()
  {
    this.wormholePositionSize = new THREE.Vector4(10, 0.0, -32, 0.8);
    this.blackholePositionSize = new THREE.Vector4(0.0, -250.0, 250.0, 12.5);
    this.saturnPositionSize = new THREE.Vector4(-14, 5, -40, 8.0);
    this.planetPositionSize = new THREE.Vector4(7.6, 62, -50, 0.08);

    this.planetPositionSize.x += this.blackholePositionSize.x;
    this.planetPositionSize.y += this.blackholePositionSize.y;
    this.planetPositionSize.z += this.blackholePositionSize.z;

    // Ring definition - xyz is normal going through ring. Its magnitude determines inner radius.
    // w component determines outer radius
    this.blackholeDisk = new THREE.Vector4(-12, 12, 6, 150.0);
    this.saturnRings = new THREE.Vector4(0, 9.22, 0, 17.1);

    var numTexturesLoaded = 0;
    var textureCount = 0;
    var updateProgress = function() {
      numTexturesLoaded++;
      if (numTexturesLoaded == textureCount)
      {
        var el = document.getElementById("loading");
        el.parentElement.removeChild(el);
        Simulation.inited = true;
      }
    };

    this.wormholeGravityRatio = 0.25;

    this.uniforms = {
      "wormhole": { type: "v4", value: this.wormholePositionSize },
      "wormholeGravityRatio": { type: "f", value: this.wormholeGravityRatio },
      // 1 = like a black hole but with the mouth at the event horizon (big gravitational well)
      // 0 = completely flat space (no gravity at all)
      "blackhole": { type: "v4", value: this.blackholePositionSize },

      "saturn":  { type: "v4", value: this.saturnPositionSize },
      "planet":  { type: "v4", value: this.planetPositionSize },

      "blackholeDisk": { type: "v4", value: this.blackholeDisk },
      "saturnRings": { type: "v4", value: this.saturnRings },

      "planetDiffuse": { type: "v3", value: new THREE.Vector3(0.58,0.85,0.96) },
      "planetSpecular": { type: "v3", value: new THREE.Vector3(0.1,0.1,0.1) },
      "texSaturn": { type: "t", value: THREE.ImageUtils.loadTexture("saturn.jpg", null, updateProgress) },
      "texSaturnRings": { type: "t", value: THREE.ImageUtils.loadTexture("saturnrings.png", null, updateProgress) },
      "texGalaxy1":  { type: "t", value: THREE.ImageUtils.loadTexture("galaxy1.png", null, updateProgress) },
      "texGalaxy2":  { type: "t", value: THREE.ImageUtils.loadTexture("galaxy2.png", null, updateProgress) },
      "texAccretionDisk": { type: "t", value: THREE.ImageUtils.loadTexture("accretion_disk.png", null, updateProgress) },

      "lightDirection": { type: "v3", value: (new THREE.Vector3(-4, 2, 3)).normalize() },

      "rayMatrix": { type: "m4", value: new THREE.Matrix4() },

      "startGalaxy": { type: "i", value: 0 },
      "cameraPosition": { type: "v3" },
    };

    for (var uniform in this.uniforms)
    {
      if (this.uniforms[uniform].type == "t") textureCount++;
    }

    this.uniforms.texAccretionDisk.value.wrapS = THREE.RepeatWrapping

    // Some entities to calculate with
    this.wormholeSphere = new THREE.Sphere(this.wormholePositionSize, this.wormholePositionSize.w);
  },

  step: function()
  {
    if (this.inited)
    {
      this.update();
    }
    this.render();

    this.stats.update();
  },

  start: function()
  {
    var self = this;

    this.clock = new THREE.Clock();

    function animate()
    {
      requestAnimationFrame(animate);

      self.step();
    }

    animate();
  },

  update: (function() {

    var prevPosition   = new THREE.Vector3(),
        prevQuaternion = new THREE.Quaternion(),
        velocity       = new THREE.Vector3(),
        direction      = new THREE.Vector3(),
        intersection   = new THREE.Vector3(),
        axis           = new THREE.Vector3(),
        rotation       = new THREE.Quaternion(),
        temp           = new THREE.Vector3(),
        ray            = new THREE.Ray();

    return function() {
      var delta = this.clock.getDelta(),
          wormholePosition = this.wormholePositionSize;

      prevPosition.copy(this.camera.position);
      prevQuaternion.copy(this.camera.quaternion);

      // Handle input
      this.keyboardControls.update(delta);
      this.tabletControls.update(delta);

      // Apply wormhole curvature/gravity.
      this.applyWormholeCurvature(prevPosition, delta);

      // Check if we're going through the wormhole
      velocity.subVectors(this.camera.position, prevPosition);
      direction.copy(velocity).normalize();

      ray.set(prevPosition, direction);

      var at = ray.intersectSphere(this.wormholeSphere, intersection);
      if (at && at.distanceToSquared(prevPosition) <= velocity.lengthSq())
      {
        // Rotate 180 degrees around axis pointing at exit point
        axis.subVectors(intersection, wormholePosition).normalize();
        rotation.setFromAxisAngle(axis, Math.PI);
        this.camera.quaternion.multiplyQuaternions(rotation, this.camera.quaternion);

        // Set new camera position a tiny bit outside mirrored intersection point
        this.camera.position.copy(wormholePosition).add(temp.subVectors(wormholePosition, intersection).multiplyScalar(1.0001));

        this.uniforms.startGalaxy.value = 1 - this.uniforms.startGalaxy.value;
      }
    };
  })(),

  render: function()
  {
    this.uniforms.rayMatrix.value.makeRotationFromQuaternion(this.camera.quaternion);
    this.uniforms.rayMatrix.value.multiply(this.rayMatrix);

    this.uniforms.cameraPosition.value = this.camera.position;

    this.renderer.clear();
    this.composer.render();
  },

  applyWormholeCurvature: (function() {

    var velocity = new THREE.Vector3(),
        newVelocity = new THREE.Vector3(),
        gravityVector = new THREE.Vector3(),
        acceleration = new THREE.Vector3(),
        rotation = new THREE.Quaternion();

    return function(prevPosition, delta) {
      velocity.subVectors(this.camera.position, prevPosition).multiplyScalar(1 / delta);
      var speedSq = velocity.lengthSq();
      newVelocity.copy(velocity);

      gravityVector.subVectors(this.wormholePositionSize, prevPosition);
      var rayDistance = gravityVector.length() - this.wormholePositionSize.w * (1 - this.wormholeGravityRatio);
      var amount = this.wormholeGravityRatio / rayDistance;
      acceleration.copy(gravityVector.normalize()).multiplyScalar(this.wormholePositionSize.w * speedSq * amount * amount);

      newVelocity.add(acceleration.multiplyScalar(delta));

      this.camera.position.addVectors(prevPosition, newVelocity.multiplyScalar(delta));

      rotation.setFromUnitVectors(velocity.normalize(), newVelocity.normalize());
      this.camera.quaternion.multiplyQuaternions(rotation, this.camera.quaternion);
    };
  })(),
};

Simulation.init();
Simulation.start();<commit_msg>Fixed bug caused by a deltatime of 0<commit_after>if (!Detector.webgl) {
  document.body.classList.add("no-ui");
  Detector.addGetWebGLMessage({id: "webgl-error"});
}

var _tempVector = new THREE.Vector3();

var Simulation = {
  init: function init()
  {
    this.initScene();
    this.initGL();
    this.initDom();
    this.initControls();
  },

  initGL: function()
  {
    var self = this;

    // Init THREE.js stuff
    this.camera = new THREE.OrthographicCamera(-1, 1, -1, 1, 0, 1);

    this.camera.lookAt(this.wormholePositionSize);

    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    this.renderer.sortObjects = false;

    this.renderer.autoClear = false;

    this.quadScene = new THREE.Scene();
    this.quadCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);

    this.quadScene.add(new THREE.Mesh(new THREE.PlaneBufferGeometry(2, 2), new THREE.ShaderMaterial({
      uniforms: this.uniforms,

      vertexShader: document.getElementById("vertexShader").textContent,
      fragmentShader: document.getElementById("fragmentShader").textContent,
    })));

    this.renderPasses = [
      new THREE.RenderPass(this.quadScene, this.quadCam),
      new THREE.BloomPass(1.25),
      new THREE.ShaderPass(THREE.CopyShader)
    ];

    this.renderPasses[this.renderPasses.length - 1].renderToScreen = true;

    this.composer = new THREE.EffectComposer(this.renderer);

    this.renderPasses.forEach(function(pass) {
      self.composer.addPass(pass);
    });

    this.rayMatrix = new THREE.Matrix4();
  },

  initDom: function()
  {
    var self = this;

    // Init some DOM stuff
    this.container = document.getElementById("container");
    this.container.appendChild(this.renderer.domElement);

    this.stats = new Stats();
    this.stats.domElement.style.position = "absolute";
    this.stats.domElement.style.top = 0;
    this.stats.domElement.style.zIndex = 100;
    document.body.appendChild(this.stats.domElement);

    var uiToggle = document.querySelector(".ui-toggle input");

    var onUIToggle = function() {
      if (uiToggle.checked) {
        document.body.classList.add("no-ui");
      }
      else {
        document.body.classList.remove("no-ui");
      }
      uiToggle.blur();
    };

    uiToggle.addEventListener("change", onUIToggle);

    onUIToggle();

    var updateResolution = function()
    {
      var size = parseInt(document.querySelector("[name=resolution]:checked").value),
          width = Math.floor(window.innerWidth / size),
          height = Math.floor(window.innerHeight / size);

      self.composer.setSize(width, height);
    };

    this.zoom = 1;

    var onWindowResize = function()
    {
      self.renderer.setSize(window.innerWidth, window.innerHeight);

      var vx, vy;
      if (window.innerWidth > window.innerHeight)
      {
        vx = 1;
        vy = window.innerHeight / window.innerWidth;
      }
      else
      {
        vx = window.innerWidth / window.innerHeight;
        vy = 1;
      }
      self.rayMatrix.set(vx, 0, 0, 0,
                         0, vy, 0, 0,
                         0, 0, -self.zoom, 0,
                         0, 0, 0, 1);

      updateResolution();
    };

    var onWheel = function(e) {
      e.preventDefault();

      var delta = e.delta || (e.deltaX + e.deltaY + e.deltaZ);
      if (delta < 0)
      {
        self.zoom *= 1.06;
      }
      else
      {
        self.zoom /= 1.06;
      }
      self.rayMatrix.elements[10] = -self.zoom;
    };

    window.addEventListener("resize", onWindowResize, false);
    onWindowResize();

    document.querySelector("#resolution").addEventListener("change", function(event) {
      updateResolution();
      event.target.blur();
    }, false);

    window.addEventListener("wheel", onWheel, false);
  },

  initControls: function()
  {
    var self = this;

    // Init the controls
    this.tabletControls = new TabletControls(this.camera, this.container);
    this.tabletControls.movementSpeed = 1.3;

    this.keyboardControls = new THREE.FlyControls(this.camera, this.container);
    this.keyboardControls.movementSpeed = 1;
    this.keyboardControls.domElement = this.container;
    this.keyboardControls.rollSpeed = Math.PI / 3;
    this.keyboardControls.autoForward = false;
    this.keyboardControls.dragToLook = false;

    var keypress = function(event)
    {
      if (event.charCode == 32)
      {
        if (!self.keyboardControls.dragToLook)
        {
          self.keyboardControls.moveState.yawLeft = 0;
          self.keyboardControls.moveState.pitchDown = 0;
        }
        self.keyboardControls.dragToLook = !self.keyboardControls.dragToLook;
      }

      // Pretty sure we don't need tablet controls when a keyboard event is triggered.
      self.tabletControls.disconnect();

      document.body.classList.remove("tablet");
    };

    window.addEventListener("keypress", keypress, false);

    // Disable tablet controls until we get some indication that we're on a tablet
    this.tabletControls.disconnect();

    var deviceListener = function(event) {
      if (event.alpha === null) return;

      self.tabletControls.connect();

      window.removeEventListener("deviceorientation", deviceListener, false);

      document.body.classList.add("tablet");
    };

    window.addEventListener("deviceorientation", deviceListener, false);
  },

  initScene: function()
  {
    this.wormholePositionSize = new THREE.Vector4(10, 0.0, -32, 0.8);
    this.blackholePositionSize = new THREE.Vector4(0.0, -250.0, 250.0, 12.5);
    this.saturnPositionSize = new THREE.Vector4(-14, 5, -40, 8.0);
    this.planetPositionSize = new THREE.Vector4(7.6, 62, -50, 0.08);

    this.planetPositionSize.x += this.blackholePositionSize.x;
    this.planetPositionSize.y += this.blackholePositionSize.y;
    this.planetPositionSize.z += this.blackholePositionSize.z;

    // Ring definition - xyz is normal going through ring. Its magnitude determines inner radius.
    // w component determines outer radius
    this.blackholeDisk = new THREE.Vector4(-12, 12, 6, 150.0);
    this.saturnRings = new THREE.Vector4(0, 9.22, 0, 17.1);

    var numTexturesLoaded = 0;
    var textureCount = 0;
    var updateProgress = function() {
      numTexturesLoaded++;
      if (numTexturesLoaded == textureCount)
      {
        var el = document.getElementById("loading");
        el.parentElement.removeChild(el);
        Simulation.inited = true;
      }
    };

    this.wormholeGravityRatio = 0.25;

    this.uniforms = {
      "wormhole": { type: "v4", value: this.wormholePositionSize },
      "wormholeGravityRatio": { type: "f", value: this.wormholeGravityRatio },
      // 1 = like a black hole but with the mouth at the event horizon (big gravitational well)
      // 0 = completely flat space (no gravity at all)
      "blackhole": { type: "v4", value: this.blackholePositionSize },

      "saturn":  { type: "v4", value: this.saturnPositionSize },
      "planet":  { type: "v4", value: this.planetPositionSize },

      "blackholeDisk": { type: "v4", value: this.blackholeDisk },
      "saturnRings": { type: "v4", value: this.saturnRings },

      "planetDiffuse": { type: "v3", value: new THREE.Vector3(0.58,0.85,0.96) },
      "planetSpecular": { type: "v3", value: new THREE.Vector3(0.1,0.1,0.1) },
      "texSaturn": { type: "t", value: THREE.ImageUtils.loadTexture("saturn.jpg", null, updateProgress) },
      "texSaturnRings": { type: "t", value: THREE.ImageUtils.loadTexture("saturnrings.png", null, updateProgress) },
      "texGalaxy1":  { type: "t", value: THREE.ImageUtils.loadTexture("galaxy1.png", null, updateProgress) },
      "texGalaxy2":  { type: "t", value: THREE.ImageUtils.loadTexture("galaxy2.png", null, updateProgress) },
      "texAccretionDisk": { type: "t", value: THREE.ImageUtils.loadTexture("accretion_disk.png", null, updateProgress) },

      "lightDirection": { type: "v3", value: (new THREE.Vector3(-4, 2, 3)).normalize() },

      "rayMatrix": { type: "m4", value: new THREE.Matrix4() },

      "startGalaxy": { type: "i", value: 0 },
      "cameraPosition": { type: "v3" },
    };

    for (var uniform in this.uniforms)
    {
      if (this.uniforms[uniform].type == "t") textureCount++;
    }

    this.uniforms.texAccretionDisk.value.wrapS = THREE.RepeatWrapping

    // Some entities to calculate with
    this.wormholeSphere = new THREE.Sphere(this.wormholePositionSize, this.wormholePositionSize.w);
  },

  step: function()
  {
    if (this.inited)
    {
      this.update();
    }
    this.render();

    this.stats.update();
  },

  start: function()
  {
    var self = this;

    this.clock = new THREE.Clock();

    function animate()
    {
      requestAnimationFrame(animate);

      self.step();
    }

    animate();
  },

  update: (function() {

    var prevPosition   = new THREE.Vector3(),
        prevQuaternion = new THREE.Quaternion(),
        velocity       = new THREE.Vector3(),
        direction      = new THREE.Vector3(),
        intersection   = new THREE.Vector3(),
        axis           = new THREE.Vector3(),
        rotation       = new THREE.Quaternion(),
        temp           = new THREE.Vector3(),
        ray            = new THREE.Ray();

    return function() {
      var delta = this.clock.getDelta(),
          wormholePosition = this.wormholePositionSize;

      // TODO: figure out why delta can become so small
      if (delta < 0.001)
      {
        delta = 0.001;
      }

      prevPosition.copy(this.camera.position);
      prevQuaternion.copy(this.camera.quaternion);

      // Handle input
      this.keyboardControls.update(delta);
      this.tabletControls.update(delta);

      // Apply wormhole curvature/gravity.
      this.applyWormholeCurvature(prevPosition, delta);

      // Check if we're going through the wormhole
      velocity.subVectors(this.camera.position, prevPosition);
      direction.copy(velocity).normalize();

      ray.set(prevPosition, direction);

      var at = ray.intersectSphere(this.wormholeSphere, intersection);
      if (at && at.distanceToSquared(prevPosition) <= velocity.lengthSq())
      {
        // Rotate 180 degrees around axis pointing at exit point
        axis.subVectors(intersection, wormholePosition).normalize();
        rotation.setFromAxisAngle(axis, Math.PI);
        this.camera.quaternion.multiplyQuaternions(rotation, this.camera.quaternion);

        // Set new camera position a tiny bit outside mirrored intersection point
        this.camera.position.copy(wormholePosition).add(temp.subVectors(wormholePosition, intersection).multiplyScalar(1.0001));

        this.uniforms.startGalaxy.value = 1 - this.uniforms.startGalaxy.value;
      }
    };
  })(),

  render: function()
  {
    this.uniforms.rayMatrix.value.makeRotationFromQuaternion(this.camera.quaternion);
    this.uniforms.rayMatrix.value.multiply(this.rayMatrix);

    this.uniforms.cameraPosition.value = this.camera.position;

    this.renderer.clear();
    this.composer.render();
  },

  applyWormholeCurvature: (function() {

    var velocity = new THREE.Vector3(),
        newVelocity = new THREE.Vector3(),
        gravityVector = new THREE.Vector3(),
        acceleration = new THREE.Vector3(),
        rotation = new THREE.Quaternion();

    return function(prevPosition, delta) {
      velocity.subVectors(this.camera.position, prevPosition).multiplyScalar(1 / delta);
      var speedSq = velocity.lengthSq();
      newVelocity.copy(velocity);

      gravityVector.subVectors(this.wormholePositionSize, prevPosition);
      var rayDistance = gravityVector.length() - this.wormholePositionSize.w * (1 - this.wormholeGravityRatio);
      var amount = this.wormholeGravityRatio / rayDistance;
      acceleration.copy(gravityVector.normalize()).multiplyScalar(this.wormholePositionSize.w * speedSq * amount * amount);

      newVelocity.add(acceleration.multiplyScalar(delta));

      this.camera.position.addVectors(prevPosition, newVelocity.multiplyScalar(delta));

      rotation.setFromUnitVectors(velocity.normalize(), newVelocity.normalize());
      this.camera.quaternion.multiplyQuaternions(rotation, this.camera.quaternion);
    };
  })(),
};

Simulation.init();
Simulation.start();<|endoftext|>


<commit_before>---
---

function loadSuccess() {
  document.getElementById("blockedInfo").innerHTML = ""
  + "YouTube Access Check Succeeded.";
  var image_x = document.getElementById("blockedImage");
  image_x.parentNode.removeChild(image_x);
  ga("send", "event", "YouTube Success", "YouTube Load Success");
}
function loadError() {
  var site = "YouTube";
  document.getElementById("blockedInfo").innerHTML = "
"
  + "" + site + " Blocked: You seem to be accessing this website from a location where "
  + site + " is blocked. As part of this website uses items from " + site + ", "
  + "please contact your network administrator in order to view this website as intended.
";
  var image_x = document.getElementById("blockedImage");
  image_x.parentNode.removeChild(image_x);
  ga("send", "event", "YouTube Error", "YouTube Load Error");
}
$(window).on("load", function() {
  //Fix for header scroll http://stackoverflow.com/a/25887125/6820516
  var elements = document.querySelectorAll('input,select,textarea');

  for (var i = elements.length; i--;) {
      elements[i].addEventListener('invalid', function () {
          this.scrollIntoView(false);
      });
  }

  $("time.timeago").timeago();
  $.timeago.settings.allowFuture = true;

  $("[data-toggle=\"tooltip\"]").tooltip();
  $(".marquee").css("animation-duration", ($(window).width() + $(".marquee").width()) / 30 + "s")
});

{% if page.editabletable %}
  // Code below is modified from http://codepen.io/ashblue/pen/mCtuA/

  var $TABLE = $('#table');

  $('.table-add').click(function () {
    var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
    $TABLE.find('table').append($clone);
  });

  $('.table-remove').click(function () {
    $(this).parents('tr').detach();
  });

  // A few jQuery helpers for exporting only
  jQuery.fn.pop = [].pop;
  jQuery.fn.shift = [].shift;

  function export() {
    var $rows = $TABLE.find('tr:not(:hidden)');
    var headers = [];
    var data = "score:\n";

    // Get the headers (add special header logic here)
    $($rows.shift()).find('th:not(:empty)').each(function () {
      headers.push($(this).text().toLowerCase());
    });

    // Turn all existing rows into a loopable array
    $rows.each(function () {
      var $td = $(this).find('td');

      // Use the headers from earlier to name our hash keys
      headers.forEach(function (header, i) {
        if (header == "team") {
          data += "  - team: " + $td.eq(i).text();;
        } else if (header == "points") {
          data += "    points: " + $td.eq(i).text();;
        }
      });
    });

    // Output the result
    return data;
  });
{% endif %}

// End code modified from http://codepen.io/ashblue/pen/mCtuA/

function submit(type, values) {
  var filename = encodeURIComponent("_announcements/"
    + moment(document.getElementById("date").value).format("YYYY-MM-DD")
    + "-" + getSlug(document.getElementById("title").value) + ".md");

  var content = "---\nenabled: true\n";
  $.each(values, function( index, value ) {
    if (document.getElementById(value).value) {
      if (value == "date") {
        content += value + ": " + moment(document.getElementById("date").value)
          .format("YYYY-MM-DD hh:MM A") + "\n";
      } else if (value == "score") {
        content += export();
      } else {
        content += value + ": " + document.getElementById(value).value + "\n";
      }
    }
  });
  content += "---\n"

  content = encodeURIComponent(content);

  message = encodeURIComponent("[New Announcement] "
    + moment(document.getElementById("date").value).format("YYYY-MM-DD")
    + "-" + document.getElementById("title").value);
  description = encodeURIComponent("Submitted via {{page.url}}");
  window.location.href = "{{ site.github.repository_url }}/new/master?filename=" + filename
    + "&value=" + content + "&message=" + message
    + "&description=" + description;
}
<commit_msg>Forgot the JS is not included in a page...<commit_after>---
---

function loadSuccess() {
  document.getElementById("blockedInfo").innerHTML = ""
  + "YouTube Access Check Succeeded.";
  var image_x = document.getElementById("blockedImage");
  image_x.parentNode.removeChild(image_x);
  ga("send", "event", "YouTube Success", "YouTube Load Success");
}
function loadError() {
  var site = "YouTube";
  document.getElementById("blockedInfo").innerHTML = "
"
  + "" + site + " Blocked: You seem to be accessing this website from a location where "
  + site + " is blocked. As part of this website uses items from " + site + ", "
  + "please contact your network administrator in order to view this website as intended.
";
  var image_x = document.getElementById("blockedImage");
  image_x.parentNode.removeChild(image_x);
  ga("send", "event", "YouTube Error", "YouTube Load Error");
}
$(window).on("load", function() {
  //Fix for header scroll http://stackoverflow.com/a/25887125/6820516
  var elements = document.querySelectorAll('input,select,textarea');

  for (var i = elements.length; i--;) {
      elements[i].addEventListener('invalid', function () {
          this.scrollIntoView(false);
      });
  }

  $("time.timeago").timeago();
  $.timeago.settings.allowFuture = true;

  $("[data-toggle=\"tooltip\"]").tooltip();
  $(".marquee").css("animation-duration", ($(window).width() + $(".marquee").width()) / 30 + "s")
});

// Code below is modified from http://codepen.io/ashblue/pen/mCtuA/

var $TABLE = $('#table');

$('.table-add').click(function () {
  var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
  $TABLE.find('table').append($clone);
});

$('.table-remove').click(function () {
  $(this).parents('tr').detach();
});

// A few jQuery helpers for exporting only
jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;

function export() {
  var $rows = $TABLE.find('tr:not(:hidden)');
  var headers = [];
  var data = "score:\n";

  // Get the headers (add special header logic here)
  $($rows.shift()).find('th:not(:empty)').each(function () {
    headers.push($(this).text().toLowerCase());
  });

  // Turn all existing rows into a loopable array
  $rows.each(function () {
    var $td = $(this).find('td');

    // Use the headers from earlier to name our hash keys
    headers.forEach(function (header, i) {
      if (header == "team") {
        data += "  - team: " + $td.eq(i).text();;
      } else if (header == "points") {
        data += "    points: " + $td.eq(i).text();;
      }
    });
  });

  // Output the result
  return data;
});

// End code modified from http://codepen.io/ashblue/pen/mCtuA/

function submit(type, values) {
  var filename = encodeURIComponent("_announcements/"
    + moment(document.getElementById("date").value).format("YYYY-MM-DD")
    + "-" + getSlug(document.getElementById("title").value) + ".md");

  var content = "---\nenabled: true\n";
  $.each(values, function( index, value ) {
    if (document.getElementById(value).value) {
      if (value == "date") {
        content += value + ": " + moment(document.getElementById("date").value)
          .format("YYYY-MM-DD hh:MM A") + "\n";
      } else if (value == "score") {
        content += export();
      } else {
        content += value + ": " + document.getElementById(value).value + "\n";
      }
    }
  });
  content += "---\n"

  content = encodeURIComponent(content);

  message = encodeURIComponent("[New Announcement] "
    + moment(document.getElementById("date").value).format("YYYY-MM-DD")
    + "-" + document.getElementById("title").value);
  description = encodeURIComponent("Submitted via {{page.url}}");
  window.location.href = "{{ site.github.repository_url }}/new/master?filename=" + filename
    + "&value=" + content + "&message=" + message
    + "&description=" + description;
}
<|endoftext|>


<commit_before>var sampleList = [{start: 30, end: 150}, {start: 540, end: 600}, {start: 560, end: 620}, {start: 610, end: 670}];
                //{9:30 am - 11:30 am}, {6:00 pm - 7:00 pm}, {6:20 pm - 7:20 pm}, {7:10 pm - 8:10 pm}
/*
Methods for Measurements:
    height & margin-top: defines the units 'px' since time events are specified in px.
    height: defines the height/length of the event card per 30min slot
    marginTop: defines the margin of the card from the top of the container

    width & left: units '%' relative to container width
    widht: defines the width/breadth of the event card (varies with number of overlaping cards)
    left: defines the position of the card on the X-axis (for overlaping events)
*/
var eventCardDimensions = {
    height: 22,
    width: 93,
    marginTop: 24,
    left: 32
};
window.onload = function(){
    layOutDay(sampleList);
};
function layOutDay(events) {
    var markupFragment, $div;
    //Sort events by start time
    events.sort(function(a,b){
        return a.start - b.start;
    });

    //Calculate the margin-top for each event card
    evalMarginTop(events);

    //Calculate the height for each event card
    evalHeight(events);

    //Calculate the width and left(pos) of each event card
    evalWidthAndLeft(events);

    //Write markup to it
    markupFragment = makeCalendarEventCards(events);

    document.getElementsByClassName('events-container')[0].appendChild(markupFragment);
}

function groupOverlappingEvents(list){
    /*
        * For each event find overlapping events and maximum #columns required
        * Optimize by ignoring events that overlap with other events - theta(n^2)
    */
    var overlappingEvents = [],
        maxColumns = 0;
    list.forEach(function(meeting, index){
        //Optimization: don't form conflict list for already processed events
        if(meeting.isProcessed){
            return;
        }
        overlappingEvents[index] = [];
        for(var i = 0; i < list.length; i++){
            if(i === index){
                continue;
            }
            if(isOverLappingEvents(meeting, list[i])){
                list[i].isProcessed = true;
                overlappingEvents[index].push(list[i]);
            }
        }
    });
    return overlappingEvents;
}

function isOverLappingEvents(meeting1, meeting2){
    //If meeting 1 starts while meeting 2 is in progress
    if(meeting1.start > meeting2.start && meeting1.start < meeting2.end){
        return true;
    }
    //If meeting 2 starts while meeting 1 is in progress
    if(meeting2.start > meeting1.start && meeting2.start < meeting1.end){
        return true;
    }
    return false;
}

function evalWidthAndLeft(eventList){
//Each event in the group has to have the same width which totals to W (W=93% based on our styles)
    var overLappingEvents = groupOverlappingEvents(eventList),
        maxWidth = eventCardDimensions.width * 100,   //*100 -> optimize for rounding to second decimal place
        width, left;
    console.log(overLappingEvents);
    //Iterate - start with events having max overlap
    overLappingEvents.forEach(function(overlaps, index){
        //ForEach will ignore all undefined events (events which were already defined in another overlapping list)

        left = 0;
        //Calc width of each card & round to the nearest hundredth

        width = (Math.ceil(maxWidth/(overlaps.length+1)))/100;
        eventList[index].left = left;
        eventList[index].width = width;
        left += width;
        overlaps.forEach(function(conflictingMeeting){
            if(!conflictingMeeting.width){
                conflictingMeeting.width = width;
                conflictingMeeting.left = left;
            }
            left += width;

            //sanitize the object
            delete conflictingMeeting.isProcessed;
        });
    });
    console.log(eventList);
}

function evalMarginTop(list){
    var k = eventCardDimensions.marginTop * 10,   //*10 -> optimization -> precalc of constants
        marginTop;
    list.forEach(function(entry){
        //Eval marginTop as the distance for 9:00 AM (00)
        marginTop = (entry.start*k)/30;
        //Round to the nearest tenth (px is accurate for 1 decimal notation)
        entry.marginTop = Math.ceil(marginTop)/10;
    });
}

function evalHeight(list){
    var height;
    list.forEach(function(entry){
        //Eval height as the distance from (end-start)

        //Round to nearest tens
        height = (Math.round((entry.end - entry.start)/10))*10;
        height = (height*eventCardDimensions.height)/30;
        //Round to the nearest hundredth
        entry.height = Math.round(height);
    });
}

function makeCalendarEventCards(nestedList){
    var markup = '',
        eventCards = document.createDocumentFragment(),
        $small = document.createElement('small'),
        $p = document.createElement('p'),
        $div = document.createElement('div'),
        $clonedNode;

        //TODO find interesting items
        $p.innerHTML = 'Sample Item:';
        $small.innerHTML = 'Sample Location';

        $div.className = 'event';
        $div.appendChild($p);
        $div.appendChild($small);

    for(var i = 0; i < nestedList.length; i++){
        for(var j = 0; j < nestedList[i].length; j++){
            $clonedNode = $div.cloneNode(true);
            $clonedNode.children[0].innerHTML +=  nestedList[i][j].start + '-' + nestedList[i][j].end;
            $clonedNode.style.width = nestedList[i][j].width+'%';
            $clonedNode.style.height = nestedList[i][j].height+'px';
            $clonedNode.style.left = nestedList[i][j].left+'%';
            $clonedNode.style.marginTop = nestedList[i][j].marginTop+'px';
            eventCards.appendChild($clonedNode);
        }
    }
    return eventCards;
}
<commit_msg>Fixes old code<commit_after>var sampleList = [{start: 30, end: 150}, {start: 540, end: 600}, {start: 560, end: 620}, {start: 610, end: 670}];
                //{9:30 am - 11:30 am}, {6:00 pm - 7:00 pm}, {6:20 pm - 7:20 pm}, {7:10 pm - 8:10 pm}
/*
Methods for Measurements:
    height & margin-top: defines the units 'px' since time events are specified in px.
    height: defines the height/length of the event card per 30min slot
    marginTop: defines the margin of the card from the top of the container

    width & left: units '%' relative to container width
    widht: defines the width/breadth of the event card (varies with number of overlaping cards)
    left: defines the position of the card on the X-axis (for overlaping events)
*/
var eventCardDimensions = {
    height: 22,
    width: 93,
    marginTop: 24,
    left: 32
};
window.onload = function(){
    layOutDay(sampleList);
};
function layOutDay(events) {
    var markupFragment, $div;
    //Sort events by start time
    events.sort(function(a,b){
        return a.start - b.start;
    });

    //Calculate the margin-top for each event card
    evalMarginTop(events);

    //Calculate the height for each event card
    evalHeight(events);

    //Calculate the width and left(pos) of each event card
    evalWidthAndLeft(events);

    //Write markup to it
    markupFragment = makeCalendarEventCards(events);

    document.getElementsByClassName('events-container')[0].appendChild(markupFragment);
}

function groupOverlappingEvents(list){
    /*
        * For each event find overlapping events and maximum #columns required
        * Optimize by ignoring events that overlap with other events - theta(n^2)
    */
    var overlappingEvents = [],
        maxColumns = 0;
    list.forEach(function(meeting, index){
        //Optimization: don't form conflict list for already processed events
        if(meeting.isProcessed){
            return;
        }
        overlappingEvents[index] = [];
        for(var i = 0; i < list.length; i++){
            if(i === index){
                continue;
            }
            if(isOverLappingEvents(meeting, list[i])){
                list[i].isProcessed = true;
                overlappingEvents[index].push(list[i]);
            }
        }
    });
    return overlappingEvents;
}

function isOverLappingEvents(meeting1, meeting2){
    //If meeting 1 starts while meeting 2 is in progress
    if(meeting1.start > meeting2.start && meeting1.start < meeting2.end){
        return true;
    }
    //If meeting 2 starts while meeting 1 is in progress
    if(meeting2.start > meeting1.start && meeting2.start < meeting1.end){
        return true;
    }
    return false;
}

function evalWidthAndLeft(eventList){
//Each event in the group has to have the same width which totals to W (W=93% based on our styles)
    var overLappingEvents = groupOverlappingEvents(eventList),
        maxWidth = eventCardDimensions.width * 100,   //*100 -> optimize for rounding to second decimal place
        width, left;
    //Iterate - start with events having max overlap
    overLappingEvents.forEach(function(overlaps, index){
        //ForEach will ignore all undefined events (events which were already defined in another overlapping list)

        left = 0;
        //Calc width of each card & round to the nearest hundredth

        width = (Math.ceil(maxWidth/(overlaps.length+1)))/100;
        eventList[index].left = left;
        eventList[index].width = width;
        left += width;
        overlaps.forEach(function(conflictingMeeting){
            if(!conflictingMeeting.width){
                conflictingMeeting.width = width;
                conflictingMeeting.left = left;
            }
            left += width;

            //sanitize the object
            delete conflictingMeeting.isProcessed;
        });
    });
}

function evalMarginTop(list){
    var k = eventCardDimensions.marginTop * 10,   //*10 -> optimization -> precalc of constants
        marginTop;
    list.forEach(function(entry){
        //Eval marginTop as the distance for 9:00 AM (00)
        marginTop = (entry.start*k)/30;
        //Round to the nearest tenth (px is accurate for 1 decimal notation)
        entry.marginTop = Math.ceil(marginTop)/10;
    });
}

function evalHeight(list){
    var height;
    list.forEach(function(entry){
        //Eval height as the distance from (end-start)

        //Round to nearest tens
        height = (Math.round((entry.end - entry.start)/10))*10;
        height = (height*eventCardDimensions.height)/30;
        //Round to the nearest hundredth
        entry.height = Math.round(height);
    });
}

function makeCalendarEventCards(eventList){
    var markup = '',
        eventCards = document.createDocumentFragment(),
        $small = document.createElement('small'),
        $p = document.createElement('p'),
        $div = document.createElement('div'),
        $clonedNode;

        //TODO find interesting items
    $p.innerHTML = 'Sample Item:';
    $small.innerHTML = 'Sample Location';

    $div.className = 'event';
    $div.appendChild($p);
    $div.appendChild($small);

    for(var j = 0; j < eventList.length; j++){
        $clonedNode = $div.cloneNode(true);
        $clonedNode.children[0].innerHTML +=  eventList[j].start + '-' + eventList[j].end;
        $clonedNode.style.width = eventList[j].width+'%';
        $clonedNode.style.height = eventList[j].height+'px';
        $clonedNode.style.left = eventList[j].left+'%';
        $clonedNode.style.marginTop = eventList[j].marginTop+'px';
        eventCards.appendChild($clonedNode);
    }
    return eventCards;
}
<|endoftext|>


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

})();
<commit_msg>Tab key support<commit_after>(function () {
  "use strict";

    document.getElementById('content').onkeydown = function(e) {
        if(e.keyCode==9) {
            e.preventDefault();
            /*
                TODO: When it is a selection, ident with (maybe):
                document.execCommand('styleWithCSS',true,null);
                document.execCommand('indent',true,null);
            */
            var sel = window.getSelection().getRangeAt(0);
            var tab = document.createTextNode('\t');
            sel.deleteContents();
            sel.insertNode(tab);
            sel.setStartAfter(tab);
        }
    }

})();
<|endoftext|>