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

  var lastChapter = 60; // update this and the volume switch below when adding chapters

  var chapterInfo = {};

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

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

  var fitMode = 0; // 0 - nofit, 1 - resize, 2 - fitwidth
  var hashChanging = false;
  var messageHideTimeoutContainer = null;
  var messageHideTimeout = 4000;

  function changeCurrentVolume(chapterIndex) {
    var oldVolume = currentVolume;
    if (chapterIndex > 52) {
      currentVolume = 9;
    }
    else if (chapterIndex > 46) {
      currentVolume = 8;
    }
    else if (chapterIndex > 40) {
      currentVolume = 7;
    }
    else if (chapterIndex > 34) {
      currentVolume = 6;
    }
    else if (chapterIndex > 29) {
      currentVolume = 5;
    }
    else if (chapterIndex > 24) {
      currentVolume = 4;
    }
    else if (chapterIndex > 17) {
      currentVolume = 3;
    }
    else if (chapterIndex > 9) {
      currentVolume = 2;
    }
    else {
      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;
    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" && e.target.id !== "infoButton") {
      hideInfo();
    }
  }

  function keyCheck(e) {
    if (e.keyCode > 48 && e.keyCode < 52) { // 1, 2, 3
      setFit(e.keyCode - 49);
    }
    else 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 showMessage(msg) {
    if (messageHideTimeoutContainer !== null) {
      clearTimeout("messageHideTimeoutContainer");
    }
    if (!msg) {
      msg = "Empty message!"
    }
    messageElement.innerHTML = msg;
    messageElement.classList.remove("hidden");
    messageHideTimeoutContainer = setTimeout(hideMessage, messageHideTimeout);
  }

  function hideMessage() {
    messageElement.classList.add("hidden");
    messageElement.innerHTML = "";
    messageHideTimeoutContainer = null;
  }

  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("/");
      split = split[split.length - 1].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() {
    setFit((fitMode + 1) % 3);
  }

  function setFit(mode) {
    var msg;
    fitMode = mode;
    if (fitMode === 1) {
      imageElement.className = "resize";
      imageContainerElement.className = "resize";
      msg = "Resized";
    }
    else if (fitMode === 2) {
      imageElement.className = "fitwidth";
      imageContainerElement.className = "fitwidth";
      msg = "Fit width";
    }
    else {
      fitMode = 0;
      imageElement.className = "nofit";
      imageContainerElement.className = "nofit";
      msg = "Full size";
    }
    localStorage.setItem("reader-fit-mode", fitMode.toString());
    fitButtonElement.title = msg;
    fitButtonElement.innerHTML = "<" + (fitMode + 1) + ">";
    showMessage(msg);
  }

  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");
    imageContainerElement = document.getElementById("imageContainer");
    loadingElement = document.getElementById("loading");
    messageElement = document.getElementById("message");
    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");
    fitButtonElement = document.getElementById("fitButton");
    setFit(parseInt(localStorage.getItem("reader-fit-mode")));
    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);
    fitButtonElement.addEventListener("click", toggleFit);
    document.getElementById("downloadButton").addEventListener("click", downloadPage);
    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 = 71; // update this and the volume switch below when adding chapters

  var chapterInfo = {};

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

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

  var fitMode = 0; // 0 - nofit, 1 - resize, 2 - fitwidth
  var hashChanging = false;
  var messageHideTimeoutContainer = null;
  var messageHideTimeout = 4000;

  function changeCurrentVolume(chapterIndex) {
    var oldVolume = currentVolume;
    if (chapterIndex > 60) {
      currentVolume = 10;
    }
    else if (chapterIndex > 52) {
      currentVolume = 9;
    }
    else if (chapterIndex > 46) {
      currentVolume = 8;
    }
    else if (chapterIndex > 40) {
      currentVolume = 7;
    }
    else if (chapterIndex > 34) {
      currentVolume = 6;
    }
    else if (chapterIndex > 29) {
      currentVolume = 5;
    }
    else if (chapterIndex > 24) {
      currentVolume = 4;
    }
    else if (chapterIndex > 17) {
      currentVolume = 3;
    }
    else if (chapterIndex > 9) {
      currentVolume = 2;
    }
    else {
      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;
    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" && e.target.id !== "infoButton") {
      hideInfo();
    }
  }

  function keyCheck(e) {
    if (e.keyCode > 48 && e.keyCode < 52) { // 1, 2, 3
      setFit(e.keyCode - 49);
    }
    else 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 showMessage(msg) {
    if (messageHideTimeoutContainer !== null) {
      clearTimeout("messageHideTimeoutContainer");
    }
    if (!msg) {
      msg = "Empty message!"
    }
    messageElement.innerHTML = msg;
    messageElement.classList.remove("hidden");
    messageHideTimeoutContainer = setTimeout(hideMessage, messageHideTimeout);
  }

  function hideMessage() {
    messageElement.classList.add("hidden");
    messageElement.innerHTML = "";
    messageHideTimeoutContainer = null;
  }

  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("/");
      split = split[split.length - 1].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() {
    setFit((fitMode + 1) % 3);
  }

  function setFit(mode) {
    var msg;
    fitMode = mode;
    if (fitMode === 1) {
      imageElement.className = "resize";
      imageContainerElement.className = "resize";
      msg = "Resized";
    }
    else if (fitMode === 2) {
      imageElement.className = "fitwidth";
      imageContainerElement.className = "fitwidth";
      msg = "Fit width";
    }
    else {
      fitMode = 0;
      imageElement.className = "nofit";
      imageContainerElement.className = "nofit";
      msg = "Full size";
    }
    localStorage.setItem("reader-fit-mode", fitMode.toString());
    fitButtonElement.title = msg;
    fitButtonElement.innerHTML = "<" + (fitMode + 1) + ">";
    showMessage(msg);
  }

  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");
    imageContainerElement = document.getElementById("imageContainer");
    loadingElement = document.getElementById("loading");
    messageElement = document.getElementById("message");
    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");
    fitButtonElement = document.getElementById("fitButton");
    setFit(parseInt(localStorage.getItem("reader-fit-mode")));
    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);
    fitButtonElement.addEventListener("click", toggleFit);
    document.getElementById("downloadButton").addEventListener("click", downloadPage);
    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>function Rect(initX) {
  this.x = initX;
  this.y = 288 - 32;
  this.velocity = 0;
  this.veleftright = 0;
  this.tail = this.x + 32;
};

Rect.prototype.draw = function(context) {
  //context.beginPath();
  context.strokeRect(this.x, this.y, 32, 32);
  //context.stroke();
  //context.closePath();
};

Rect.prototype.update = function() {
  /*if (this.x < -32) {
    this.x = Game.entites[16].tail;

  } else if (this.x > 512) {
    this.x = -32;
  }*/

  if(player.input.left == true){
    this.veleftright = 5;
    if(player.input.jump == true){
      this.veleftright += 5;
    }
  }else if(player.input.right == true){
    this.veleftright = -5;
    if(player.input.jump == true){
      this.veleftright -= 5;
    }
  }else{
    this.veleftright = 0;
  }

  this.y += this.velocity;
  this.x += this.veleftright;
  this.tail = this.x + 32;
};
<commit_msg>Update rect.js<commit_after>function Rect(initX) {
  this.x = initX;
  this.y = 288 - 32;
  this.velocity = 0;
  this.veleftright = 0;
  this.tail = this.x + 32;
};

Rect.prototype.draw = function(context) {
  //context.beginPath();
  context.fillRect(this.x, this.y, 32, 32);
  //context.stroke();
  //context.closePath();
};

Rect.prototype.update = function() {
  /*if (this.x < -32) {
    this.x = Game.entites[16].tail;

  } else if (this.x > 512) {
    this.x = -32;
  }*/

  if(player.input.left == true){
    this.veleftright = 5;
    if(player.input.jump == true){
      this.veleftright += 5;
    }
  }else if(player.input.right == true){
    this.veleftright = -5;
    if(player.input.jump == true){
      this.veleftright -= 5;
    }
  }else{
    this.veleftright = 0;
  }

  this.y += this.velocity;
  this.x += this.veleftright;
  this.tail = this.x + 32;
};
<|endoftext|>


<commit_before>/*global jQuery, Snap */

"use strict";

(function(w, $, Snap) {
    var $w = $(window);
    $(function() {
	$('img#nz-map').width($w.width());
        var svg = $('<svg id="cursor-shadow"><rect/></svg>').appendTo('body').css({height: 25, width: 25});
	var s = Snap('svg#cursor-shadow');
	var c = s.circle(svg.width()/2, svg.height()/2, Math.min(svg.width(), svg.height())/2 - 2);
	$(window).mousemove(function(e) {
	    svg.css({left: e.pageX - svg.width()/2, top:e.pageY - svg.height()/2});
	});
    });
})(window, jQuery, Snap);
<commit_msg>js3 code formatting~<commit_after>/*global jQuery, Snap */

