<commit_before>function generate(){
    document.getElementById('poem-author').innerHTML = generate_lines(1, false, 3);
    document.getElementById('poem-title').innerHTML = generate_lines(1, false);
    document.getElementById('poem').innerHTML = generate_lines(random_number(23) + 1);
}

function generate_lines(number_of_lines, line, maximum_words_per_line){
    var block = '';
    var capitalize = true;
    var consonants = 'bcdfghjklmnpqrstvwxyz';
    var lines = '';
    maximum_words_per_line = maximum_words_per_line || 10;
    var number_of_letters = 0;
    var number_of_words = 0;
    var punctuation = '?!';
    var special = 'áäčďěíňóůöřšťúüýž';
    var stanza = number_of_lines > 1
      ? .1
      : 0;
    var vowels = 'aeiou';

    if(line == undefined){
        var line = true;
    }

    while(number_of_lines > 0){
        capitalize = true;
        number_of_words = random_number(maximum_words_per_line) + 1;

        while(number_of_words > 0){
            number_of_letters = random_number(5) + 1;

            // Things that aren't lines are capitalized
            //   or chance for first letter of word to be capitalized.
            if(!line
              || Math.random() < .1){
                capitalize = true;
            }

            while(number_of_letters > 0){
                block = consonants[random_number(consonants.length)];

                if(Math.random() < .05){
                    block += special[random_number(special.length)];

                }else{
                    block += vowels[random_number(vowels.length)];
                }

                // Random chance to have vowel before consonant.
                if(Math.random() < .3){
                    block = block.split('').reverse().join('');
                }

                if(capitalize){
                    capitalize = false;

                    block = block[0].toUpperCase()
                      + block[1];
                }

                lines += block;
                number_of_letters--;
            }

            // If not last word, add a space.
            if(number_of_words > 1){
                lines += ' ';
            }

            number_of_words--;
        }

        // Only add punctuation to lines.
        if(line){
            var added = false;

            for(var id in punctuation){
                if(Math.random() < .1){
                    lines += punctuation[id];
                    added = true;
                    break;
                }
            }

            if(!added){
                lines += '.';
            }
        }

        lines += '
';

        // Chance of new stanza.
        if(stanza > Math.random()){
            lines += '
';
        }

        number_of_lines--;
    }

    return lines;
}

function random_number(i){
    return Math.floor(Math.random() * i);
}

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // Enter: generate()
    if(key === 13){
        generate();
    }
};

window.onload = generate;
<commit_msg>added use strict<commit_after>'use strict';

function generate(){
    document.getElementById('poem-author').innerHTML = generate_lines(1, false, 3);
    document.getElementById('poem-title').innerHTML = generate_lines(1, false);
    document.getElementById('poem').innerHTML = generate_lines(random_number(23) + 1);
}

function generate_lines(number_of_lines, line, maximum_words_per_line){
    var block = '';
    var capitalize = true;
    var consonants = 'bcdfghjklmnpqrstvwxyz';
    var lines = '';
    maximum_words_per_line = maximum_words_per_line || 10;
    var number_of_letters = 0;
    var number_of_words = 0;
    var punctuation = '?!';
    var special = 'áäčďěíňóůöřšťúüýž';
    var stanza = number_of_lines > 1
      ? .1
      : 0;
    var vowels = 'aeiou';

    if(line == undefined){
        var line = true;
    }

    while(number_of_lines > 0){
        capitalize = true;
        number_of_words = random_number(maximum_words_per_line) + 1;

        while(number_of_words > 0){
            number_of_letters = random_number(5) + 1;

            // Things that aren't lines are capitalized
            //   or chance for first letter of word to be capitalized.
            if(!line
              || Math.random() < .1){
                capitalize = true;
            }

            while(number_of_letters > 0){
                block = consonants[random_number(consonants.length)];

                if(Math.random() < .05){
                    block += special[random_number(special.length)];

                }else{
                    block += vowels[random_number(vowels.length)];
                }

                // Random chance to have vowel before consonant.
                if(Math.random() < .3){
                    block = block.split('').reverse().join('');
                }

                if(capitalize){
                    capitalize = false;

                    block = block[0].toUpperCase()
                      + block[1];
                }

                lines += block;
                number_of_letters--;
            }

            // If not last word, add a space.
            if(number_of_words > 1){
                lines += ' ';
            }

            number_of_words--;
        }

        // Only add punctuation to lines.
        if(line){
            var added = false;

            for(var id in punctuation){
                if(Math.random() < .1){
                    lines += punctuation[id];
                    added = true;
                    break;
                }
            }

            if(!added){
                lines += '.';
            }
        }

        lines += '
';

        // Chance of new stanza.
        if(stanza > Math.random()){
            lines += '
';
        }

        number_of_lines--;
    }

    return lines;
}

function random_number(i){
    return Math.floor(Math.random() * i);
}

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // Enter: generate()
    if(key === 13){
        generate();
    }
};

window.onload = generate;
<|endoftext|>