(function(w, $, Snap) {
  "use strict";
  var $w = $(window);
  $(function() {
    $('img#nz-map').width($w.width());
    var svg = $('<svg id="cursor-shadow"><rect/></svg>').appendTo('body').css({height: 25, width: 25});
    /*jshint newcap:false */
    var s = Snap('svg#cursor-shadow');
    var c = s.circle(svg.width()/2, svg.height()/2, Math.min(svg.width(), svg.height())/2 - 2);
    $(window).mousemove(function(e) {
      svg.css({left: e.pageX - svg.width()/2, top:e.pageY - svg.height()/2});
    });
  });
})(window, jQuery, Snap);
<|endoftext|>


<commit_before>/**
 * @constructor
 */
function User(user_id, position, color, mouse_is_down, it_is_me, nickname, use_pen){

    this.reposition_label = function(){
        if (this.it_is_me) return
        this.label.style.left = (canvas.offsetLeft + this.position[0] - CROSSHAIR_HALF_SIZE) + "px"
        this.label.style.top = (this.position[1] - CROSSHAIR_HALF_SIZE) + "px"
    }

    this.create_label = function(){
        var text = document.createTextNode(this.nickname || this.user_id)
        if (this.it_is_me){
            nickname_span.appendChild(text)
        }else{
            this.label = create_element("div")
            this.label.appendChild(text)
            this.label.style.position = "absolute"
            this.label.style.paddingLeft = "16px"
            this.label.style.zIndex = reverse_zindex(4)
            this.label.style.background = "url(http://" + DOMAIN + "/static/crosshair.png) no-repeat"
            this.reposition_label()
            document.body.appendChild(this.label)
        }
    }

    this.init = function(user_id, position, color, mouse_is_down, it_is_me, nickname, use_pen){
        this.user_id       = user_id
        this.position      = position
        this.color         = color
        this.mouse_is_down = mouse_is_down
        this.it_is_me      = it_is_me
        this.nickname      = nickname
        this.use_pen       = use_pen
        users[this.user_id] = this
        this.create_label()
    }

    this.init(user_id, position, color, mouse_is_down, it_is_me, nickname, use_pen)

    this.mouse_up = function(){
        this.mouse_is_down = false
    }

    this.mouse_down = function(){
        this.mouse_is_down = true
    }

    this.mouse_move = function(x, y, duration){
        if (this.mouse_is_down){
            draw_line(
                this.position[0], this.position[1],          // origin
                x, y,                                        // destination
                duration,                                    // duration
                this.color[0], this.color[1], this.color[2], // color
                this.use_pen,                                // pen or eraser
                ctx                                          // context
            )
            if (this.use_pen && this.it_is_me){
                mask_shift()
            }
        }
        this.position = [x, y]
        this.reposition_label()
    }

    this.change_color = function(red, green, blue){
        this.color = [red, green, blue]
    }

    this.change_tool = function(use_pen){
        this.use_pen = use_pen
    }

    this.change_nickname = function(nickname, timestamp){
        add_chat_notification(this.get_label() + " is now known as " + nickname, timestamp)
        this.nickname = nickname
        if (this.it_is_me){
            nickname_span.removeChild(nickname_span.firstChild)
            nickname_span.appendChild(document.createTextNode(nickname))
        }else{
            this.label.removeChild(this.label.firstChild)
            var text = document.createTextNode(this.nickname)
            this.label.appendChild(text)
        }
    }

    this.destroy = function(){
        if (this.label){
            document.body.removeChild(this.label)
        }
        delete users[this.user_id]
    }

    this.get_label = function(){
        return this.nickname || this.user_id
    }
}
<commit_msg>user labels in frame_div<commit_after>/**
 * @constructor
 */
function User(user_id, position, color, mouse_is_down, it_is_me, nickname, use_pen){

    this.reposition_label = function(){
        if (this.it_is_me) return
        this.label.style.left = (canvas.offsetLeft + this.position[0] - CROSSHAIR_HALF_SIZE) + "px"
        this.label.style.top = (this.position[1] - CROSSHAIR_HALF_SIZE) + "px"
    }

    this.create_label = function(){
        var text = document.createTextNode(this.nickname || this.user_id)
        if (this.it_is_me){
            nickname_span.appendChild(text)
        }else{
            this.label = create_element("div")
            this.label.appendChild(text)
            this.label.style.position = "absolute"
            this.label.style.paddingLeft = "16px"
            this.label.style.zIndex = reverse_zindex(4)
            this.label.style.background = "url(http://" + DOMAIN + "/static/crosshair.png) no-repeat"
            this.reposition_label()
            frame_div.appendChild(this.label)
        }
    }

    this.init = function(user_id, position, color, mouse_is_down, it_is_me, nickname, use_pen){
        this.user_id       = user_id
        this.position      = position
        this.color         = color
        this.mouse_is_down = mouse_is_down
        this.it_is_me      = it_is_me
        this.nickname      = nickname
        this.use_pen       = use_pen
        users[this.user_id] = this
        this.create_label()
    }

    this.init(user_id, position, color, mouse_is_down, it_is_me, nickname, use_pen)

    this.mouse_up = function(){
        this.mouse_is_down = false
    }

    this.mouse_down = function(){
        this.mouse_is_down = true
    }

    this.mouse_move = function(x, y, duration){
        if (this.mouse_is_down){
            draw_line(
                this.position[0], this.position[1],          // origin
                x, y,                                        // destination
                duration,                                    // duration
                this.color[0], this.color[1], this.color[2], // color
                this.use_pen,                                // pen or eraser
                ctx                                          // context
            )
            if (this.use_pen && this.it_is_me){
                mask_shift()
            }
        }
        this.position = [x, y]
        this.reposition_label()
    }

    this.change_color = function(red, green, blue){
        this.color = [red, green, blue]
    }

    this.change_tool = function(use_pen){
        this.use_pen = use_pen
    }

    this.change_nickname = function(nickname, timestamp){
        add_chat_notification(this.get_label() + " is now known as " + nickname, timestamp)
        this.nickname = nickname
        if (this.it_is_me){
            nickname_span.removeChild(nickname_span.firstChild)
            nickname_span.appendChild(document.createTextNode(nickname))
        }else{
            this.label.removeChild(this.label.firstChild)
            var text = document.createTextNode(this.nickname)
            this.label.appendChild(text)
        }
    }

    this.destroy = function(){
        if (this.label){
            frame_div.removeChild(this.label)
        }
        delete users[this.user_id]
    }

    this.get_label = function(){
        return this.nickname || this.user_id
    }
}
<|endoftext|>


<commit_before>// ======================================================================
// formats a given hashrate (H/s) to humand readable hashrate
// like xxx.yyy GH/s
// ======================================================================
var formatHashrate = function (rate) {
  rate = parseFloat(rate);
  unit = 'H/s';
  if (rate >= 1000) { rate /= 1000; unit = 'KH/s'; }
  if (rate >= 1000) { rate /= 1000; unit = 'MH/s'; }
  if (rate >= 1000) { rate /= 1000; unit = 'GH/s'; }
  if (rate >= 1000) { rate /= 1000; unit = 'TH/s'; }
  if (rate >= 1000) { rate /= 1000; unit = 'PH/s'; }

  return (rate.toFixed(2) + ' ' + unit);
}

// ======================================================================
// formats a given int value to human readable si format
// ======================================================================
var formatInt = function (rate) {
  rate = parseFloat(rate);
  unit = '';
  if (rate >= 1000) { rate /= 1000; unit = 'k'; }
  if (rate >= 1000) { rate /= 1000; unit = 'M'; }
  if (rate >= 1000) { rate /= 1000; unit = 'G'; }
  if (rate >= 1000) { rate /= 1000; unit = 'T'; }

  return ((unit == '' ? rate.toFixed(0) : rate.toFixed(2)) + unit);
}

// ======================================================================
// format seconds to an interval like '1d 7h 5s'
// ======================================================================
const formatSeconds = function(time) {
  const sec_num = parseInt(time, 10);
  const days = Math.floor(sec_num / 86400);
  const hours = Math.floor((sec_num - (days * 86400)) / 3600);
  const minutes = Math.floor((sec_num - (days * 86400 + hours * 3600)) / 60);
  const seconds = sec_num - (days * 86400) - (hours * 3600) - (minutes * 60);

  let formatted = '';
  if (days > 0) { formatted += days + 'd '; }
  formatted += hours + 'h ' + minutes + 'm ' + seconds + 's';

  return formatted;
}

// ======================================================================
// Sorts a dict by value
// ======================================================================
function sortByValue(toSort) {
  var keys = Object.keys(toSort);
  keys.sort(function (a, b) {
    return toSort[a] < toSort[b] ? -1 : (toSort[a] === toSort[b] ? 0 : 1);
  });

  return keys;
}
<commit_msg>Fixing up the utility functions, making them es6 compliant, better scoping<commit_after>// ======================================================================
// formats a given hashrate (H/s) to humand readable hashrate
// like xxx.yyy GH/s
// ======================================================================
const formatHashrate = function(rate) {
  rate = parseFloat(rate);
  let unit = 'H/s';
  if (rate >= 1000) { rate /= 1000; unit = 'KH/s'; }
  if (rate >= 1000) { rate /= 1000; unit = 'MH/s'; }
  if (rate >= 1000) { rate /= 1000; unit = 'GH/s'; }
  if (rate >= 1000) { rate /= 1000; unit = 'TH/s'; }
  if (rate >= 1000) { rate /= 1000; unit = 'PH/s'; }

  return (rate.toFixed(2) + ' ' + unit);
}

// ======================================================================
// formats a given int value to human readable si format
// ======================================================================
const formatInt = function(rate) {
  rate = parseFloat(rate);
  let unit = '';
  if (rate >= 1000) { rate /= 1000; unit = 'k'; }
  if (rate >= 1000) { rate /= 1000; unit = 'M'; }
  if (rate >= 1000) { rate /= 1000; unit = 'G'; }
  if (rate >= 1000) { rate /= 1000; unit = 'T'; }

  return ((unit == '' ? rate.toFixed(0) : rate.toFixed(2)) + unit);
}

// ======================================================================
// format seconds to an interval like '1d 7h 5s'
// ======================================================================
const formatSeconds = function(time) {
  const sec_num = parseInt(time, 10);
  const days = Math.floor(sec_num / 86400);
  const hours = Math.floor((sec_num - (days * 86400)) / 3600);
  const minutes = Math.floor((sec_num - (days * 86400 + hours * 3600)) / 60);
  const seconds = sec_num - (days * 86400) - (hours * 3600) - (minutes * 60);

  let formatted = '';
  if (days > 0) { formatted += days + 'd '; }
  formatted += hours + 'h ' + minutes + 'm ' + seconds + 's';

  return formatted;
}

// ======================================================================
// Sorts a dict by value
// ======================================================================
const sortByValue = function(toSort) {
  const keys = Object.keys(toSort);
  keys.sort(function (a, b) {
    return toSort[a] < toSort[b] ? -1 : (toSort[a] === toSort[b] ? 0 : 1);
  });

  return keys;
}
<|endoftext|>