<commit_before>"use strict";
(function() {
  var baseURL = "https://dl.dropboxusercontent.com/s/";
  var infoURL = "https://nonegiven.github.io/res/opm/vNUM.json"

  var lastChapter = 9;

  var chapterInfo = {};

  var currentVolume = -1;
  var currentChapter = -1;
  var currentTitle = "";
  var currentNumber = "";
  var currentPage = -1;
  var currentPageURL = "";
  var chapterSize = -1;

  var imageElement = null;
  var loadingElement = null;
  var leftElement = null;
  var rightElement = null;
  var titleElement = null;
  var navbarElement = null;
  var pageSwitchBarElement = null;
  var chapterSwitcherElement = null;
  var infoPanelElement = null;

  var hashChanging = false;

  function changeCurrentVolume(chapterIndex) {
    var oldVolume = currentVolume;
    //if (chapterIndex <= 9) {
    currentVolume = 1;
    return oldVolume !== currentVolume;
  }

  function getVolumeInfo(chapterIndex, pageIndex) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", infoURL.replace("NUM", currentVolume));
    xhr.onload = function(data) {
      chapterInfo = JSON.parse(this.responseText);
      if (chapterIndex !== undefined) {
        switchChapter(chapterIndex, pageIndex)
      }
    };
    xhr.send();
  }

  function switchChapter(chapterIndex, pageIndex) {
    if (chapterIndex <= lastChapter) {
      if (changeCurrentVolume(chapterIndex)) {
        getVolumeInfo(chapterIndex, pageIndex);
        return;
      }
      currentChapter = chapterIndex;
      currentTitle = chapterInfo[currentChapter].title;
      currentNumber = chapterInfo[currentChapter].number;
      chapterSize = chapterInfo[currentChapter].pages.length - 1;
      titleElement.innerHTML = "Ch " + currentNumber + ": " + currentTitle;
      hashChanging = true;
      chapterSwitcherElement.selectedIndex = currentChapter - 1;
      buildPageSwitchBar();
      loadPage(pageIndex > 0 ? pageIndex : 1); // handles not-passed case too becuase lol Javascript
    }
  }

  function loadPage(pageIndex) {
    if (pageIndex > chapterSize) {
      pageIndex = chapterSize;
    }
    startLoading();
    pageSwitchBarElement.children[pageSwitchBarElement.getAttribute("data-selected")].classList.remove("selected");
    pageSwitchBarElement.children[pageIndex - 1].classList.add("selected");
    pageSwitchBarElement.setAttribute("data-selected", pageIndex - 1);
    currentPage = pageIndex;
    document.title = seriesTitle + " Ch " + currentNumber + ": " + currentTitle + " p" + currentPage;
    hashChanging = true;
    setFragment();
    var path = chapterInfo[currentChapter].pages[currentPage];
    currentPageURL = baseURL + path;
    var extension = path.substr(path.lastIndexOf(".") + 1);
    if (currentPage < 2 && currentChapter < 2) {
      leftElement.classList.remove("hand");
    }
    else {
      leftElement.classList.add("hand");
    }
    if (currentPage >= chapterSize && currentChapter >= lastChapter) {
      rightElement.classList.remove("hand");
    }
    else {
      rightElement.classList.add("hand");
    }
    loadingElement.innerHTML = "Loading... 0.00%";
    var xhr = new XMLHttpRequest();
    xhr.open("GET", currentPageURL);
    xhr.responseType = "arraybuffer";
    xhr.onprogress = function(data) {
      var percentDisplay = (data.loaded / data.total * 100).toFixed(2);
      loadingElement.innerHTML = "Loading... " + percentDisplay + "%";
    };
    xhr.onload = function(data) {
      hashChanging = false;
      loadingElement.innerHTML = "Loading... 100.00%";
      var blob = new Blob([this.response], {type: "image/" + extension});
      imageElement.src = window.URL.createObjectURL(blob);
    };
    xhr.send();
  }

  function startLoading() {
    loadingElement.classList.remove("hidden");
  }

  function stopLoading() {
    imageElement.classList.remove("hidden");
    loadingElement.classList.add("hidden");
    window.scrollTo(0, 0);
  }

  function pageBack() {
    if (currentPage < 2) {
      if (currentChapter > 1) {
        switchChapter(currentChapter - 1);
      }
    }
    else {
      loadPage(currentPage - 1);
    }
  }

  function pageForward() {
    if (currentPage >= chapterSize) {
      if (currentChapter < lastChapter) {
        switchChapter(currentChapter + 1);
      }
    }
    else {
      loadPage(currentPage + 1);
    }
  }

  function clickCheck(e) {
    if (e.target.id !== "infoPanel") {
      hideInfo();
    }
  }

  function keyCheck(e) {
    if (e.keyCode === 27) { // Esc
      hideInfo();
    }
    else if (!e.ctrlKey) {
      if (e.keyCode === 37) { // Left Arrow
        if (e.shiftKey) {
          if (currentChapter > 1) {
            switchChapter(currentChapter - 1);
          }
        }
        else {
          pageBack();
        }
      }
      else if (e.keyCode === 39) { // Right Arrow
        if (e.shiftKey) {
          if (currentChapter < lastChapter) {
            switchChapter(currentChapter + 1);
          }
        }
        else {
          pageForward();
        }
      }
    }
  }

  function setFragment() {
    window.location.hash = currentChapter + "," + currentPage;
  }

  function parseFragment() {
    if (!hashChanging) {
      var split = window.location.hash.split("#")[1].split(",");
      var chapterIndex = parseInt(split[0]);
      if (isNaN(chapterIndex)) {
        chapterIndex = 1;
      }
      var pageIndex = parseInt(split[1]);
      if (isNaN(pageIndex)) {
        pageIndex = 1;
      }
      switchChapter(chapterIndex, pageIndex);
    }
  }

  function chapterSwitcherChange(e) {
    if (!hashChanging) {
      var chapter = parseInt(e.target[e.target.selectedIndex].value);
      if (chapter !== currentChapter) {
        switchChapter(chapter);
      }
    }
  }

  function showNavbar() {
    navbarElement.classList.remove("transparent");
  }

  function hideNavbar() {
    navbarElement.classList.add("transparent");
  }

  function buildPageSwitchBar() {
    pageSwitchBarElement.innerHTML = "";
    pageSwitchBarElement.setAttribute("data-selected", "0");
    var pageBlock, split;
    for (var i = 1; i <= chapterSize; i++) {
      pageBlock = document.createElement("span");
      pageBlock.className = "page hand";
      if (i === 1) {
        pageBlock.classList.add("selected");
      }
      pageBlock.setAttribute("data-page", i);
      split = chapterInfo[currentChapter].pages[i].split("_");
      pageBlock.innerHTML = split[split.length - 1].split(".")[0];
      pageSwitchBarElement.appendChild(pageBlock);
    }
  }

  function pageSwitchClick(e) {
    if (e.target.classList.contains("selected")) {
      return;
    }
    var page = parseInt(e.target.getAttribute("data-page"));
    if (!isNaN(page)) {
      loadPage(page);
    }
  }

  function showPageSwitchBar() {
    pageSwitchBarElement.classList.remove("transparent");
  }

  function hidePageSwitchBar() {
    pageSwitchBarElement.classList.add("transparent");
  }

  function downloadPage() {
    if (currentPageURL) {
      window.open(currentPageURL, "_blank");
    }
  }

  function toggleFit() {
    if (imageElement.classList.contains("nofit")) {
      imageElement.classList.remove("nofit");
      imageElement.classList.add("fit");
    }
    else {
      imageElement.classList.remove("fit");
      imageElement.classList.add("nofit");
    }
  }

  function showInfo() {
    infoPanelElement.classList.remove("hidden");
  }

  function hideInfo() {
    infoPanelElement.classList.remove("add");
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    window.addEventListener("hashchange", parseFragment);
    imageElement = document.getElementById("image");
    loadingElement = document.getElementById("loading");
    leftElement = document.getElementById("left")
    rightElement = document.getElementById("right");
    titleElement = document.getElementById("title");
    navbarElement = document.getElementById("navbar");
    pageSwitchBarElement = document.getElementById("pageSwitchBar");
    chapterSwitcherElement = document.getElementById("chapterSwitcher");
    infoPanelElement = document.getElementById("infoPanel");
    leftElement.addEventListener("click", pageBack);
    rightElement.addEventListener("click", pageForward);
    imageElement.addEventListener("load", stopLoading);
    navbarElement.addEventListener("mouseover", showNavbar);
    navbarElement.addEventListener("mouseout", hideNavbar);
    pageSwitchBarElement.addEventListener("mouseover", showPageSwitchBar);
    pageSwitchBarElement.addEventListener("mouseout", hidePageSwitchBar);
    pageSwitchBarElement.addEventListener("click", pageSwitchClick);
    chapterSwitcherElement.addEventListener("change", chapterSwitcherChange);
    document.getElementById("downloadButton").addEventListener("click", downloadPage);
    document.getElementById("fitButton").addEventListener("click", toggleFit);
    document.getElementById("infoButton").addEventListener("click", showInfo);
    document.addEventListener("keydown", keyCheck);
    document.addEventListener("click", clickCheck);
    if (window.location.hash === "") {
      switchChapter(1);
    }
    else {
      parseFragment();
    }
  }

  document.addEventListener("DOMContentLoaded", setup);
  var seriesTitle = "One-Punch Man";
  document.title = seriesTitle;
}).call(this);
<commit_msg>Update read.js<commit_after>"use strict";
(function() {
  var baseURL = "https://dl.dropboxusercontent.com/s/";
  var infoURL = "https://nonegiven.github.io/res/opm/vNUM.json"

  var lastChapter = 9;

  var chapterInfo = {};

  var currentVolume = -1;
  var currentChapter = -1;
  var currentTitle = "";
  var currentNumber = "";
  var currentPage = -1;
  var currentPageURL = "";
  var chapterSize = -1;

  var imageElement = null;
  var loadingElement = null;
  var leftElement = null;
  var rightElement = null;
  var titleElement = null;
  var navbarElement = null;
  var pageSwitchBarElement = null;
  var chapterSwitcherElement = null;
  var infoPanelElement = null;

  var hashChanging = false;

  function changeCurrentVolume(chapterIndex) {
    var oldVolume = currentVolume;
    //if (chapterIndex <= 9) {
    currentVolume = 1;
    return oldVolume !== currentVolume;
  }

  function getVolumeInfo(chapterIndex, pageIndex) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", infoURL.replace("NUM", currentVolume));
    xhr.onload = function(data) {
      chapterInfo = JSON.parse(this.responseText);
      if (chapterIndex !== undefined) {
        switchChapter(chapterIndex, pageIndex)
      }
    };
    xhr.send();
  }

  function switchChapter(chapterIndex, pageIndex) {
    if (chapterIndex <= lastChapter) {
      if (changeCurrentVolume(chapterIndex)) {
        getVolumeInfo(chapterIndex, pageIndex);
        return;
      }
      currentChapter = chapterIndex;
      currentTitle = chapterInfo[currentChapter].title;
      currentNumber = chapterInfo[currentChapter].number;
      chapterSize = chapterInfo[currentChapter].pages.length - 1;
      titleElement.innerHTML = "Ch " + currentNumber + ": " + currentTitle;
      hashChanging = true;
      chapterSwitcherElement.selectedIndex = currentChapter - 1;
      buildPageSwitchBar();
      loadPage(pageIndex > 0 ? pageIndex : 1); // handles not-passed case too becuase lol Javascript
    }
  }

  function loadPage(pageIndex) {
    if (pageIndex > chapterSize) {
      pageIndex = chapterSize;
    }
    startLoading();
    pageSwitchBarElement.children[pageSwitchBarElement.getAttribute("data-selected")].classList.remove("selected");
    pageSwitchBarElement.children[pageIndex - 1].classList.add("selected");
    pageSwitchBarElement.setAttribute("data-selected", pageIndex - 1);
    currentPage = pageIndex;
    document.title = seriesTitle + " Ch " + currentNumber + ": " + currentTitle + " p" + currentPage;
    hashChanging = true;
    setFragment();
    var path = chapterInfo[currentChapter].pages[currentPage];
    currentPageURL = baseURL + path;
    var extension = path.substr(path.lastIndexOf(".") + 1);
    if (currentPage < 2 && currentChapter < 2) {
      leftElement.classList.remove("hand");
    }
    else {
      leftElement.classList.add("hand");
    }
    if (currentPage >= chapterSize && currentChapter >= lastChapter) {
      rightElement.classList.remove("hand");
    }
    else {
      rightElement.classList.add("hand");
    }
    loadingElement.innerHTML = "Loading... 0.00%";
    var xhr = new XMLHttpRequest();
    xhr.open("GET", currentPageURL);
    xhr.responseType = "arraybuffer";
    xhr.onprogress = function(data) {
      var percentDisplay = (data.loaded / data.total * 100).toFixed(2);
      loadingElement.innerHTML = "Loading... " + percentDisplay + "%";
    };
    xhr.onload = function(data) {
      hashChanging = false;
      loadingElement.innerHTML = "Loading... 100.00%";
      var blob = new Blob([this.response], {type: "image/" + extension});
      imageElement.src = window.URL.createObjectURL(blob);
    };
    xhr.send();
  }

  function startLoading() {
    loadingElement.classList.remove("hidden");
  }

  function stopLoading() {
    imageElement.classList.remove("hidden");
    loadingElement.classList.add("hidden");
    window.scrollTo(0, 0);
  }

  function pageBack() {
    if (currentPage < 2) {
      if (currentChapter > 1) {
        switchChapter(currentChapter - 1);
      }
    }
    else {
      loadPage(currentPage - 1);
    }
  }

  function pageForward() {
    if (currentPage >= chapterSize) {
      if (currentChapter < lastChapter) {
        switchChapter(currentChapter + 1);
      }
    }
    else {
      loadPage(currentPage + 1);
    }
  }

  function clickCheck(e) {
    if (e.target.id !== "infoPanel") {
      hideInfo();
    }
  }

  function keyCheck(e) {
    if (e.keyCode === 27) { // Esc
      hideInfo();
    }
    else if (!e.ctrlKey) {
      if (e.keyCode === 37) { // Left Arrow
        if (e.shiftKey) {
          if (currentChapter > 1) {
            switchChapter(currentChapter - 1);
          }
        }
        else {
          pageBack();
        }
      }
      else if (e.keyCode === 39) { // Right Arrow
        if (e.shiftKey) {
          if (currentChapter < lastChapter) {
            switchChapter(currentChapter + 1);
          }
        }
        else {
          pageForward();
        }
      }
    }
  }

  function setFragment() {
    window.location.hash = currentChapter + "," + currentPage;
  }

  function parseFragment() {
    if (!hashChanging) {
      var split = window.location.hash.split("#")[1].split(",");
      var chapterIndex = parseInt(split[0]);
      if (isNaN(chapterIndex)) {
        chapterIndex = 1;
      }
      var pageIndex = parseInt(split[1]);
      if (isNaN(pageIndex)) {
        pageIndex = 1;
      }
      switchChapter(chapterIndex, pageIndex);
    }
  }

  function chapterSwitcherChange(e) {
    if (!hashChanging) {
      var chapter = parseInt(e.target[e.target.selectedIndex].value);
      if (chapter !== currentChapter) {
        switchChapter(chapter);
      }
    }
  }

  function showNavbar() {
    navbarElement.classList.remove("transparent");
  }

  function hideNavbar() {
    navbarElement.classList.add("transparent");
  }

  function buildPageSwitchBar() {
    pageSwitchBarElement.innerHTML = "";
    pageSwitchBarElement.setAttribute("data-selected", "0");
    var pageBlock, split;
    for (var i = 1; i <= chapterSize; i++) {
      pageBlock = document.createElement("span");
      pageBlock.className = "page hand";
      if (i === 1) {
        pageBlock.classList.add("selected");
      }
      pageBlock.setAttribute("data-page", i);
      split = chapterInfo[currentChapter].pages[i].split("_");
      pageBlock.innerHTML = split[split.length - 1].split(".")[0];
      pageSwitchBarElement.appendChild(pageBlock);
    }
  }

  function pageSwitchClick(e) {
    if (e.target.classList.contains("selected")) {
      return;
    }
    var page = parseInt(e.target.getAttribute("data-page"));
    if (!isNaN(page)) {
      loadPage(page);
    }
  }

  function showPageSwitchBar() {
    pageSwitchBarElement.classList.remove("transparent");
  }

  function hidePageSwitchBar() {
    pageSwitchBarElement.classList.add("transparent");
  }

  function downloadPage() {
    if (currentPageURL) {
      window.open(currentPageURL, "_blank");
    }
  }

  function toggleFit() {
    if (imageElement.classList.contains("nofit")) {
      imageElement.classList.remove("nofit");
      imageElement.classList.add("fit");
    }
    else {
      imageElement.classList.remove("fit");
      imageElement.classList.add("nofit");
    }
  }

  function showInfo() {
    infoPanelElement.classList.remove("hidden");
  }

  function hideInfo() {
    infoPanelElement.classList.add("hidden");
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    window.addEventListener("hashchange", parseFragment);
    imageElement = document.getElementById("image");
    loadingElement = document.getElementById("loading");
    leftElement = document.getElementById("left")
    rightElement = document.getElementById("right");
    titleElement = document.getElementById("title");
    navbarElement = document.getElementById("navbar");
    pageSwitchBarElement = document.getElementById("pageSwitchBar");
    chapterSwitcherElement = document.getElementById("chapterSwitcher");
    infoPanelElement = document.getElementById("infoPanel");
    leftElement.addEventListener("click", pageBack);
    rightElement.addEventListener("click", pageForward);
    imageElement.addEventListener("load", stopLoading);
    navbarElement.addEventListener("mouseover", showNavbar);
    navbarElement.addEventListener("mouseout", hideNavbar);
    pageSwitchBarElement.addEventListener("mouseover", showPageSwitchBar);
    pageSwitchBarElement.addEventListener("mouseout", hidePageSwitchBar);
    pageSwitchBarElement.addEventListener("click", pageSwitchClick);
    chapterSwitcherElement.addEventListener("change", chapterSwitcherChange);
    document.getElementById("downloadButton").addEventListener("click", downloadPage);
    document.getElementById("fitButton").addEventListener("click", toggleFit);
    document.getElementById("infoButton").addEventListener("click", showInfo);
    document.addEventListener("keydown", keyCheck);
    document.addEventListener("click", clickCheck);
    if (window.location.hash === "") {
      switchChapter(1);
    }
    else {
      parseFragment();
    }
  }

  document.addEventListener("DOMContentLoaded", setup);
  var seriesTitle = "One-Punch Man";
  document.title = seriesTitle;
}).call(this);
<|endoftext|>