<commit_before>define(['jquery', 'underscore', 'backbone', 'data', 'ui', 'nouislider', 'LZString', 'bootstrap', 'bootstrap-select', 'jquery.unveil'], function ($, _, Backbone, Data, Ui, noUiSlider, LZString, BitSet, skillDescTemplate) {
    var activeMenu = "";
    var runeList = [];
    var runeCheckList = [];
    var classId = 0;
    var minX = 0;
    var maxX = 0;
    var minY = 0;
    var maxY = 0;
    var scale = 0.2;

    var initUiLanguage = function () {
        $('[data-lang]').each(function () {
            var $this = $(this);
            var key = $this.data("lang");
            var value = Ui.getText(key);
            $this.text(value);
        });
    };
    var getActiveMenu = function () {
        return activeMenu;
    }
    var setActiveMenu = function (id) {
        activeMenu = id;
        $("nav.navbar .active").removeClass('active');
        //$("body>div[data-tab]").hide();
        var current = $("nav.navbar [data-class-id=" + id + "]");
        current.parents('li').addClass('active');
    };
    var clear = function () {
        runeList = [];
        runeCheckList = [];
    };
    var render = function (id, savedata) {
        var self = this;
        if (id == 0) {
            return;
        }
        classId = id;
        setActiveMenu(id);
        //clear main
        $('#main').find("img").attr('src', ''); //stop image loading when doPage
        $('#main').empty();
        clear();
        //get data
        var astrolabe = Data.getAstrolabe();

        minX = _.min(astrolabe, function (o) { return o.X }).X;
        maxX = _.max(astrolabe, function (o) { return o.X }).X;
        minY = _.min(astrolabe, function (o) { return o.Y }).Y;
        maxY = _.max(astrolabe, function (o) { return o.Y }).Y;

        var $div = $("
").addClass("rune-container");

        _.each(astrolabe, function (o, i) {
            //debugger;
            var cost = Data.getRuneCost(o.Id);
            var desc = Data.getRuneDesc(o.Id, classId);
            var $rune = $("")
                .css("left", (o.X - minX) * scale)
                .css("top", (maxY - o.Y) * scale)
                .addClass("rune")
                .attr("id", "rune" + o.Id)
                .attr("data-id", o.Id)
                .data("rune", o)
                .data("cost", cost)
                .data("desc", desc)
                .data("status", 0)  //0:unchecked,1:checked,2:saved
                .attr("data-toggle", "popover")
                .attr("title", desc.Name)
                .attr("data-content", (desc.Desc || "")
                + "
" + _.reduce(cost, function (result, current) {
                    return result + current.Name + "*" + current.Count + " ";
                }, ""))
                .click(function () {
                    runeClick(o);
                });
            if (o.Id == 10000) {
                //set default rune as saved
                runeList.push(10000);
                $rune.addClass("rune-center")
                    .data("status", 2)
                    .attr("title", "")
                    .attr("data-toggle", "")
                    .off('click');
            }
            if (o.Evo == 3) {
                $rune.addClass("rune-not-available")
                    .attr("title", "")
                    .attr("data-toggle", "")
                    .off('click');
            }
            if (desc.SpecialDescId) {
                $rune.addClass("rune-special");
            }
            $div.append($rune);
        });
        $('#main').append($div);

        $('[data-toggle="popover"]').popover({
            //container: 'body',
            html: true,
            trigger: 'hover focus'
        });

        renderRuneLink();

        $('#btnSearch').click(function () {
            var text = $('#txtSearch').val();
            $('.rune[data-original-title*="' + text + '"]').popover('show');
        });
        $('#btnClear').click(function () {
            $('[data-toggle="popover"]').popover('hide');
        });

        $('#btnReset').click(function () {
            if (confirm("是否重置本次选择？")) {
                _.each(runeCheckList, function (o, i) {
                    var $rune = $("#rune" + o);
                    $rune.data('status', 0)
                        .removeClass('rune-checked')
                });
                runeCheckList = [];

                renderRuneLink();
                renderCost();
            }
        });
        $('#btnSave').click(function () {
            save();
        });

        if (savedata) {
            load(savedata);
        }

        setTimeout(function () {
            //a little delay to unveil for better unveil effect
            $('#main').find("img").unveil();
        }, 100);
    };

    var renderRuneLink = function () {
        $(".rune-link-container").remove();
        var $runeLink = $("<canvas>")
            .css("left", 0)
            .css("top", 0)
            .attr("width", (maxX - minX + 10) * scale)
            .attr("height", (maxY - minY + 10) * scale)
            .addClass("rune-link-container");
        $('.rune-container').append($runeLink);
        var linkcontext = $runeLink[0].getContext('2d');
        $(".rune").each(function (i, o) {
            var $rune = $(o);
            var runeData = $rune.data("rune")
            _.each(runeData.Link, function (o, i) {
                var $runeTo = $(".rune[data-id=" + o + "]");
                var runeToData = $runeTo.data("rune");
                if ($runeTo.length > 0) {
                    linkcontext.beginPath();
                    linkcontext.moveTo($rune.position().left + 5, $rune.position().top + 5);
                    linkcontext.lineTo($runeTo.position().left + 5, $runeTo.position().top + 5);
                    linkcontext.lineWidth = 3;
                    if (runeData.Evo == 3 || runeToData.Evo == 3) {
                        linkcontext.strokeStyle = 'rgba(233, 233, 233, 0.15)';
                    }
                    else if ($rune.data('status') == 0 || $runeTo.data('status') == 0) {
                        linkcontext.strokeStyle = '#aaa';
                    }
                    else {
                        linkcontext.strokeStyle = 'skyblue';
                    }
                    linkcontext.stroke();
                }
            });
        });
    };
    var renderCost = function () {
        var runeCost = [];
        var runeCheckCost = [];
        $(".rune").each(function (i, o) {
            var $rune = $(o);
            var runeData = $rune.data("rune")
            var status = $rune.data('status');
            var cost = $rune.data('cost');
            switch (status) {
                case 0: break;
                case 1: runeCheckCost.push(cost); break;
                case 2: runeCost.push(cost); break;
                default: break;
            }
        });
        runeCheckCost = _.reduce(runeCheckCost, function (memo, item) {
            _.each(item, function (o, i) {
                memo[o.Name] = (memo[o.Name] || 0) + o.Count;
            })
            return memo;
        }, {});
        runeCost = _.reduce(runeCost, function (memo, item) {
            _.each(item, function (o, i) {
                memo[o.Name] = (memo[o.Name] || 0) + o.Count;
            })
            return memo;
        }, {});
        var runeCheckCostText = "";
        _.each(runeCheckCost, function (o, i) {
            runeCheckCostText += i + "*" + o + " ";
        })
        $('#runeCheckCost').text(runeCheckCostText);
        var runeCostText = "";
        _.each(runeCost, function (o, i) {
            runeCostText += i + "*" + o + " ";
        })
        $('#runeCost').text(runeCostText);
    };

    var runeClick = function (rune) {
        var $rune = $("#rune" + rune.Id);
        var status = $rune.data('status');
        switch (status) {
            case 0: checkRune(rune.Id); break;
            case 1: uncheckRune(rune.Id); break;
            case 2: uncheckRuneWithConfirm(rune.Id); break;
            default: break;
        }
        renderRuneLink();
        renderCost();
    };

    var checkRune = function (runeId, noRecursion, isSaved) {
        if (runeId == 10000) {
            return;
        }
        var $rune = $("#rune" + runeId);
        if ($rune.data('rune').evo == 3) {
            return;
        }
        if (!noRecursion) {
            var path = Data.getPath(runeList.concat(runeCheckList), runeId);
            console.log("getPath", path);
            if (!path.length) {
                alert("无路径！")
                return;
            }
            _.each(path, function (o, i) {
                checkRune(o, true);
            });
        }
        else {
            if (isSaved) {
                $rune.data('status', 2)
                    .addClass('rune-saved');
            }
            else {
                $rune.data('status', 1)
                    .addClass('rune-checked');
                runeCheckList.push(runeId);
            }
        }
    };
    var uncheckRuneWithConfirm = function (runeId) {
        if (confirm("是否取消选中该符文？")) {
            uncheckRune(runeId);
        }
    };
    var uncheckRune = function (runeId, noRecursion) {
        if (runeId == 10000) {
            return;
        }
        var $rune = $("#rune" + runeId);
        if ($rune.data('rune').evo == 3) {
            return;
        }
        $rune.data('status', 0)
            .removeClass('rune-checked')
            .removeClass('rune-saved');
        runeList = _.without(runeList, runeId);
        runeCheckList = _.without(runeCheckList, runeId);
        if (!noRecursion) {
            var components = Data.getConnectedComponent(runeList.concat(runeCheckList));
            _.each(components, function (o, i) {
                if (_.contains(o, 10000) == false) {
                    _.each(o, function (p, j) {
                        uncheckRune(p, true);
                    });
                }
            });
        }
    };

    var save = function () {
        runeList = _.unique(runeList.concat(runeCheckList));
        runeCheckList = [];
        _.each(runeList, function (o, i) {
            var $rune = $("#rune" + o);
            $rune.data('status', 2)
                .removeClass('rune-checked')
                .addClass('rune-saved');
        });
        renderCost();

        var data = stringifyCondition(runeList);
        Backbone.history.navigate("class/" + classId + "/share/" + data, { trigger: false });
    };
    var load = function (savedata) {
        runeList = parseCondition(savedata);
        _.each(runeList, function (o, i) {
            checkRune(o, true, true);
        });
        renderRuneLink();
        renderCost();
    };

    function stringifyCondition(condition) {
        return LZString.compressToEncodedURIComponent(JSON.stringify(condition));
    }

    function parseCondition(conditionJson) {
        return JSON.parse(LZString.decompressFromEncodedURIComponent(conditionJson));
    }

    return {
        initUiLanguage: initUiLanguage,
        getActiveMenu: getActiveMenu,
        setActiveMenu: setActiveMenu,
        render: render,
    };
});<commit_msg>bugfix<commit_after>define(['jquery', 'underscore', 'backbone', 'data', 'ui', 'nouislider', 'LZString', 'bootstrap', 'bootstrap-select', 'jquery.unveil'], function ($, _, Backbone, Data, Ui, noUiSlider, LZString, BitSet, skillDescTemplate) {
    var activeMenu = "";
    var runeList = [];
    var runeCheckList = [];
    var classId = 0;
    var minX = 0;
    var maxX = 0;
    var minY = 0;
    var maxY = 0;
    var scale = 0.2;

    var initUiLanguage = function () {
        $('[data-lang]').each(function () {
            var $this = $(this);
            var key = $this.data("lang");
            var value = Ui.getText(key);
            $this.text(value);
        });
    };
    var getActiveMenu = function () {
        return activeMenu;
    }
    var setActiveMenu = function (id) {
        activeMenu = id;
        $("nav.navbar .active").removeClass('active');
        //$("body>div[data-tab]").hide();
        var current = $("nav.navbar [data-class-id=" + id + "]");
        current.parents('li').addClass('active');
    };
    var clear = function () {
        runeList = [];
        runeCheckList = [];
    };
    var render = function (id, savedata) {
        var self = this;
        if (id == 0) {
            return;
        }
        classId = id;
        setActiveMenu(id);
        //clear main
        $('#main').find("img").attr('src', ''); //stop image loading when doPage
        $('#main').empty();
        clear();
        //get data
        var astrolabe = Data.getAstrolabe();

        minX = _.min(astrolabe, function (o) { return o.X }).X;
        maxX = _.max(astrolabe, function (o) { return o.X }).X;
        minY = _.min(astrolabe, function (o) { return o.Y }).Y;
        maxY = _.max(astrolabe, function (o) { return o.Y }).Y;

        var $div = $("
").addClass("rune-container");

        _.each(astrolabe, function (o, i) {
            //debugger;
            var cost = Data.getRuneCost(o.Id);
            var desc = Data.getRuneDesc(o.Id, classId);
            var $rune = $("")
                .css("left", (o.X - minX) * scale)
                .css("top", (maxY - o.Y) * scale)
                .addClass("rune")
                .attr("id", "rune" + o.Id)
                .attr("data-id", o.Id)
                .data("rune", o)
                .data("cost", cost)
                .data("desc", desc)
                .data("status", 0)  //0:unchecked,1:checked,2:saved
                .attr("data-toggle", "popover")
                .attr("title", desc.Name)
                .attr("data-content", (desc.Desc || "")
                + "
" + _.reduce(cost, function (result, current) {
                    return result + current.Name + "*" + current.Count + " ";
                }, ""))
                .click(function () {
                    runeClick(o);
                });
            if (o.Id == 10000) {
                //set default rune as saved
                runeList.push(10000);
                $rune.addClass("rune-center")
                    .data("status", 2)
                    .attr("title", "")
                    .attr("data-toggle", "")
                    .off('click');
            }
            if (o.Evo == 3) {
                $rune.addClass("rune-not-available")
                    .attr("title", "")
                    .attr("data-toggle", "")
                    .off('click');
            }
            if (desc.SpecialDescId) {
                $rune.addClass("rune-special");
            }
            $div.append($rune);
        });
        $('#main').append($div);

        $('[data-toggle="popover"]').popover({
            //container: 'body',
            html: true,
            trigger: 'hover focus'
        });

        renderRuneLink();
        renderCost();

        $('#btnSearch').off('click').click(function () {
            var text = $('#txtSearch').val();
            $('.rune[data-original-title*="' + text + '"]').popover('show');
        });
        $('#btnClear').off('click').click(function () {
            $('[data-toggle="popover"]').popover('hide');
        });

        $('#btnReset').off('click').click(function () {
            if (confirm("是否重置本次选择？")) {
                _.each(runeCheckList, function (o, i) {
                    var $rune = $("#rune" + o);
                    $rune.data('status', 0)
                        .removeClass('rune-checked')
                });
                runeCheckList = [];

                renderRuneLink();
                renderCost();
            }
        });
        $('#btnSave').off('click').click(function () {
            save();
        });

        if (savedata) {
            load(savedata);
        }

        setTimeout(function () {
            //a little delay to unveil for better unveil effect
            $('#main').find("img").unveil();
        }, 100);
    };

    var renderRuneLink = function () {
        $(".rune-link-container").remove();
        var $runeLink = $("<canvas>")
            .css("left", 0)
            .css("top", 0)
            .attr("width", (maxX - minX + 10) * scale)
            .attr("height", (maxY - minY + 10) * scale)
            .addClass("rune-link-container");
        $('.rune-container').append($runeLink);
        var linkcontext = $runeLink[0].getContext('2d');
        $(".rune").each(function (i, o) {
            var $rune = $(o);
            var runeData = $rune.data("rune")
            _.each(runeData.Link, function (o, i) {
                var $runeTo = $(".rune[data-id=" + o + "]");
                var runeToData = $runeTo.data("rune");
                if ($runeTo.length > 0) {
                    linkcontext.beginPath();
                    linkcontext.moveTo($rune.position().left + 5, $rune.position().top + 5);
                    linkcontext.lineTo($runeTo.position().left + 5, $runeTo.position().top + 5);
                    linkcontext.lineWidth = 3;
                    if (runeData.Evo == 3 || runeToData.Evo == 3) {
                        linkcontext.strokeStyle = 'rgba(233, 233, 233, 0.15)';
                    }
                    else if ($rune.data('status') == 0 || $runeTo.data('status') == 0) {
                        linkcontext.strokeStyle = '#aaa';
                    }
                    else {
                        linkcontext.strokeStyle = 'skyblue';
                    }
                    linkcontext.stroke();
                }
            });
        });
    };
    var renderCost = function () {
        var runeCost = [];
        var runeCheckCost = [];
        $(".rune").each(function (i, o) {
            var $rune = $(o);
            var runeData = $rune.data("rune")
            var status = $rune.data('status');
            var cost = $rune.data('cost');
            switch (status) {
                case 0: break;
                case 1: runeCheckCost.push(cost); break;
                case 2: runeCost.push(cost); break;
                default: break;
            }
        });
        runeCheckCost = _.reduce(runeCheckCost, function (memo, item) {
            _.each(item, function (o, i) {
                memo[o.Name] = (memo[o.Name] || 0) + o.Count;
            })
            return memo;
        }, {});
        runeCost = _.reduce(runeCost, function (memo, item) {
            _.each(item, function (o, i) {
                memo[o.Name] = (memo[o.Name] || 0) + o.Count;
            })
            return memo;
        }, {});
        var runeCheckCostText = "";
        _.each(runeCheckCost, function (o, i) {
            runeCheckCostText += i + "*" + o + " ";
        })
        $('#runeCheckCost').text(runeCheckCostText);
        var runeCostText = "";
        _.each(runeCost, function (o, i) {
            runeCostText += i + "*" + o + " ";
        })
        $('#runeCost').text(runeCostText);
    };

    var runeClick = function (rune) {
        var $rune = $("#rune" + rune.Id);
        var status = $rune.data('status');
        switch (status) {
            case 0: checkRune(rune.Id); break;
            case 1: uncheckRune(rune.Id); break;
            case 2: uncheckRuneWithConfirm(rune.Id); break;
            default: break;
        }
        renderRuneLink();
        renderCost();
    };

    var checkRune = function (runeId, noRecursion, isSaved) {
        if (runeId == 10000) {
            return;
        }
        var $rune = $("#rune" + runeId);
        if ($rune.data('rune').evo == 3) {
            return;
        }
        if (!noRecursion) {
            var path = Data.getPath(runeList.concat(runeCheckList), runeId);
            console.log("getPath", path);
            if (!path.length) {
                alert("无路径！")
                return;
            }
            _.each(path, function (o, i) {
                checkRune(o, true);
            });
        }
        else {
            if (isSaved) {
                $rune.data('status', 2)
                    .addClass('rune-saved');
            }
            else {
                $rune.data('status', 1)
                    .addClass('rune-checked');
                runeCheckList.push(runeId);
            }
        }
    };
    var uncheckRuneWithConfirm = function (runeId) {
        if (confirm("是否取消选中该符文？")) {
            uncheckRune(runeId);
        }
    };
    var uncheckRune = function (runeId, noRecursion) {
        if (runeId == 10000) {
            return;
        }
        var $rune = $("#rune" + runeId);
        if ($rune.data('rune').evo == 3) {
            return;
        }
        $rune.data('status', 0)
            .removeClass('rune-checked')
            .removeClass('rune-saved');
        runeList = _.without(runeList, runeId);
        runeCheckList = _.without(runeCheckList, runeId);
        if (!noRecursion) {
            var components = Data.getConnectedComponent(runeList.concat(runeCheckList));
            _.each(components, function (o, i) {
                if (_.contains(o, 10000) == false) {
                    _.each(o, function (p, j) {
                        uncheckRune(p, true);
                    });
                }
            });
        }
    };

    var save = function () {
        runeList = _.unique(runeList.concat(runeCheckList));
        runeCheckList = [];
        _.each(runeList, function (o, i) {
            var $rune = $("#rune" + o);
            $rune.data('status', 2)
                .removeClass('rune-checked')
                .addClass('rune-saved');
        });
        renderCost();

        var data = stringifyCondition(runeList);
        Backbone.history.navigate("class/" + classId + "/share/" + data, { trigger: false });
    };
    var load = function (savedata) {
        runeList = parseCondition(savedata);
        _.each(runeList, function (o, i) {
            checkRune(o, true, true);
        });
        renderRuneLink();
        renderCost();
    };

    function stringifyCondition(condition) {
        return LZString.compressToEncodedURIComponent(JSON.stringify(condition));
    }

    function parseCondition(conditionJson) {
        return JSON.parse(LZString.decompressFromEncodedURIComponent(conditionJson));
    }

    return {
        initUiLanguage: initUiLanguage,
        getActiveMenu: getActiveMenu,
        setActiveMenu: setActiveMenu,
        render: render,
    };
});<|endoftext|>