<commit_before>var user_choice = '';
var options = ['rock','paper','scissors'];
var justus_choice = '';
var user_score = 0;
var justus_score = 0;

$('#user_score').append(user_score.toString());
$('#justus_score').append(justus_score.toString());

function evaluate_choices(choice1,choice2){
  if(choice1 == choice2){
    $('#game_message').empty();
    $('#game_message').append('Tie');
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }
  else if(choice1 == 'rock' && choice2 == 'paper'){
    $('#game_message').empty();
    $('#game_message').append('Justus Wins!');
    justus_score = justus_score + 1;
    $('#justus_score').empty();
    $('#justus_score').append(justus_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }else if(choice1 == 'paper' && choice2 == 'scissors'){
    $('#game_message').empty();
    $('#game_message').append('Justus Wins!');
    justus_score = justus_score + 1;
    $('#justus_score').empty();
    $('#justus_score').append(justus_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }else if(choice1 == 'scissors' && choice2 == 'rock'){
    $('#game_message').empty();
    $('#game_message').append('Justus Wins!');
    justus_score = justus_score + 1;
    $('#justus_score').empty();
    $('#justus_score').append(justus_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }else if(choice1 == 'paper' && choice2 == 'rock'){
    $('#game_message').empty();
    $('#game_message').append('You Win!');
    user_score = user_score + 1;
    $('#user_score').empty();
    $('#user_score').append(user_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }else if(choice1 == 'scissors' && choice2 == 'paper'){
    $('#game_message').empty();
    $('#game_message').append('You Win!');
    user_score = user_score + 1;
    $('#user_score').empty();
    $('#user_score').append(user_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }else if(choice1 == 'rock' && choice2 == 'scissors'){
    $('#game_message').empty();
    $('#game_message').append('You Win!');
    user_score = user_score + 1;
    $('#user_score').empty();
    $('#user_score').append(user_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }
}

// Returns a random number between min (inclusive) and max (exclusive)
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

$('#rock').on('click',function(e){
  e.preventDefault();
  user_choice = 'rock';
  justus_choice = options[getRandomArbitrary(0,3)].toString();
  $('#rock').removeClass('btn-active');
  evaluate_choices(user_choice,justus_choice);
});
$('#paper').on('click',function(e){
  e.preventDefault();
  user_choice = 'paper';
  justus_choice = options[getRandomArbitrary(0,3)].toString();
  $('#paper').removeClass('btn-active');
  evaluate_choices(user_choice,justus_choice);
});
$('#scissors').on('click',function(e){
  e.preventDefault();
  user_choice = 'scissors';
  justus_choice = options[getRandomArbitrary(0,3)].toString();
  $('#scissors').removeClass('btn-active');
  evaluate_choices(user_choice,justus_choice);
});
<commit_msg>fixed random num issue<commit_after>var user_choice = '';
var options = ['rock','paper','scissors'];
var justus_choice = '';
var user_score = 0;
var justus_score = 0;

$('#user_score').append(user_score.toString());
$('#justus_score').append(justus_score.toString());

function evaluate_choices(choice1,choice2){
  if(choice1 == choice2){
    $('#game_message').empty();
    $('#game_message').append('Tie');
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }
  else if(choice1 == 'rock' && choice2 == 'paper'){
    $('#game_message').empty();
    $('#game_message').append('Justus Wins!');
    justus_score = justus_score + 1;
    $('#justus_score').empty();
    $('#justus_score').append(justus_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }else if(choice1 == 'paper' && choice2 == 'scissors'){
    $('#game_message').empty();
    $('#game_message').append('Justus Wins!');
    justus_score = justus_score + 1;
    $('#justus_score').empty();
    $('#justus_score').append(justus_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }else if(choice1 == 'scissors' && choice2 == 'rock'){
    $('#game_message').empty();
    $('#game_message').append('Justus Wins!');
    justus_score = justus_score + 1;
    $('#justus_score').empty();
    $('#justus_score').append(justus_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }else if(choice1 == 'paper' && choice2 == 'rock'){
    $('#game_message').empty();
    $('#game_message').append('You Win!');
    user_score = user_score + 1;
    $('#user_score').empty();
    $('#user_score').append(user_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }else if(choice1 == 'scissors' && choice2 == 'paper'){
    $('#game_message').empty();
    $('#game_message').append('You Win!');
    user_score = user_score + 1;
    $('#user_score').empty();
    $('#user_score').append(user_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }else if(choice1 == 'rock' && choice2 == 'scissors'){
    $('#game_message').empty();
    $('#game_message').append('You Win!');
    user_score = user_score + 1;
    $('#user_score').empty();
    $('#user_score').append(user_score);
    $('#justus_choice').empty();
    $('#user_choice').empty();
    $('#justus_choice').append(justus_choice);
    $('#user_choice').append(user_choice);
    setTimeout(function(){ $('#game_message').empty();$('#game_message').append('Who\'s gonna win...');$('#justus_choice').empty();
    $('#user_choice').empty(); }, 2500);
  }
}

// Returns a random number between min (inclusive) and max (exclusive)
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

$('#rock').on('click',function(e){
  e.preventDefault();
  user_choice = 'rock';
  justus_choice = options[getRandomArbitrary(0,2)].toString();
  $('#rock').removeClass('btn-active');
  evaluate_choices(user_choice,justus_choice);
});
$('#paper').on('click',function(e){
  e.preventDefault();
  user_choice = 'paper';
  justus_choice = options[getRandomArbitrary(0,2)].toString();
  $('#paper').removeClass('btn-active');
  evaluate_choices(user_choice,justus_choice);
});
$('#scissors').on('click',function(e){
  e.preventDefault();
  user_choice = 'scissors';
  justus_choice = options[getRandomArbitrary(0,2)].toString();
  $('#scissors').removeClass('btn-active');
  evaluate_choices(user_choice,justus_choice);
});
<|endoftext|>


<commit_before>function setMeter(rating) {
	if(rating>=6) {
		var x=500;
	} else if(rating<=-6) {
		var x=-500;
	} else {
		var x=rating*100;
	}
	var r=$("#meterRed");
	var g=$("#meterGreen");
	g.animate({width: (583+x)}, Math.abs(g.width()-(583+x)));
	r.animate({width: (583-x)}, Math.abs(r.width()-(583-x)));
}

var player;
var firebase = new Firebase('https://adr2370.firebaseio.com/');
var songdb = firebase.child('songs');
var playerdb = firebase.child('playerdb');
var commentdb = firebase.child('comments');
var currentdb = firebase.child('current');
var goingToNext = false;

var songs=new Array();

function startVideo() {
	//youtube video
	currentdb.once('value', function(dataSnapshot) {
		var id=dataSnapshot.child('id').val();
		if(player==null) {
			player=new YT.Player('youtube', {
				height: '390',
				width: '640',
				videoId: id,
				playerVars: { autoplay:1, enablejsapi:1, modestbranding:1, rel:0, showinfo:0, iv_load_policy:3, volume:50 },
				events: {
					'onStateChange': onPlayerStateChange,
					//'onError': onError
				}});
		} else {
			player.loadVideoById(id, 5, "large");
		}
		/*if(player!=null) {
			playerdb.child('volume').once('value', function(dataSnapshot) {
				player.setVolume(dataSnapshot.val());
			});
		} else {
			console.log("SOMETHING WENT WRONG");
		}*/
		$("#visuals canvas").hide();
		$("#"+id).remove();
		songdb.child(id).remove();
		removeA(songs, id);
	});
}

function nextVideo() {
	if(!goingToNext) {
		goingToNext=true;
		setMeter(0);
		$("#comments").html("");
		commentdb.remove();
		//currentdb.remove();
		if(songs.length>0) {
			songdb.child(songs[0]).once('value', function(dataSnapshot) {
				currentdb.set(dataSnapshot.val());
				currentdb.child('rating').set(0);
				currentdb.child('skip').set(0);
				currentdb.child('play').set(0);
				currentdb.child('pause').set(0);
				currentdb.child('fullScreen').set(0);
				currentdb.child('id').set(songs[0]);
				goingToNext=false;
			});
		} else {
			$("#youtube").replaceWith($('
<\/div>'));
			player=null;
			goingToNext=false;
		}
	}
}

function onPlayerStateChange(event) {
	if(event.data == 0) {
		currentdb.remove();
	}
}

function onError(event) {
	currentdb.remove();
}

currentdb.on('child_changed', function(snapshot, prevChildName) {
	//CHANGE RATING OR SKIP VIDEO
	if(snapshot.name()=="rating") {
		setMeter(snapshot.val());
	} else if(snapshot.name()=="skip"&&snapshot.val()==1) {
		nextVideo();
	} else if(snapshot.name()=="play"&&snapshot.val()==1) {
		currentdb.child('play').set(0);
		player.playVideo();
	} else if(snapshot.name()=="pause"&&snapshot.val()==1) {
		currentdb.child('pause').set(0);
		player.pauseVideo();
	} else if(snapshot.name()=="fullScreen"&&snapshot.val()==1) {
		currentdb.child('fullScreen').set(0);
		window.fullScreen();
	}
});

currentdb.on('child_added', function(snapshot, prevChildName) {
	//ADDED SONG
	if(snapshot.name()=="id") {
		startVideo();
	}
});

currentdb.on('child_removed', function(snapshot, prevChildName) {
	//ADDED SONG
	if(snapshot.name()=="id") {
		//nextVideo();
	}
});

songdb.on('child_added', function(snapshot, prevChildName) {
	//ADDS SOMETHING TO QUEUE
	//snapshot.name() is youtube id, all else is below
	songs.push(snapshot.name());
	$("#queue").append('
'+snapshot.child('name').val()+'<\/td>'+snapshot.child('length').val()+'<\/td><\/td>'+snapshot.child('numViews').val()+'<\/tr>');
	currentdb.on('value', function(snapshot, prevChildName) {
		if(snapshot.val()==null) {
			nextVideo();
		}
	});
});

songdb.on('child_moved', function(snapshot, prevChildName) {
	//SWITCHES ORDER OF STUFF IN QUEUE
	//prevChildName is the name of the previous one, snapshot.name is the id of the snapshot
	if(prevChildName==null) {
		$("#topQueue").after($("#"+snapshot.name()).remove());
	} else {
		$("#"+prevChildName).after($("#"+snapshot.name()).remove());
	}
});

playerdb.on('child_changed', function(snapshot, prevChildName) {
	player.setVolume(snapshot.val());
});

commentdb.on('child_added', function(snapshot, prevChildName) {
	//COMMENTS ADDED
	//snapshot.val() is each comment
	$("#comments").prepend("
" + snapshot.val()+"<\/p>");
});

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}<commit_msg>Tried without using go to next<commit_after>function setMeter(rating) {
	if(rating>=6) {
		var x=500;
	} else if(rating<=-6) {
		var x=-500;
	} else {
		var x=rating*100;
	}
	var r=$("#meterRed");
	var g=$("#meterGreen");
	g.animate({width: (583+x)}, Math.abs(g.width()-(583+x)));
	r.animate({width: (583-x)}, Math.abs(r.width()-(583-x)));
}

var player;
var firebase = new Firebase('https://adr2370.firebaseio.com/');
var songdb = firebase.child('songs');
var playerdb = firebase.child('playerdb');
var commentdb = firebase.child('comments');
var currentdb = firebase.child('current');
var goingToNext = false;

var songs=new Array();

function startVideo() {
	//youtube video
	currentdb.once('value', function(dataSnapshot) {
		var id=dataSnapshot.child('id').val();
		if(player==null) {
			player=new YT.Player('youtube', {
				height: '390',
				width: '640',
				videoId: id,
				playerVars: { autoplay:1, enablejsapi:1, modestbranding:1, rel:0, showinfo:0, iv_load_policy:3, volume:50 },
				events: {
					'onStateChange': onPlayerStateChange,
					//'onError': onError
				}});
		} else {
			player.loadVideoById(id, 5, "large");
		}
		/*if(player!=null) {
			playerdb.child('volume').once('value', function(dataSnapshot) {
				player.setVolume(dataSnapshot.val());
			});
		} else {
			console.log("SOMETHING WENT WRONG");
		}*/
		$("#visuals canvas").hide();
		$("#"+id).remove();
		songdb.child(id).remove();
		removeA(songs, id);
	});
}

function nextVideo() {
	//if(!goingToNext) {
	//	goingToNext=true;
		setMeter(0);
		$("#comments").html("");
		commentdb.remove();
		if(songs.length>0) {
			songdb.child(songs[0]).once('value', function(dataSnapshot) {
				currentdb.set(dataSnapshot.val());
				currentdb.child('rating').set(0);
				currentdb.child('skip').set(0);
				currentdb.child('play').set(0);
				currentdb.child('pause').set(0);
				currentdb.child('fullScreen').set(0);
				currentdb.child('id').set(songs[0]);
				//goingToNext=false;
			});
		} else {
			$("#youtube").replaceWith($('
<\/div>'));
			player=null;
			//goingToNext=false;
		}
	}
}

function onPlayerStateChange(event) {
	if(event.data == 0) {
		currentdb.remove();
	}
}

function onError(event) {
	currentdb.remove();
}

currentdb.on('child_changed', function(snapshot, prevChildName) {
	//CHANGE RATING OR SKIP VIDEO
	if(snapshot.name()=="rating") {
		setMeter(snapshot.val());
	} else if(snapshot.name()=="skip"&&snapshot.val()==1) {
		nextVideo();
	} else if(snapshot.name()=="play"&&snapshot.val()==1) {
		currentdb.child('play').set(0);
		player.playVideo();
	} else if(snapshot.name()=="pause"&&snapshot.val()==1) {
		currentdb.child('pause').set(0);
		player.pauseVideo();
	} else if(snapshot.name()=="fullScreen"&&snapshot.val()==1) {
		currentdb.child('fullScreen').set(0);
		window.fullScreen();
	}
});

currentdb.on('child_added', function(snapshot, prevChildName) {
	//ADDED SONG
	if(snapshot.name()=="id") {
		startVideo();
	}
});

currentdb.on('child_removed', function(snapshot, prevChildName) {
	//ADDED SONG
	if(snapshot.name()=="id") {
		//nextVideo();
	}
});

songdb.on('child_added', function(snapshot, prevChildName) {
	//ADDS SOMETHING TO QUEUE
	//snapshot.name() is youtube id, all else is below
	songs.push(snapshot.name());
	$("#queue").append('
'+snapshot.child('name').val()+'<\/td>'+snapshot.child('length').val()+'<\/td><\/td>'+snapshot.child('numViews').val()+'<\/tr>');
	currentdb.on('value', function(snapshot, prevChildName) {
		if(snapshot.val()==null) {
			nextVideo();
		}
	});
});

songdb.on('child_moved', function(snapshot, prevChildName) {
	//SWITCHES ORDER OF STUFF IN QUEUE
	//prevChildName is the name of the previous one, snapshot.name is the id of the snapshot
	if(prevChildName==null) {
		$("#topQueue").after($("#"+snapshot.name()).remove());
	} else {
		$("#"+prevChildName).after($("#"+snapshot.name()).remove());
	}
});

playerdb.on('child_changed', function(snapshot, prevChildName) {
	player.setVolume(snapshot.val());
});

commentdb.on('child_added', function(snapshot, prevChildName) {
	//COMMENTS ADDED
	//snapshot.val() is each comment
	$("#comments").prepend("
" + snapshot.val()+"<\/p>");
});

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}<|endoftext|>


<commit_before>function generateKeyStats(data){
    numberOfIncidents(data);
}

function numberOfIncidents(data){
    var count=0;
    var begin = new Date();
    begin.setDate(begin.getDate()-30);
    data.forEach(function(d){
        if(d['#date']>begin){
            count++;
        }
    });
    $('#numberofincidents').html(data.length);
}

function generateMap(){
    var baselayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {});

    map = L.map('map', {
        center: [20, 10],  //center: [43,20],
        zoom: 4,            //zoom: 5,
        layers: [baselayer]
    });
}

function clusterMarkers(markers) {

    //Checking if Markers is an array of objects or a single object
    if (Object.prototype.toString.call(markers) === '[object Array]') {

        //if an array of objects then create a marker for each of them
        markers.forEach(function(d){
            d.marker = L.marker([d['#geo+lat'],d['#geo+lon']], { icon: myIcon })
            d.marker.on('click', function (e) {
                showIncident(d);
            })
            d.visible = false;
        })
    }
    else //if not an array then create a single marker
    {
        markers.marker = L.marker([markers['#geo+lat'],markers['#geo+lon']], { icon: myIcon })
        markers.marker.on('click', function (e) {
            showIncident(markers);
        })
        markers.visible = false;
    }
    return markers;
}

function DateAdd(date, type, amount){
    var y = date.getFullYear(),
        m = date.getMonth(),
        d = date.getDate();
    if(type === 'y'){
        y += amount;
    };
    if(type === 'm'){
        m += amount;
    };
    if(type === 'd'){
        d += amount;
    };
    return new Date(y, m, d);
}

function filterDateRange(date,days,data){

    var begin = DateAdd(date, 'd', -30)

    data.forEach(function (d) {
        if (d['#date']>=begin&&d['#date']<=date) {
            if (!d.visible) {
                d = clusterMarkers(d);
                markerClusters.addLayer(d.marker);
                markerClusters.addTo(map);
                d.visible = true;
            }
        } else {
            if (d.visible) {
                map.removeLayer(d.marker);
                markerClusters.removeLayer(d.marker);
                d.visible = false;
            }
        }
    }
    );

    headlines(data);

    return data;
};

function addSlider(data){
    var max = new Date();
    var min = d3.min(data,function(d){
        return d['#date'];
    });
    $('#slider').html(''+max.toISOString().substring(0, 10)+'<input id="dateslider" type="range" min="'+min.valueOf()+'" max="'+max.valueOf()+'" step="86400000"  value="'+max.valueOf()+'" />
Showing 30 days previous
');

    $('#dateslider').on("input", function() {
        var mill = parseInt($('#dateslider').val());
        var date = new Date(mill);
        $('#sliderdate').html(date.toISOString().substring(0, 10));
    });

    $('#dateslider').on("change", function(){
        var mill = parseInt($('#dateslider').val());
        var date = new Date(mill);
        data = filterDateRange(date,30,data);
    });
}

function showIncident(d) {
    if(d['#meta+url']!=''){
        $('#headlines').html('
Back

'+d['#date'].toISOString().substring(0, 10)+' '+d['#event+title']+'

'+d['#event+description']+'

More info
');
    } else {
        $('#headlines').html('
Back

'+d['#date'].toISOString().substring(0, 10)+' '+d['#event+title']+'

'+d['#event+description']+'
');
    }
    $('#back').on('click', function(){
        headlines(data);
    });
}

function headlines(data){
    $('#headlines').html('');
    data.forEach(function(d,i){
        if (d.visible) {
            $('#headlines').append('
'+d['#date'].toISOString().substring(0, 10)+' '+d['#event+title']+'
');
        }
        $('#headline'+i).on('click',function(){
            map.setView([d['#geo+lat'],d['#geo+lon']], 8);
            showIncident(d);
        });
    });
}

function hxlProxyToJSON(input){
    var output = [];
    var keys=[]
    input.forEach(function(e,i){
        if(i==0){
            e.forEach(function(e2,i2){
                var parts = e2.split('+');
                var key = parts[0]
                if(parts.length>1){
                    var atts = parts.splice(1,parts.length);
                    atts.sort();
                    atts.forEach(function(att){
                        key +='+'+att
                    });
                }
                keys.push(key);
            });
        } else {
            var row = {};
            e.forEach(function(e2,i2){
                row[keys[i2]] = e2;
            });
            output.push(row);
        }
    });
    return output;
}

function parseDates(tags,data){
    var parseDateFormat = d3.time.format("%Y-%m-%d").parse;
    data.forEach(function(d){
        tags.forEach(function(t){
            d[t] = parseDateFormat(d[t]);
        });
    });

    data.sort(date_sort);
    return data;
}

function removeIncompletes(data){
    output = [];
    data.forEach(function(d){
        if(!isNaN(d['#geo+lat']) && !isNaN(d['#geo+lat'])){
            output.push(d);
        }
    });
    return data;
}

var date_sort = function (d1, d2) {
    if (d1['#date'] < d2['#date']) return 1;
    if (d1['#date'] > d2['#date']) return -1;
    return 0;
};

var keyStatsCall = $.ajax({
    type: 'GET',
    url: 'https://proxy.hxlstandard.org/data.json?filter01=clean&clean-num-tags01=%23geo&force=on&url=https%3A//docs.google.com/spreadsheets/d/1uecK0OhCxMQmmWspuPoTvFL4o3xmfJVRrvE-wMUtQ_4/edit%23gid%3D0&strip-headers=on&clean-date-tags01=%23date',
    dataType: 'json',
});

var map, data;

var myIcon = L.icon({
    iconUrl: 'img/pin@1x.svg',
    iconSize: [60, 40],
    iconAnchor: [20, 40],
    popupAnchor: [0, -14]
});

var markerClusters = L.markerClusterGroup();

generateMap();

$.when(keyStatsCall).then(function(keyStatsArgs){
    data = parseDates(['#date'],(hxlProxyToJSON(keyStatsArgs)));
    data = removeIncompletes(data);
    addSlider(data);
    data = clusterMarkers(data);
    data = filterDateRange(new Date(), 30, data);
    generateKeyStats(data);
});<commit_msg>added date checks<commit_after>function generateKeyStats(data){
    numberOfIncidents(data);
}

function numberOfIncidents(data){
    var count=0;
    var begin = new Date();
    begin.setDate(begin.getDate()-30);
    data.forEach(function(d){
        if(d['#date']>begin){
            count++;
        }
    });
    $('#numberofincidents').html(data.length);
}

function generateMap(){
    var baselayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {});

    map = L.map('map', {
        center: [20, 10],  //center: [43,20],
        zoom: 4,            //zoom: 5,
        layers: [baselayer]
    });
}

function clusterMarkers(markers) {

    //Checking if Markers is an array of objects or a single object
    if (Object.prototype.toString.call(markers) === '[object Array]') {

        //if an array of objects then create a marker for each of them
        markers.forEach(function(d){
            d.marker = L.marker([d['#geo+lat'],d['#geo+lon']], { icon: myIcon })
            d.marker.on('click', function (e) {
                showIncident(d);
            })
            d.visible = false;
        })
    }
    else //if not an array then create a single marker
    {
        markers.marker = L.marker([markers['#geo+lat'],markers['#geo+lon']], { icon: myIcon })
        markers.marker.on('click', function (e) {
            showIncident(markers);
        })
        markers.visible = false;
    }
    return markers;
}

function DateAdd(date, type, amount){
    var y = date.getFullYear(),
        m = date.getMonth(),
        d = date.getDate();
    if(type === 'y'){
        y += amount;
    };
    if(type === 'm'){
        m += amount;
    };
    if(type === 'd'){
        d += amount;
    };
    return new Date(y, m, d);
}

function filterDateRange(date,days,data){

    var begin = DateAdd(date, 'd', -30)

    data.forEach(function (d) {
        if (d['#date']>=begin&&d['#date']<=date) {
            if (!d.visible) {
                d = clusterMarkers(d);
                markerClusters.addLayer(d.marker);
                markerClusters.addTo(map);
                d.visible = true;
            }
        } else {
            if (d.visible) {
                map.removeLayer(d.marker);
                markerClusters.removeLayer(d.marker);
                d.visible = false;
            }
        }
    }
    );

    headlines(data);

    return data;
};

function addSlider(data){
    var max = new Date();
    var min = d3.min(data,function(d){
        return d['#date'];
    });
    $('#slider').html(''+max.toISOString().substring(0, 10)+'<input id="dateslider" type="range" min="'+min.valueOf()+'" max="'+max.valueOf()+'" step="86400000"  value="'+max.valueOf()+'" />
Showing 30 days previous
');

    $('#dateslider').on("input", function() {
        var mill = parseInt($('#dateslider').val());
        var date = new Date(mill);
        $('#sliderdate').html(date.toISOString().substring(0, 10));
    });

    $('#dateslider').on("change", function(){
        var mill = parseInt($('#dateslider').val());
        var date = new Date(mill);
        data = filterDateRange(date,30,data);
    });
}

function showIncident(d) {
    if(d['#meta+url']!=''){
        $('#headlines').html('
Back

'+d['#date'].toISOString().substring(0, 10)+' '+d['#event+title']+'

'+d['#event+description']+'

More info
');
    } else {
        $('#headlines').html('
Back

'+d['#date'].toISOString().substring(0, 10)+' '+d['#event+title']+'

'+d['#event+description']+'
');
    }
    $('#back').on('click', function(){
        headlines(data);
    });
}

function headlines(data){
    $('#headlines').html('');
    data.forEach(function(d,i){
        if (d.visible) {
            $('#headlines').append('
'+d['#date'].toISOString().substring(0, 10)+' '+d['#event+title']+'
');
        }
        $('#headline'+i).on('click',function(){
            map.setView([d['#geo+lat'],d['#geo+lon']], 8);
            showIncident(d);
        });
    });
}

// hxlProxyToJSON: reading hxl tags and setting them as keys for each event
// input is an array with hxl tags as first object, and then the data as objects
// output is an array with hxl tags as keys for the data objects

function hxlProxyToJSON(input){
    var output = [];
    var keys = []
    input.forEach(function(e,i){
        if(i==0){
            e.forEach(function(e2,i2){
                var parts = e2.split('+');
                var key = parts[0]
                if(parts.length>1){
                    var atts = parts.splice(1,parts.length);
                    atts.sort();
                    atts.forEach(function(att){
                        key +='+'+att
                    });
                }
                keys.push(key);
            });
        } else {
            var row = {};
            e.forEach(function(e2,i2){
                row[keys[i2]] = e2;
            });
            output.push(row);
        }
    });
    return output;
}

//parseDates checks date is in the following format 2017-03-06 and is not before 1900 or beyond 2099
//and parses the date if the date is valid, if not it changes the date into 0000-00-00

function parseDates(tags, data) {
    var parseDateFormat = d3.time.format("%Y-%m-%d").parse;
    data.forEach(function (d) {
        tags.forEach(function(t){
            if (datePattern.test(t)){
                d[t] = parseDateFormat(d[t]);
            } else {
                d[t] = parseDateFormat('0000-00-00');
            }
        });
    });

    data.sort(date_sort);
    return data;
}

function removeIncompletes(data){
    output = [];
    data.forEach(function(d){
        if(!isNaN(d['#geo+lat']) && !isNaN(d['#geo+lat']) && (d['#date']!=='0000-00-00')){
            output.push(d);
        }
    });
    return data;
}

var datePattern = new RegExp('(19|20)\\d\\d-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])');

var date_sort = function (d1, d2) {
    if (d1['#date'] < d2['#date']) return 1;
    if (d1['#date'] > d2['#date']) return -1;
    return 0;
};

var keyStatsCall = $.ajax({
    type: 'GET',
    url: 'https://proxy.hxlstandard.org/data.json?filter01=clean&clean-num-tags01=%23geo&force=on&url=https%3A//docs.google.com/spreadsheets/d/1uecK0OhCxMQmmWspuPoTvFL4o3xmfJVRrvE-wMUtQ_4/edit%23gid%3D0&strip-headers=on&clean-date-tags01=%23date',
    dataType: 'json',
});

var map, data;

var myIcon = L.icon({
    iconUrl: 'img/pin@1x.svg',
    iconSize: [60, 40],
    iconAnchor: [20, 40],
    popupAnchor: [0, -14]
});

var markerClusters = L.markerClusterGroup();

generateMap();

$.when(keyStatsCall).then(function(keyStatsArgs){
    data = parseDates(['#date'],(hxlProxyToJSON(keyStatsArgs)));
    data = removeIncompletes(data);
    addSlider(data);
    data = clusterMarkers(data);
    data = filterDateRange(new Date(), 30, data);
    generateKeyStats(data);
});<|endoftext|>


<commit_before>var map = L.map('map', { });
if (location.hash) {
    var h = location.hash.substr(1).split('/');
    map.setView([h[1], h[2]], h[0]);
} else {
    map.setView([37.7, -97.3], 16);
}

var layer = null;
map.attributionControl.setPrefix('');
L.hash(map);
L.tileLayer('http://a.tiles.mapbox.com/v3/tmcw.map-l1m85h7s/{z}/{x}/{y}.png', {
        attribution: "<a target='_blank' href='http://www.openstreetmap.org/copyright.html?name=OSM Latest Changes' style='background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAMAAACelLz8AAAB11BMVEXZ2dlkZGT///////////8mJibIyMj5+fm6urr///8sLCywsLBJSUn///9eXl7////////j4+P////////Q0ND////u7u7i4uIfHx/s7OxmZmZzc3P39/fw8PDg4OD5+fmNjY1cXFz5+flQUFBGRkaIiIhtbW3///////9hYWHS0tKlpaWsrKzZ2dmgoKCpqalycnLg4OCCgoJLS0tEREQlJSX9/f3///8/Pz/e3t4jIyP///////////+/v7+Ghobp6enDw8Pl5eVXV1f////////U1NT////////////////l5eW1tbX///+4uLj////////////////////////////w8PDNzc3GxsYuLi7w8PD///////9paWmvr6/c3NwhISHe3t5UVFQfHx/y8vLn5+d3d3eXl5f////09PTs7Oz///8zMzN8fHz///+UlJT////////u7u44ODj////p6en///86Ojqurq5ZWVlfX1////////8hISFBQUGioqIlJSXV1dV6enoqKioxMTH39/eLi4s4ODj///9ra2ubm5v9/f3Nzc28vLz///9LS0v///////////+FhYUdHR3////X19cjIyM2Njaenp7///8AAAAbGxtl93oXAAAAnXRSTlNzcE9udnpweG9Gem50TnI9Z3VgbHEWeHR9dnBvendzfG5ye3N0b3A4I3Fxbm5ybm5wdG5zdXt0NHVze14eMW9udW90cld4cUdSFx11bnJvHG1ANj8VQnlwcHl4H1xwb3N8dHN8eXZvbnV5d0t4byluAyd3dwt2VnZucnEvCn11bnxyb3p4e252BHBufXFvYnRzZQxvfWpyfHdufQB9fOn/1AAAAY5JREFUKM+V0mVvwzAQBuCMmZmZmZmZmZmZGcpMa7ukWXK5H7ukVbOpmqbt/WDZfiRLdz6C+8oqAPh6+8BqnANaOI74RoASydLisnzRdiGt9yQa9pVglC7LYws8advLTxEWoJaGx1x6ksx/LdQetI5R55xIE4O2+yvhwZDgwxUaobDh1kn6F/ud9vSMBu3p5lLgycqGAZosjneCe52zLTyjEB17DRAdERkva0Rk34h3x+gNinmy7FqyKOcWiDcWfw4QgL+TXC2sH8yOJ9V1AXRaUZmdkZqCALX4APDhotKjbcZ8LDkyoiyBp3I0ipRWgVgDORu768mJCFt3uEe4SXPA1wRFqgPatEVBJpyZSDcpFBR2mKzFubgGN5BfpjEb3GTVdJtNRqrq+DE9aQcMJFSKhIyW7UFsri7JUyHJqMhNhqT+UPL/iO+8ix4e5y1P38A6zv+X0Pln89jU7LT9mtU575mLkcmZV47/r/Y9+4temIKhARutVO/3H54Mc87ZuG1rFQfn8uq+r/dc7zp8AmmAXy4xp9xiAAAAAElFTkSuQmCC) no-repeat; background-size:26px 26px;background-position:-48px -24px\0/;width:24px;height:24px;display:block;z-index:1000;bottom:2px;right:5px;bottom:5px;position:absolute;'>"
    })
    .addTo(map);

function updateMap() {
    if (map.getZoom() > 13) {
        d3.select('#map').classed('faded', true);
        d3.select('#zoom-in').classed('hide', true);
        d3.select('#results').classed('hide', false);
        run();
    } else {
        d3.select('#map').classed('faded', true);
        d3.select('#zoom-in').classed('hide', false);
        d3.select('#results').classed('hide', true);
        layer && map.removeLayer(layer);
        layer = null;
    }
}

updateMap();

function run() {
    var bounds = map.getBounds();
    d3.xml('http://www.openstreetmap.org/api/0.6/map?bbox=' +
        bounds.getSouthWest().lng + ',' +
        bounds.getSouthWest().lat + ',' +
        bounds.getNorthEast().lng + ',' +
        bounds.getNorthEast().lat // + ',' +
        ).on('load', function(xml) {
            d3.select('#map').classed('faded', false);
            layer && map.removeLayer(layer);

            layer = new L.OSM.DataLayer(xml).addTo(map);

            var bytime = [];
            var changesets = {};

            layer.eachLayer(function(l) {
                changesets[l.feature.changeset] = changesets[l.feature.changeset] || {
                    id: l.feature.changeset,
                    time: new Date(l.feature.timestamp),
                    user: l.feature.user,
                    comment: '',
                    features: []
                };
                changesets[l.feature.changeset].features.push(l);
            });
            for (var k in changesets) {
                bytime.push(changesets[k]);
            }

            layer.on('click', function(e) {
                click({ feature: e.layer });
            });

            bytime.sort(function(a, b) {
                return (+b.time) - (+a.time);
            });

            var datescale = d3.time.scale()
                .domain(d3.extent(bytime.map(function(b) { return b.time; })))
                .range([0, 1]);

            var colint = d3.interpolateRgb('#000', '#f00');
            var results = d3.select('#results');
            var allresults = results
                .selectAll('div.result')
                .data(bytime, function(d) {
                    return d.id;
                })
                .attr('class', 'result')
                .style('color', function(l) {
                    return colint(datescale(l.time));
                });
            allresults.exit().remove();

            var rl = allresults.enter()
                .append('div')
                .attr('class', 'result')
                .style('color', function(l) {
                    return colint(datescale(l.time));
                });
            allresults.order();

            function click(d) {
                results
                    .selectAll('div.result')
                    .classed('active', function(_) {
                        return _.id == (d.id || d.feature.feature.changeset);
                });
                resetStyle();
                var id = d.id ? d.id : d.feature.feature.changeset;
                layer.eachLayer(function(l) {
                    if (l.feature.changeset == id) {
                        l.setStyle({ color: '#0f0' });
                    }
                });
                if (d3.event) d3.event.preventDefault();
            }

           rl.append('a').classed('load', true).html('→ ').attr('href', '#')
           .on('click', click);

           rl.append('a').text(function(d) {
               return d.user + ' ';
           })
           .attr('target', '_blank')
           .attr('href', function(d) {
               return 'http://openstreetmap.org/user/' + d.user;
           });

           rl.append('span').attr('class', 'date').text(function(d) {
               return moment(d.time).format('MMM Do YYYY, h:mm:ss a ');
           });

           rl.append('div').attr('class', 'changeset').each(function(d) {
               var t = this;
               d3.xml('http://www.openstreetmap.org/api/0.6/changeset/' + d.id)
                   .on('load', function(xml) {
                       d3.select(t).html(
                           '' +
                           (L.OSM.getTags(xml).comment || '
–
') +
                           ''
                       );
                   })
                   .get();
               });

           function resetStyle() {
               layer.eachLayer(function(l) {
                   l.setStyle({
                       color: colint(datescale(new Date(l.feature.timestamp))),
                       opacity: 0.4,
                       weight: 6
                   });
               });
           }

           resetStyle();

    }).get();
}
var timeOutId = 0
map.on('moveend', function() {
    clearTimeout(timeOutId);
    timeOutId = setTimeout(updateMap, 500);
});
<commit_msg>Fix link.<commit_after>var map = L.map('map', { });
if (location.hash) {
    var h = location.hash.substr(1).split('/');
    map.setView([h[1], h[2]], h[0]);
} else {
    map.setView([37.7, -97.3], 16);
}

var layer = null;
map.attributionControl.setPrefix('');
L.hash(map);
L.tileLayer('http://a.tiles.mapbox.com/v3/tmcw.map-l1m85h7s/{z}/{x}/{y}.png', {
        attribution: "<a target='_blank' href='http://www.openstreetmap.org/copyright' style='background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAMAAACelLz8AAAB11BMVEXZ2dlkZGT///////////8mJibIyMj5+fm6urr///8sLCywsLBJSUn///9eXl7////////j4+P////////Q0ND////u7u7i4uIfHx/s7OxmZmZzc3P39/fw8PDg4OD5+fmNjY1cXFz5+flQUFBGRkaIiIhtbW3///////9hYWHS0tKlpaWsrKzZ2dmgoKCpqalycnLg4OCCgoJLS0tEREQlJSX9/f3///8/Pz/e3t4jIyP///////////+/v7+Ghobp6enDw8Pl5eVXV1f////////U1NT////////////////l5eW1tbX///+4uLj////////////////////////////w8PDNzc3GxsYuLi7w8PD///////9paWmvr6/c3NwhISHe3t5UVFQfHx/y8vLn5+d3d3eXl5f////09PTs7Oz///8zMzN8fHz///+UlJT////////u7u44ODj////p6en///86Ojqurq5ZWVlfX1////////8hISFBQUGioqIlJSXV1dV6enoqKioxMTH39/eLi4s4ODj///9ra2ubm5v9/f3Nzc28vLz///9LS0v///////////+FhYUdHR3////X19cjIyM2Njaenp7///8AAAAbGxtl93oXAAAAnXRSTlNzcE9udnpweG9Gem50TnI9Z3VgbHEWeHR9dnBvendzfG5ye3N0b3A4I3Fxbm5ybm5wdG5zdXt0NHVze14eMW9udW90cld4cUdSFx11bnJvHG1ANj8VQnlwcHl4H1xwb3N8dHN8eXZvbnV5d0t4byluAyd3dwt2VnZucnEvCn11bnxyb3p4e252BHBufXFvYnRzZQxvfWpyfHdufQB9fOn/1AAAAY5JREFUKM+V0mVvwzAQBuCMmZmZmZmZmZmZGcpMa7ukWXK5H7ukVbOpmqbt/WDZfiRLdz6C+8oqAPh6+8BqnANaOI74RoASydLisnzRdiGt9yQa9pVglC7LYws8advLTxEWoJaGx1x6ksx/LdQetI5R55xIE4O2+yvhwZDgwxUaobDh1kn6F/ud9vSMBu3p5lLgycqGAZosjneCe52zLTyjEB17DRAdERkva0Rk34h3x+gNinmy7FqyKOcWiDcWfw4QgL+TXC2sH8yOJ9V1AXRaUZmdkZqCALX4APDhotKjbcZ8LDkyoiyBp3I0ipRWgVgDORu768mJCFt3uEe4SXPA1wRFqgPatEVBJpyZSDcpFBR2mKzFubgGN5BfpjEb3GTVdJtNRqrq+DE9aQcMJFSKhIyW7UFsri7JUyHJqMhNhqT+UPL/iO+8ix4e5y1P38A6zv+X0Pln89jU7LT9mtU575mLkcmZV47/r/Y9+4temIKhARutVO/3H54Mc87ZuG1rFQfn8uq+r/dc7zp8AmmAXy4xp9xiAAAAAElFTkSuQmCC) no-repeat; background-size:26px 26px;background-position:-48px -24px\0/;width:24px;height:24px;display:block;z-index:1000;bottom:2px;right:5px;bottom:5px;position:absolute;'>"
    })
    .addTo(map);

function updateMap() {
    if (map.getZoom() > 13) {
        d3.select('#map').classed('faded', true);
        d3.select('#zoom-in').classed('hide', true);
        d3.select('#results').classed('hide', false);
        run();
    } else {
        d3.select('#map').classed('faded', true);
        d3.select('#zoom-in').classed('hide', false);
        d3.select('#results').classed('hide', true);
        layer && map.removeLayer(layer);
        layer = null;
    }
}

updateMap();

function run() {
    var bounds = map.getBounds();
    d3.xml('http://www.openstreetmap.org/api/0.6/map?bbox=' +
        bounds.getSouthWest().lng + ',' +
        bounds.getSouthWest().lat + ',' +
        bounds.getNorthEast().lng + ',' +
        bounds.getNorthEast().lat // + ',' +
        ).on('load', function(xml) {
            d3.select('#map').classed('faded', false);
            layer && map.removeLayer(layer);

            layer = new L.OSM.DataLayer(xml).addTo(map);

            var bytime = [];
            var changesets = {};

            layer.eachLayer(function(l) {
                changesets[l.feature.changeset] = changesets[l.feature.changeset] || {
                    id: l.feature.changeset,
                    time: new Date(l.feature.timestamp),
                    user: l.feature.user,
                    comment: '',
                    features: []
                };
                changesets[l.feature.changeset].features.push(l);
            });
            for (var k in changesets) {
                bytime.push(changesets[k]);
            }

            layer.on('click', function(e) {
                click({ feature: e.layer });
            });

            bytime.sort(function(a, b) {
                return (+b.time) - (+a.time);
            });

            var datescale = d3.time.scale()
                .domain(d3.extent(bytime.map(function(b) { return b.time; })))
                .range([0, 1]);

            var colint = d3.interpolateRgb('#000', '#f00');
            var results = d3.select('#results');
            var allresults = results
                .selectAll('div.result')
                .data(bytime, function(d) {
                    return d.id;
                })
                .attr('class', 'result')
                .style('color', function(l) {
                    return colint(datescale(l.time));
                });
            allresults.exit().remove();

            var rl = allresults.enter()
                .append('div')
                .attr('class', 'result')
                .style('color', function(l) {
                    return colint(datescale(l.time));
                });
            allresults.order();

            function click(d) {
                results
                    .selectAll('div.result')
                    .classed('active', function(_) {
                        return _.id == (d.id || d.feature.feature.changeset);
                });
                resetStyle();
                var id = d.id ? d.id : d.feature.feature.changeset;
                layer.eachLayer(function(l) {
                    if (l.feature.changeset == id) {
                        l.setStyle({ color: '#0f0' });
                    }
                });
                if (d3.event) d3.event.preventDefault();
            }

           rl.append('a').classed('load', true).html('→ ').attr('href', '#')
           .on('click', click);

           rl.append('a').text(function(d) {
               return d.user + ' ';
           })
           .attr('target', '_blank')
           .attr('href', function(d) {
               return 'http://openstreetmap.org/user/' + d.user;
           });

           rl.append('span').attr('class', 'date').text(function(d) {
               return moment(d.time).format('MMM Do YYYY, h:mm:ss a ');
           });

           rl.append('div').attr('class', 'changeset').each(function(d) {
               var t = this;
               d3.xml('http://www.openstreetmap.org/api/0.6/changeset/' + d.id)
                   .on('load', function(xml) {
                       d3.select(t).html(
                           '' +
                           (L.OSM.getTags(xml).comment || '
–
') +
                           ''
                       );
                   })
                   .get();
               });

           function resetStyle() {
               layer.eachLayer(function(l) {
                   l.setStyle({
                       color: colint(datescale(new Date(l.feature.timestamp))),
                       opacity: 0.4,
                       weight: 6
                   });
               });
           }

           resetStyle();

    }).get();
}
var timeOutId = 0
map.on('moveend', function() {
    clearTimeout(timeOutId);
    timeOutId = setTimeout(updateMap, 500);
});
<|endoftext|>


<commit_before>/*
    Operations needed:
    x Load/parse json mesh data
    x Separate script to convert .obj to .json format
    x Camera smooth zoom after mesh loaded.
    x Import geometry from source into THREE.js structures (LineSegments, mesh, Dots?)
    - Import geometry from source into program data structures (possibly a halfedge DS?)
    x Display edges
      x Don't display them twice.
      - Display them wider? If so, probably use https://github.com/spite/THREE.MeshLine
    - Display faces, including numbers!
    - Display vertices (as billboard circles? glowing stars?)
    - Pick an edge with mouse
    - Pick a face
    - Pick a vertex
    - Change a vertex from one material to another; that apparently means
      having to move it from one LineSegments to another.
    - Display a "loading" spinner while loading
*/

var MAX_POINTS = 1000, MAX_EDGES = 1000, MAX_FACES = 1000;

// Mesh to load. Points are assumed to be centered around origin.
var dataURL = 'data/';
var DEFAULT_DATA_FILE='phe-A200sC200tI.json';

var renderer, scene, camera, sphere;

var maxR = 1; // max distance from origin.
var maxR2 = 0; // maxR squared
var camR = 4 * maxR; // distance of camera
var autoRotating = true;

function init() {
    // TODO: make antialias a controllable option?
    renderer = new THREE.WebGLRenderer({antialias:  true});
    renderer.setSize( 800, 600 );
    document.body.appendChild( renderer.domElement );

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(
        35,             // Field of view
        800 / 600,      // Aspect ratio
        0.5,            // Near plane
        6              // Far plane
    );
    camera.position.set( camR, 0, 0 );
    camera.lookAt( scene.position );

    controls = new THREE.TrackballControls( camera );
    controls.rotateSpeed = 2.0;
    controls.zoomSpeed = 1.2;
    controls.panSpeed = 0.8;
    controls.noZoom = false;
    controls.noPan = false;
    controls.staticMoving = false;
    controls.dynamicDampingFactor = 0.2;
    controls.keys = [ 65, 83, 68 ];
    // Don't need the following if we use an animation loop?
    controls.addEventListener( 'change', changeControls );

    var light = new THREE.PointLight( 0xFFFF00 );
    light.position.set( 10, 10, 10 );
    scene.add( light );

    renderer.setClearColor( 0, 1);
    render();

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

    fetch(dataURL + DEFAULT_DATA_FILE)
      .then(status)
      .then(json)
      .then(function(data) {
        // console.log('Request succeeded with JSON response', data);
        importData(data);
      }).catch(function(error) {
        // TODO: inform the user?
        console.log('Request failed', error);
      });
}

// TODO: I don't think this is consistent with how we start...
// maybe subtract a right and/or bottom margin?
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( window.innerWidth, window.innerHeight );
    controls.handleResize();
    render();
}

// Load JSON:
function status(response) {
  if (response.status >= 200 && response.status < 300) {
    return Promise.resolve(response);
  } else {
    return Promise.reject(new Error(response.statusText));
  }
}

function json(response) {
  return response.json();
}

/** Length squared, of vector. */
function length2(v) {
    return v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
}

function updateMaxR(v) {
    var d2 = length2(v);
    if (d2 > maxR2) maxR2 = d2;
}

/** Pull data into Three.js and app data structures. */
function importData(data) {
    // // geometry
    // var geometry = new THREE.BufferGeometry();

    // // attributes
    // var positions = new Float32Array( MAX_POINTS * 3 ); // 3 vertices per point
    // geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
    var geometry = new THREE.Geometry();

    maxR2 = 0;

    var edgesAddedToMesh = {};

    for (var f=0; f < data.faces.length; f++) {
        var face = data.faces[f];
        for (var v=0; v < face.length; v++) {
            var nv = (v+1 >= face.length) ? 0 : v+1;
            // Check: is the reversed edge already added? If so don't add it again.
            if ([face[nv], face[v]] in edgesAddedToMesh) {
                // console.log("Edge already added", face[v], face[nv]);
                continue;
            }
            // Add this edge.
            edgesAddedToMesh[[face[v], face[nv]]] = true;

            var v1 = data.vertices[face[v]], v2 = data.vertices[face[nv]];
            updateMaxR(v1);
            geometry.vertices.push(new THREE.Vector3(v1[0], v1[1], v1[2]));
            // was: new (Function.prototype.bind.apply(THREE.Vector3, data.vertices[face[v]-1])));
            updateMaxR(v2);
            geometry.vertices.push(new THREE.Vector3(v2[0], v2[1], v2[2]));
            // was: new (Function.prototype.bind.apply(THREE.Vector3, data.vertices[face[nv]-1])));
        }
    }

    maxR = Math.sqrt(maxR2);
    console.log("maxR: ", maxR);

    var material = new THREE.LineBasicMaterial( { color: 0xff888888, linewidth: 6 } ); // 0xff888888
    sphere = new THREE.LineSegments( geometry, material );

    scene.add(sphere);

    autoRotating = true; // autorotate at first
}

/** Linear interpolation */
// Precise method, which guarantees v = v1 when t = 1.
// https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support
function lerp(v0, v1, t) {
    return (1 - t) * v0 + t * v1;
}

function animate() {
    if (autoRotating && sphere !== undefined) {
        sphere.rotation.x += 0.0005;
        sphere.rotation.y += 0.0005;
        // console.log("Rotated");
    }

    camR = lerp(camR, 4 * maxR, 0.15);
    // camera.position.set( camR, 0, 0 );
    // camera.lookAt( scene.position );

    // console.log("animate");
    requestAnimationFrame( animate );
    controls.update();
    // not needed?
    render();
}

function render() {
    console.log("render");
    renderer.render( scene, camera );
}

function changeControls() {
    console.log("changeControls");
    // Stop autorotating when user touches controls.
    autoRotating = false;
    render();
}
init();
animate();
<commit_msg>Set renderer to use window size and pixel ratio.<commit_after>/*
    Operations needed:
    x Load/parse json mesh data
    x Separate script to convert .obj to .json format
    x Camera smooth zoom after mesh loaded.
    x Import geometry from source into THREE.js structures (LineSegments, mesh, Dots?)
    - Import geometry from source into program data structures (possibly a halfedge DS?)
    x Display edges
      x Don't display them twice.
      - Display them wider? If so, probably use https://github.com/spite/THREE.MeshLine
    - Display faces, including numbers!
    - Display vertices (as billboard circles? glowing stars?)
    - Pick an edge with mouse
    - Pick a face
    - Pick a vertex
    - Change a vertex from one material to another; that apparently means
      having to move it from one LineSegments to another.
    - Display a "loading" spinner while loading
*/

var MAX_POINTS = 1000, MAX_EDGES = 1000, MAX_FACES = 1000;

// Mesh to load. Points are assumed to be centered around origin.
var dataURL = 'data/';
var DEFAULT_DATA_FILE='phe-A200sC200tI.json';

var renderer, scene, camera, sphere;

var maxR = 1; // max distance from origin.
var maxR2 = 0; // maxR squared
var camR = 4 * maxR; // distance of camera
var autoRotating = true;

function init() {
    // TODO: make antialias a controllable option?
    renderer = new THREE.WebGLRenderer({antialias:  true});
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(
        35,             // Field of view
        800 / 600,      // Aspect ratio
        0.5,            // Near plane
        6              // Far plane
    );
    camera.position.set( camR, 0, 0 );
    camera.lookAt( scene.position );

    controls = new THREE.TrackballControls( camera );
    controls.rotateSpeed = 2.0;
    controls.zoomSpeed = 1.2;
    controls.panSpeed = 0.8;
    controls.noZoom = false;
    controls.noPan = false;
    controls.staticMoving = false;
    controls.dynamicDampingFactor = 0.2;
    controls.keys = [ 65, 83, 68 ];
    // Don't need the following if we use an animation loop?
    controls.addEventListener( 'change', changeControls );

    var light = new THREE.PointLight( 0xFFFF00 );
    light.position.set( 10, 10, 10 );
    scene.add( light );

    renderer.setClearColor( 0, 1);
    render();

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

    fetch(dataURL + DEFAULT_DATA_FILE)
      .then(status)
      .then(json)
      .then(function(data) {
        // console.log('Request succeeded with JSON response', data);
        importData(data);
      }).catch(function(error) {
        // TODO: inform the user?
        console.log('Request failed', error);
      });
}

// TODO: I don't think this is consistent with how we start...
// maybe subtract a right and/or bottom margin?
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( window.innerWidth, window.innerHeight );
    controls.handleResize();
    render();
}

// Load JSON:
function status(response) {
  if (response.status >= 200 && response.status < 300) {
    return Promise.resolve(response);
  } else {
    return Promise.reject(new Error(response.statusText));
  }
}

function json(response) {
  return response.json();
}

/** Length squared, of vector. */
function length2(v) {
    return v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
}

function updateMaxR(v) {
    var d2 = length2(v);
    if (d2 > maxR2) maxR2 = d2;
}

/** Pull data into Three.js and app data structures. */
function importData(data) {
    // // geometry
    // var geometry = new THREE.BufferGeometry();

    // // attributes
    // var positions = new Float32Array( MAX_POINTS * 3 ); // 3 vertices per point
    // geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
    var geometry = new THREE.Geometry();

    maxR2 = 0;

    var edgesAddedToMesh = {};

    for (var f=0; f < data.faces.length; f++) {
        var face = data.faces[f];
        for (var v=0; v < face.length; v++) {
            var nv = (v+1 >= face.length) ? 0 : v+1;
            // Check: is the reversed edge already added? If so don't add it again.
            if ([face[nv], face[v]] in edgesAddedToMesh) {
                // console.log("Edge already added", face[v], face[nv]);
                continue;
            }
            // Add this edge.
            edgesAddedToMesh[[face[v], face[nv]]] = true;

            var v1 = data.vertices[face[v]], v2 = data.vertices[face[nv]];
            updateMaxR(v1);
            geometry.vertices.push(new THREE.Vector3(v1[0], v1[1], v1[2]));
            // was: new (Function.prototype.bind.apply(THREE.Vector3, data.vertices[face[v]-1])));
            updateMaxR(v2);
            geometry.vertices.push(new THREE.Vector3(v2[0], v2[1], v2[2]));
            // was: new (Function.prototype.bind.apply(THREE.Vector3, data.vertices[face[nv]-1])));
        }
    }

    maxR = Math.sqrt(maxR2);
    console.log("maxR: ", maxR);

    var material = new THREE.LineBasicMaterial( { color: 0xff888888, linewidth: 6 } ); // 0xff888888
    sphere = new THREE.LineSegments( geometry, material );

    scene.add(sphere);

    autoRotating = true; // autorotate at first
}

/** Linear interpolation */
// Precise method, which guarantees v = v1 when t = 1.
// https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support
function lerp(v0, v1, t) {
    return (1 - t) * v0 + t * v1;
}

function animate() {
    if (autoRotating && sphere !== undefined) {
        sphere.rotation.x += 0.0005;
        sphere.rotation.y += 0.0005;
        // console.log("Rotated");
    }

    camR = lerp(camR, 4 * maxR, 0.15);
    // camera.position.set( camR, 0, 0 );
    // camera.lookAt( scene.position );

    // console.log("animate");
    requestAnimationFrame( animate );
    controls.update();
    // not needed?
    render();
}

function render() {
    console.log("render");
    renderer.render( scene, camera );
}

function changeControls() {
    console.log("changeControls");
    // Stop autorotating when user touches controls.
    autoRotating = false;
    render();
}
init();
animate();
<|endoftext|>