<commit_before>/*
 * xWeb (v1.0) by EvolSoft
 * Developer: EvolSoft
 * Website: http://www.evolsoft.tk
 * Date: 29/03/2015 06:01 PM (UTC)
 * Copyright & License: (C) 2015 EvolSoft
 * Licensed under MIT (https://github.com/EvolSoft/xWeb/blob/master/LICENSE)
 */

//**** xWeb Core ****//

/** @var string XWEB_VERSION **/
var XWEB_VERSION = "1.0";

/**
 * Changes the Webpage title
 *
 * @param title The new title
 */
function changeTitle(title){
	if(checkElement("title")){
		$("title").text(title);
	}else{
		$("head").append("<title>" + title + "</title>");
	}
}

/**
 * Checks if a element exists
 *
 * @param element The element tag, class, name or id to check
 *
 * @return int
 */
function checkElement(element){
	return $(element).length;
}

/**
 * Get xWeb version
 *
 * @return string xWebVersion
 */
function getVersion(){
	return XWEB_VERSION;
}

/**
 * px to int
 *
 * @param px px
 *
 * @return int
 */
function pxtoint(px){
	return px.replace("px", "");
}

//**** Alerts ****//

$(document).on("click", ".close", function() {
	if($(this).parent().hasClass("alert")){
		$(this).parent().trigger("alert.close");
		$(this).parent().remove();
	}
});

$(document).on("click", "[alert-close]", function() {
	if($(this).parent().hasClass("alert")){
		$(this).parent().trigger("alert.close");
		$(this).parent().remove();
	}
});

//**** Menus ****//

$(document).on("mousedown", function() {
	if($(event.target).parent().hasClass("open") && $(event.target).parent().hasClass("menu-group")){
		$(".menu-group").removeClass("open"); //Closes all other menus
	}else if($(event.target).parent().hasClass("menu-group") && $(event.target).attr("openmenu") == ""){
		$(".menu-group").removeClass("open"); //Closes all other menus
		$(event.target).parent().toggleClass("open");
	}else{ //Close all opened menus
		$(".menu-group").removeClass("open"); //Closes all other menus
	}
});

//**** Modals ****//

/**
 * Toggles a modal
 *
 * @param target The target modal
 */
function toggleModal(target) {
	if($(target).hasClass("modal")){
	    $(target).toggleClass("modal-open");
	    if($(target).hasClass("modal-open")){ //Modal opened
	    	$(target).trigger("modal.open");
	    }else{ //Modal closed
	    	$(target).trigger("modal.close");
	    }
	}
}

$(document).on("click", ".close", function() {
	if($(this).parent().parent().hasClass("modal")){ //.modal > .modal-window > .close
		$(this).parent().parent().trigger("modal.close");
		$(this).parent().parent().removeClass("modal-open");
	}
});

$(document).on("click", ".modal-background", function() {
	if($(this).parent().hasClass("modal")){ //.modal > .modal-background
	    if($(this).parent().attr("static") == "false" || typeof $(this).parent().attr("static") === typeof undefined){
			$(this).parent().trigger("modal.close");
	    	$(this).parent().removeClass("modal-open");
		}
	}
});

//**** Navbar ****//

$(document).on("click", ".navbar-toggle", function(){
	if($(this).parent().hasClass("navbar")){ //.navbar > .navbar-toggle
		$(this).parent().find(".navbar-links").toggleClass("open");
	}
});

//**** Sliders ****//

/** @var bool click **/
var click = false;
/** @var current **/
var current = null;
/** @var int pos **/
var pos = 0;

$(document).on("mousedown", function() {
	click = true;
	current = event.target;
});

$(document).on("mouseup", function() {
	click = false;
	current = null;
});

$(document).on("mousemove", function(e) {
	if(click && current != null && $(current).attr("class") == "slider-handle"){
		fixedpos = e.pageX - $(current).parent().offset().left;
		percent = Math.round(((fixedpos * 100) / pxtoint($(current).parent().css("width"))));
		if(e.pageX > pos){ //Check mouse direction
			if(fixedpos >= 0 && fixedpos <= $(current).parent().width()){
				$(current).css("left",  + percent + "%");
				$(current).parent().find(".slider-progress").css("width", percent + 1 + "%");
				$(current).parent().trigger("slider.change");
			}
		}else{
			if(fixedpos >= 0 && fixedpos <= $(current).parent().width()){
				$(current).css("left",  + percent + "%");
				$(current).parent().find(".slider-progress").css("width", percent + 1 + "%");
				$(current).parent().trigger("slider.change");
			}
		}
	}
	pos = e.pageX;
});

/**
 * Get range slider value
 *
 * @param r_slider the range slider
 *
 * @return int|null range slider value in percentage or null if the element isn't a range slider
 */
function getRSliderVal(r_slider){
	if($(r_slider).hasClass("slider")){
		percentage = percent = Math.round(((pxtoint($(r_slider).find(".slider-handle").css("left")) * 100) / pxtoint($(r_slider).css("width"))));
		return percentage;
	}else{
		return null;
	}
}

//**** Tabs ****//

$(document).on("click", "a", function(){
	if($(this).parent().parent().hasClass("tabs")){ //ul.tabs > li > a
		$(this).parent().parent().find("li").removeClass("active"); //ul.tabs > li
		$(this).parent().addClass("active"); //ul.tabs > li
		$(this).parent().parent().parent().find(".tab-content").css("display", "none"); //Closes all tab-contents (div.tabs > ul.tabs > li > a)
		if($(this).parent().parent().parent().find("[tab-id=" + $(event.target).attr("open-tab") + "]").hasClass("tab-content")){
			$(this).parent().parent().parent().find("[tab-id=" + $(event.target).attr("open-tab") + "]").css("display", "block");
		}
	}
});
<commit_msg>Basic Image Sliders implementation<commit_after>/*
 * xWeb (v1.0) by EvolSoft
 * Developer: EvolSoft
 * Website: http://www.evolsoft.tk
 * Date: 07/04/2015 02:00 PM (UTC)
 * Copyright & License: (C) 2015 EvolSoft
 * Licensed under MIT (https://github.com/EvolSoft/xWeb/blob/master/LICENSE)
 */

//**** xWeb Core ****//

/** @var string XWEB_VERSION **/
var XWEB_VERSION = "1.0";

/**
 * Changes the Webpage title
 *
 * @param title The new title
 */
function changeTitle(title){
	if(checkElement("title")){
		$("title").text(title);
	}else{
		$("head").append("<title>" + title + "</title>");
	}
}

/**
 * Checks if a element exists
 *
 * @param element The element tag, class, name or id to check
 *
 * @return int
 */
function checkElement(element){
	return $(element).length;
}

/**
 * Get xWeb version
 *
 * @return string xWebVersion
 */
function getVersion(){
	return XWEB_VERSION;
}

/**
 * px to int
 *
 * @param px px
 *
 * @return int
 */
function pxtoint(px){
	return px.replace("px", "");
}

//**** Alerts ****//

$(document).on("click", ".close", function() {
	if($(this).parent().hasClass("alert")){
		$(this).parent().trigger("alert.close");
		$(this).parent().remove();
	}
});

$(document).on("click", "[alert-close]", function() {
	if($(this).parent().hasClass("alert")){
		$(this).parent().trigger("alert.close");
		$(this).parent().remove();
	}
});

//**** Image Sliders ****//

$(document).on("click", ".image-slider-control-left", function(){
	parent = $(event.target).parent().find(".image-slider-images").children(".image-slider-item");
	activeParent = $(event.target).parent().find(".image-slider-images").children(".image-slider-item.active");
	if(activeParent.prev().length > 0){ //Check if previous element exists
		parent.removeClass("active");
		activeParent.prev().addClass("active");
		activeParent.css("margin-left", "0%");
		activeParent.prev().css("margin-left", "-100%");
		activeParent.animate({"margin-left" : "100%"}, 200);
		activeParent.prev().animate({"margin-left" : "0%"}, 200);
		$(event.target).parent().find(".image-slider-navigation").children("li").removeClass("active");
		$(event.target).parent().find(".image-slider-navigation").find("[img-id='" + activeParent.prev().attr("img-item") + "']").addClass("active");
	}else{
		parent.removeClass("active");
		parent.last().addClass("active");
		activeParent.css("margin-left", "0%");
		parent.last().css("margin-left", "-100%");
		activeParent.animate({"margin-left" : "100%"}, 200);
		parent.last().animate({"margin-left" : "0%"}, 200);
		$(event.target).parent().find(".image-slider-navigation").children("li").removeClass("active");
		$(event.target).parent().find(".image-slider-navigation").find("[img-id='" + parent.last().attr("img-item") + "']").addClass("active");
	}
});

$(document).on("click", ".image-slider-control-right", function(){
	parent = $(event.target).parent().find(".image-slider-images").children(".image-slider-item");
	activeParent = $(event.target).parent().find(".image-slider-images").children(".image-slider-item.active");
	if(activeParent.next().length > 0){ //Check if next element exists
		parent.removeClass("active");
		activeParent.next().addClass("active");
		activeParent.css("margin-left", "0%");
		activeParent.next().css("margin-left", "100%");
		activeParent.animate({"margin-left" : "-100%"}, 200);
		activeParent.next().animate({"margin-left" : "0%"}, 200);
		$(event.target).parent().find(".image-slider-navigation").children("li").removeClass("active");
		$(event.target).parent().find(".image-slider-navigation").find("[img-id='" + activeParent.next().attr("img-item") + "']").addClass("active");
	}else{
		parent.removeClass("active");
		parent.first().addClass("active");
		activeParent.css("margin-left", "0%");
		parent.first().css("margin-left", "100%");
		activeParent.animate({"margin-left" : "-100%"}, 200);
		parent.first().animate({"margin-left" : "0%"}, 200);
		$(event.target).parent().find(".image-slider-navigation").children("li").removeClass("active");
		$(event.target).parent().find(".image-slider-navigation").find("[img-id='" + parent.first().attr("img-item") + "']").addClass("active");
	}
});

//**** Menus ****//

$(document).on("mousedown", function() {
	var target = event.target;
	if($(target).parent().hasClass("open") && $(target).parent().hasClass("menu-group")){
		$(".menu-group").removeClass("open"); //Closes all other menus
		$(".menu-group").each(function(){
			$(this).not($(target).parent()).trigger("menu.close"); //Trigger menu.close event on all closed menus
		});
	}else if($(target).parent().hasClass("menu-group") && $(target).attr("openmenu") == ""){
		$(".menu-group").removeClass("open"); //Closes all other menus
		$(".menu-group").each(function(){
			$(this).not($(target).parent()).trigger("menu.close"); //Trigger menu.close event on all closed menus
		});
		$(target).parent().toggleClass("open");
		$(target).parent().trigger("menu.open");
	}else{ //Close all opened menus
		$(".menu-group").removeClass("open"); //Closes all other menus
		$(".menu-group").each(function(){
			$(this).not($(target).parent()).trigger("menu.close"); //Trigger menu.close event on all closed menus
		});
	}
});

//**** Modals ****//

/**
 * Toggles a modal
 *
 * @param target The target modal
 */
function toggleModal(target) {
	if($(target).hasClass("modal")){
	    $(target).toggleClass("modal-open");
	    if($(target).hasClass("modal-open")){ //Modal opened
	    	$(target).trigger("modal.open");
	    }else{ //Modal closed
	    	$(target).trigger("modal.close");
	    }
	}
}

$(document).on("click", ".close", function() {
	if($(this).parent().parent().hasClass("modal")){ //.modal > .modal-window > .close
		$(this).parent().parent().trigger("modal.close");
		$(this).parent().parent().removeClass("modal-open");
	}
});

$(document).on("click", ".modal-background", function() {
	if($(this).parent().hasClass("modal")){ //.modal > .modal-background
	    if($(this).parent().attr("static") == "false" || typeof $(this).parent().attr("static") === typeof undefined){
			$(this).parent().trigger("modal.close");
	    	$(this).parent().removeClass("modal-open");
		}
	}
});

//**** Navbar ****//

$(document).on("click", ".navbar-toggle", function(){
	if($(this).parent().hasClass("navbar")){ //.navbar > .navbar-toggle
		$(this).parent().find(".navbar-links").toggleClass("open");
	}
});

//**** Sliders ****//

/** @var bool click **/
var click = false;
/** @var current **/
var current = null;
/** @var int pos **/
var pos = 0;

$(document).on("mousedown", function() {
	click = true;
	current = event.target;
});

$(document).on("mouseup", function() {
	click = false;
	current = null;
});

$(document).on("mousemove", function(e) {
	if(click && current != null && $(current).attr("class") == "slider-handle"){
		fixedpos = e.pageX - $(current).parent().offset().left;
		percent = Math.round(((fixedpos * 100) / pxtoint($(current).parent().css("width"))));
		if(e.pageX > pos){ //Check mouse direction
			if(fixedpos >= 0 && fixedpos <= $(current).parent().width()){
				$(current).css("left",  + percent + "%");
				$(current).parent().find(".slider-progress").css("width", percent + 1 + "%");
				$(current).parent().trigger("slider.change");
			}
		}else{
			if(fixedpos >= 0 && fixedpos <= $(current).parent().width()){
				$(current).css("left",  + percent + "%");
				$(current).parent().find(".slider-progress").css("width", percent + 1 + "%");
				$(current).parent().trigger("slider.change");
			}
		}
	}
	pos = e.pageX;
});

/**
 * Get range slider value
 *
 * @param r_slider the range slider
 *
 * @return int|null range slider value in percentage or null if the element isn't a range slider
 */
function getRSliderVal(r_slider){
	if($(r_slider).hasClass("slider")){
		percentage = percent = Math.round(((pxtoint($(r_slider).find(".slider-handle").css("left")) * 100) / pxtoint($(r_slider).css("width"))));
		return percentage;
	}else{
		return null;
	}
}

//**** Tabs ****//

$(document).on("click", "a", function(){
	if($(this).parent().parent().hasClass("tabs")){ //ul.tabs > li > a
		$(this).parent().parent().find("li").removeClass("active"); //ul.tabs > li
		$(this).parent().addClass("active"); //ul.tabs > li
		$(this).parent().parent().parent().find(".tab-content").css("display", "none"); //Closes all tab-contents (div.tabs > ul.tabs > li > a)
		if($(this).parent().parent().parent().find("[tab-id=" + $(event.target).attr("open-tab") + "]").hasClass("tab-content")){
			$(this).parent().parent().parent().find("[tab-id=" + $(event.target).attr("open-tab") + "]").css("display", "block");
		}
	}
});

<|endoftext|>


<commit_before>function updateOnVirtualData(swiper) {
  if (!swiper || swiper.destroyed) return;
  swiper.updateSlides();
  swiper.updateProgress();
  swiper.updateSlidesClasses();
  if (swiper.lazy && swiper.params.lazy.enabled) {
    swiper.lazy.load();
  }
}

function renderVirtual(swiperRef, slides, virtualData) {
  if (!virtualData) return null;
  const style = swiperRef.value.isHorizontal()
    ? {
        [swiperRef.value.rtlTranslate ? 'right' : 'left']: `${virtualData.offset}px`,
      }
    : {
        top: `${virtualData.offset}px`,
      };
  return slides
    .filter((slide, index) => index >= virtualData.from && index <= virtualData.to)
    .map((slide) => {
      if (!slide.props) slide.props = {};
      if (!slide.props.style) slide.props.style = {};
      slide.props.swiperRef = swiperRef;
      slide.props.style = style;
      return slide;
    });
}

export { renderVirtual, updateOnVirtualData };
<commit_msg>Vue: Clone slides<commit_after>import { h } from 'vue';

function updateOnVirtualData(swiper) {
  if (!swiper || swiper.destroyed) return;
  swiper.updateSlides();
  swiper.updateProgress();
  swiper.updateSlidesClasses();
  if (swiper.lazy && swiper.params.lazy.enabled) {
    swiper.lazy.load();
  }
}

function renderVirtual(swiperRef, slides, virtualData) {
  if (!virtualData) return null;
  const style = swiperRef.value.isHorizontal()
    ? {
        [swiperRef.value.rtlTranslate ? 'right' : 'left']: `${virtualData.offset}px`,
      }
    : {
        top: `${virtualData.offset}px`,
      };
  return slides
    .filter((slide, index) => index >= virtualData.from && index <= virtualData.to)
    .map((slide) => {
      if (!slide.props) slide.props = {};
      if (!slide.props.style) slide.props.style = {};
      slide.props.swiperRef = swiperRef;
      slide.props.style = style;
      return h(slide.type, { ...slide.props }, slide.children);
    });
}

export { renderVirtual, updateOnVirtualData };
<|endoftext|>


<commit_before>(function (ReportFilters, Errors, Calendar) {
    var App = {
        cfg: {
            sdate:         '#sdate',
            edate:         '#edate',
            legend:        '#legend',
            welcome:       '#welcome',
            loading:       '#loading',
            errorTarget:   '#error-container',
            errorTemplate: '#error',
            chart:         '#chart',
            filter:        '#initiatives',
            buttons:       '#controls',
            filterOptions: {
                url:                '../../lib/php/reportFilters.php',
                triggerForm:        '#initiatives',
                filterForm:         '#secondary-filters',
                locationsTemplate:  '#locations-template',
                activitiesTemplate: '#activities-template',
                locationsSelect:    '#locations',
                activitiesSelect:   '#activities'
            }
        },
        filters: null,
        init: function () {
            // Insert default dates
            this.insertDefaultDates();

            // Set initiative filter to default (for back button)
            $(this.cfg.filter).val('default');

            // Insert filter select boxes
            this.insertFilters();

            // Bind Events
            this.bindEvents();
        },
        /**
         * Inserts default dates into form
         */
        insertDefaultDates : function () {
            // Create dates for default date display
            var now = moment().format('YYYY-MM-DD'),
                then = moment().subtract('months', 6).format('YYYY-MM-DD');

            // Insert default dates into DOM
            $(this.cfg.sdate).val(then);
            $(this.cfg.edate).val(now);
        },
        /**
         * Initializes and inserts secondary filters
         */
        insertFilters: function () {
            var filters,
                self = this;

            if (this.filters === null) {
                this.filters = new ReportFilters(this.cfg.filterOptions);
            }

            filters = this.filters.init();

            filters.fail(function (e) {
                self.error(e);
            });
        },
        bindEvents: function () {
            var self = this;

            // Initialize datepicker
            $(self.cfg.sdate).datepicker({'format': 'yyyy-mm-dd', 'autoclose': 'true'});
            $(self.cfg.edate).datepicker({'format': 'yyyy-mm-dd', 'autoclose': 'true'});

            // Get chart data on submit
            $('body').on('submit', 'form', function (e) {
                var input = $(this).serializeArray();

                $.when(self.getData(input))
                    .then(self.processData.bind(self))
                    .then(self.drawChart.bind(self), self.error.bind(self));

                e.preventDefault();
            });

            // Toggle between sum and avg
            $('#avg-sum').on('click', function (e) {
                var state = e.target.value;

                self.drawChart(self.data, state);
            });

            // Initialize help popovers
            $('.suma-popover').popover({placement: 'bottom'});

            // Chart download
            $('#calendar-download').on('click', function () {
                var linkId = "#" + this.id,
                    chartId = "#" + $(this).attr('data-chart-div');

                self.downloadPNG(linkId, chartId);
            });
        },
        downloadPNG: function (linkId, chartId) {
            var canvas,
                img,
                svg;

            // Get svg markup from chart
            svg = $.trim($(chartId).html());

            // Insert invisible canvas
            $('body').append('<canvas id="canvas" style="display:none"></canvas>');

            // Insert chart into invisible canvas
            canvg(document.getElementById('canvas'), svg);

            // Retrieve contents of invisible canvas
            canvas = document.getElementById('canvas');

            // Convert canvas to data
            img = canvas.toDataURL("image/png");

            // Update href to use data:image
            $(linkId).attr('href', img);

            // Remove Canvas
            $('#canvas').remove();
        },
        getData: function (input) {
            var self = this;

            return $.ajax({
                url: 'results.php',
                data: input,
                beforeSend: function () {
                    var text = $('#submit').data('loading-text');
                    $('#submit').addClass('disabled').val(text);
                    $('#submit').attr('disabled', 'true');
                    $(self.cfg.loading).show();
                    $(self.cfg.buttons).hide();
                    $(self.cfg.legend).hide();
                    $(self.cfg.welcome).hide();
                    $(self.cfg.errorTarget).empty();
                    $('svg').remove();
                },
                success: function () {
                    $(self.cfg.buttons).show();
                    $(self.cfg.legend).show();
                },
                complete: function () {
                    var text = $('#submit').data('default-text');
                    $('#submit').removeClass('disabled').val(text);
                    $('#submit').removeAttr('disabled');
                    $(self.cfg.loading).hide();
                },
                timeout: 180000 // 3 mins
            });
        },
        error: function (e) {
            $(this.cfg.buttons).hide();
            $(this.cfg.legend).hide();
            $(this.cfg.welcome).hide();

            // Log errors for debugging
            console.log('error object', e);

            this.buildTemplate([{msg: Errors.getMsg(e.statusText)}], this.cfg.errorTemplate, this.cfg.errorTarget);
        },
        sortData: function (response) {
            return _.sortBy(
                _.map(response, function (count, date) {
                    return {
                        date: date,
                        count: count.count
                    };
                }),
                function (obj) {
                    return obj.date;
                }
            );
        },
        processData: function (response) {
            var dfd = $.Deferred(),
                data = {};

            // Does response have enough values to draw meaningful graph?
            if (Object.keys(response.periodSum).length < 1) {
                dfd.reject({statusText: 'no data'});
            }

            data.sum = this.sortData(response.periodSum);

            data.avg = this.sortData(response.periodAvg);

            this.data = data;

            dfd.resolve(data);

            return dfd.promise();
        },
        getState: function () {
            return $('#avg-sum > .active')[0].value;
        },
        drawChart: function (counts, state) {
            var data;

            if (state) {
                data = counts[state];
            } else {
                state = this.getState();
                data = counts[state];
            }

            if (!this.calendar) {
                this.calendar = Calendar();
            }

            d3.select(this.cfg.chart)
                .datum(data)
                .call(this.calendar);
        },
        buildTemplate: function (items, templateId, targetId, empty) {
            var html,
                json,
                template;

            // Insert list into object for template iteration
            json = {items: items};

            // Retrieve template from index.php (in script tag)
            html = $(templateId).html();

            // Compile template
            template = Handlebars.compile(html);

            // Populate template with data and insert into DOM
            if (empty) {
                $(targetId).empty();
            }

            $(targetId).prepend(template(json));
        }
    };

    // Start app on document ready
    $(document).ready(function () {
        App.init();
    });
}(ReportFilters, Errors, Calendar));
<commit_msg>clean up config<commit_after>(function (ReportFilters, Errors, Calendar) {
    var App = {
        cfg: {
            sdate:         '#sdate',
            edate:         '#edate',
            legend:        '#legend',
            welcome:       '#welcome',
            loading:       '#loading',
            errorTarget:   '#error-container',
            errorTemplate: '#error',
            chart:         '#chart',
            filter:        '#initiatives',
            buttons:       '#controls',
            submit:        '#submit',
            avgSum:        '#avg-sum',
            state:         '#avg-sum > .active',
            popover:       '.suma-popover',
            calendarDownload: '#calendar-download',
            filterOptions: {
                url:                '../../lib/php/reportFilters.php',
                triggerForm:        '#initiatives',
                filterForm:         '#secondary-filters',
                locationsTemplate:  '#locations-template',
                activitiesTemplate: '#activities-template',
                locationsSelect:    '#locations',
                activitiesSelect:   '#activities'
            }
        },
        filters: null,
        init: function () {
            // Insert default dates
            this.insertDefaultDates();

            // Set initiative filter to default (for back button)
            $(this.cfg.filter).val('default');

            // Insert filter select boxes
            this.insertFilters();

            // Bind Events
            this.bindEvents();
        },
        /**
         * Inserts default dates into form
         */
        insertDefaultDates : function () {
            // Create dates for default date display
            var now = moment().format('YYYY-MM-DD'),
                then = moment().subtract('months', 6).format('YYYY-MM-DD');

            // Insert default dates into DOM
            $(this.cfg.sdate).val(then);
            $(this.cfg.edate).val(now);
        },
        /**
         * Initializes and inserts secondary filters
         */
        insertFilters: function () {
            var filters,
                self = this;

            if (this.filters === null) {
                this.filters = new ReportFilters(this.cfg.filterOptions);
            }

            filters = this.filters.init();

            filters.fail(function (e) {
                self.error(e);
            });
        },
        bindEvents: function () {
            var self = this;

            // Initialize datepicker
            $(self.cfg.sdate).datepicker({'format': 'yyyy-mm-dd', 'autoclose': 'true'});
            $(self.cfg.edate).datepicker({'format': 'yyyy-mm-dd', 'autoclose': 'true'});

            // Get chart data on submit
            $('body').on('submit', 'form', function (e) {
                var input = $(this).serializeArray();

                $.when(self.getData(input))
                    .then(self.processData.bind(self))
                    .then(self.drawChart.bind(self), self.error.bind(self));

                e.preventDefault();
            });

            // Toggle between sum and avg
            $(self.cfg.avgSum).on('click', function (e) {
                var state = e.target.value;

                self.drawChart(self.data, state);
            });

            // Initialize help popovers
            $(self.cfg.popover).popover({placement: 'bottom'});

            // Chart download
            $(self.cfg.calendarDownload).on('click', function () {
                var linkId = "#" + this.id,
                    chartId = "#" + $(this).attr('data-chart-div');

                self.downloadPNG(linkId, chartId);
            });
        },
        downloadPNG: function (linkId, chartId) {
            var canvas,
                img,
                svg;

            // Get svg markup from chart
            svg = $.trim($(chartId).html());

            // Insert invisible canvas
            $('body').append('<canvas id="canvas" style="display:none"></canvas>');

            // Insert chart into invisible canvas
            canvg(document.getElementById('canvas'), svg);

            // Retrieve contents of invisible canvas
            canvas = document.getElementById('canvas');

            // Convert canvas to data
            img = canvas.toDataURL("image/png");

            // Update href to use data:image
            $(linkId).attr('href', img);

            // Remove Canvas
            $('#canvas').remove();
        },
        toggleSubmit: function (loading) {
            var loadingText = $(this.cfg.submit).data('loading-text'),
                defaultText = $(this.cfg.submit).data('default-text');

            if (loading) {
                $(this.cfg.submit).addClass('disabled').val(loadingText);
                $(this.cfg.submit).attr('disabled', 'true');
            } else {
                $(this.cfg.submit).removeClass('disabled').val(defaultText);
                $(this.cfg.submit).removeAttr('disabled');
            }
        },
        getData: function (input) {
            var self = this;

            return $.ajax({
                url: 'results.php',
                data: input,
                beforeSend: function () {
                    self.toggleSubmit(true);
                    $(self.cfg.loading).show();
                    $(self.cfg.buttons).hide();
                    $(self.cfg.legend).hide();
                    $(self.cfg.welcome).hide();
                    $(self.cfg.errorTarget).empty();
                    $('svg').remove();
                },
                success: function () {
                    $(self.cfg.buttons).show();
                    $(self.cfg.legend).show();
                },
                complete: function () {
                    self.toggleSubmit();
                    $(self.cfg.loading).hide();
                },
                timeout: 180000 // 3 mins
            });
        },
        error: function (e) {
            $(this.cfg.buttons).hide();
            $(this.cfg.legend).hide();
            $(this.cfg.welcome).hide();

            // Log errors for debugging
            console.log('error object', e);

            this.buildTemplate([{msg: Errors.getMsg(e.statusText)}], this.cfg.errorTemplate, this.cfg.errorTarget);
        },
        sortData: function (response) {
            return _.sortBy(
                _.map(response, function (count, date) {
                    return {
                        date: date,
                        count: count.count
                    };
                }),
                function (obj) {
                    return obj.date;
                }
            );
        },
        processData: function (response) {
            var dfd = $.Deferred(),
                data = {};

            // Does response have enough values to draw meaningful graph?
            if (Object.keys(response.periodSum).length < 1) {
                dfd.reject({statusText: 'no data'});
            }

            data.sum = this.sortData(response.periodSum);

            data.avg = this.sortData(response.periodAvg);

            this.data = data;

            dfd.resolve(data);

            return dfd.promise();
        },
        getState: function () {
            return $(this.cfg.state)[0].value;
        },
        drawChart: function (counts, state) {
            var data;

            if (state) {
                data = counts[state];
            } else {
                state = this.getState();
                data = counts[state];
            }

            if (!this.calendar) {
                this.calendar = Calendar();
            }

            d3.select(this.cfg.chart)
                .datum(data)
                .call(this.calendar);
        },
        buildTemplate: function (items, templateId, targetId, empty) {
            var html,
                json,
                template;

            // Insert list into object for template iteration
            json = {items: items};

            // Retrieve template from index.php (in script tag)
            html = $(templateId).html();

            // Compile template
            template = Handlebars.compile(html);

            // Populate template with data and insert into DOM
            if (empty) {
                $(targetId).empty();
            }

            $(targetId).prepend(template(json));
        }
    };

    // Start app on document ready
    $(document).ready(function () {
        App.init();
    });
}(ReportFilters, Errors, Calendar));
<|endoftext|>


<commit_before>/*
* This module provides an API to control Keynote presentations.
*
* Author: Humberto Rodriguez Avila
*
*/
var osascript = require('applescript');

/*  the keynote API constructor  */
var Keynote = function () {};

Keynote.prototype.startOrNext = function () {
   osascript.execFile('./scripts/startOrNext.scpt', function(err, result){
    if (err) return console.error(err);});
};

Keynote.prototype.prev = function () {
    osascript.execFile('./scripts/prev.scpt', function(err, result){
    if (err) return console.error(err);});
};

/*  export the API  */
module.exports = Keynote;

<commit_msg>Update naming style<commit_after>/*
* This module provides an API to control Keynote presentations.
*
* Author: Humberto Rodriguez Avila
*
*/
var Osascript = require('applescript');

/*  the keynote API constructor  */
var Keynote = function () {};

/*  starts the presentation or shows the next slide  */
Keynote.prototype.startOrNext = function () {
   Osascript.execFile('./scripts/startOrNext.scpt', function(err, result){
    if (err) return console.error(err);});
};

/*  shows the previous slide  */
Keynote.prototype.prev = function () {
    Osascript.execFile('./scripts/prev.scpt', function(err, result){
    if (err) return console.error(err);});
};

/*  export the API  */
module.exports = Keynote;

<|endoftext|>