<commit_before>const {classes: Cc, interfaces: Ci, utils: Cu} = Components;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/AddonManager.jsm");

var self = this, icon;

function include(addon, path) {
  Services.scriptloader.loadSubScript(addon.getResourceURI(path).spec, self);
}

function $(node, childId) {
  if (node.getElementById) {
    return node.getElementById(childId);
  } else {
    return node.querySelector("#" + childId);
  }
}

function loadIntoWindow(window) {
  if (!window) return;

  let doc = window.document;
  let toolbox = $(doc, "navigator-toolbox");

  if (toolbox) { // navigator window
    // add to palette
    let button = doc.createElement("toolbarbutton");
    button.setAttribute("id", BUTTON_ID);
    button.setAttribute("label", "Replace Bookmark");
    button.setAttribute("class", "toolbarbutton-1 chromeclass-toolbar-additional");
    button.setAttribute("tooltiptext", "Replace an existing bookmark");
    button.style.listStyleImage = "url(" + icon + ")";
    button.addEventListener("command", main.action, false);
    toolbox.palette.appendChild(button);

    // move to saved toolbar position
    let {toolbarId, nextItemId} = main.getPrefs(),
        toolbar = toolbarId && $(doc, toolbarId);
    if (toolbar) {
      let nextItem = $(doc, nextItemId);
      toolbar.insertItem(BUTTON_ID, nextItem &&
                         nextItem.parentNode.id == toolbarId &&
                         nextItem);
    }
    window.addEventListener("aftercustomization", afterCustomize, false);

    // add hotkey
    let keyset = doc.createElement("keyset");
    keyset.setAttribute("id", KEYSET_ID);
    let replaceKey = doc.createElement("key");
    replaceKey.setAttribute("key", "D");
    replaceKey.setAttribute("modifiers", "accel,alt");
    replaceKey.setAttribute("oncommand", "void(0);");
    replaceKey.addEventListener("command", main.action, true);
    keyset.appendChild(replaceKey);
    doc.querySelector("window").appendChild(keyset);
  }
}

function afterCustomize(e) {
  let toolbox = e.target;
  let button = $(toolbox.parentNode, BUTTON_ID);
  let toolbarId, nextItemId;
  if (button) {
    let parent = button.parentNode,
        nextItem = button.nextSibling;
    if (parent && parent.localName == "toolbar") {
      toolbarId = parent.id;
      nextItemId = nextItem && nextItem.id;
    }
  }
  main.setPrefs(toolbarId, nextItemId);
}

function unloadFromWindow(window) {
  if (!window) return;

  let doc = window.document;
  let button = $(doc, BUTTON_ID) ||
    $($(doc, "navigator-toolbox").palette, BUTTON_ID);
  button && button.parentNode.removeChild(button);
  let keyset = $(doc, KEYSET_ID);
  keyset.parentNode.removeChild(keyset);

  window.removeEventListener("aftercustomization", afterCustomize, false);
}

function eachWindow(callback) {
  let enumerator = Services.wm.getEnumerator("navigator:browser");
  while (enumerator.hasMoreElements()) {
    let win = enumerator.getNext();
    if (win.document.readyState === "complete") {
      callback(win);
    } else {
      runOnLoad(win, callback);
    }
  }
}

function runOnLoad(window, callback) {
  window.addEventListener("load", function() {
    window.removeEventListener("load", arguments.callee, false);
    callback(window);
  }, false);
}

function windowWatcher(subject, topic) {
  if (topic === "domwindowopened") {
    runOnLoad(subject, loadIntoWindow);
  }
}

function startup(data, reason) AddonManager.getAddonByID(data.id, function(addon) {
  include(addon, "content/main.js");
  include(addon, "content/bookmarks.js");
  icon = addon.getResourceURI("content/icon.png").spec;

  // existing windows
  eachWindow(loadIntoWindow);

  // new windows
  Services.ww.registerNotification(windowWatcher);
});

function shutdown(data, reason) {
  Services.ww.unregisterNotification(windowWatcher);
  eachWindow(unloadFromWindow);
}
<commit_msg>Close #1 with a workaround<commit_after>const {classes: Cc, interfaces: Ci, utils: Cu} = Components;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/AddonManager.jsm");

var self = this, icon;

function include(addon, path) {
  Services.scriptloader.loadSubScript(addon.getResourceURI(path).spec, self);
}

function $(node, childId) {
  if (node.getElementById) {
    return node.getElementById(childId);
  } else {
    return node.querySelector("#" + childId);
  }
}

function loadIntoWindow(window) {
  if (!window) return;

  let doc = window.document;
  let toolbox = $(doc, "navigator-toolbox");

  if (toolbox) { // navigator window
    // add to palette
    let button = doc.createElement("toolbarbutton");
    button.setAttribute("id", BUTTON_ID);
    button.setAttribute("label", "Replace Bookmark");
    button.setAttribute("class", "toolbarbutton-1 chromeclass-toolbar-additional");
    button.setAttribute("tooltiptext", "Replace an existing bookmark");
    button.style.listStyleImage = "url(" + icon + ")";
    button.addEventListener("command", main.action, false);
    toolbox.palette.appendChild(button);

    // move to saved toolbar position
    let {toolbarId, nextItemId} = main.getPrefs(),
        toolbar = toolbarId && $(doc, toolbarId);
    if (toolbar) {
      let nextItem = $(doc, nextItemId);
      toolbar.insertItem(BUTTON_ID, nextItem &&
                         nextItem.parentNode.id == toolbarId &&
                         nextItem);
    }
    window.addEventListener("aftercustomization", afterCustomize, false);

    // add hotkey
    let keyset = doc.createElement("keyset");
    keyset.setAttribute("id", KEYSET_ID);
    let replaceKey = doc.createElement("key");
    replaceKey.setAttribute("key", "D");
    replaceKey.setAttribute("modifiers", "accel,alt");
    replaceKey.setAttribute("oncommand", "void(0);");
    replaceKey.addEventListener("command", main.action, true);
    keyset.appendChild(replaceKey);
    doc.querySelector("window").appendChild(keyset);
  }
}

function afterCustomize(e) {
  let toolbox = e.target;
  let button = $(toolbox.parentNode, BUTTON_ID);
  let toolbarId, nextItemId;
  if (button) {
    let parent = button.parentNode,
        nextItem = button.nextSibling;
    if (parent && parent.localName == "toolbar") {
      toolbarId = parent.id;
      nextItemId = nextItem && nextItem.id;
    }
  }
  main.setPrefs(toolbarId, nextItemId);
}

function unloadFromWindow(window) {
  if (!window) return;

  let doc = window.document;
  let button = $(doc, BUTTON_ID) ||
    $($(doc, "navigator-toolbox").palette, BUTTON_ID);
  button && button.parentNode.removeChild(button);
  let keyset = $(doc, KEYSET_ID);
  keyset.parentNode.removeChild(keyset);

  window.removeEventListener("aftercustomization", afterCustomize, false);
}

function eachWindow(callback) {
  let enumerator = Services.wm.getEnumerator("navigator:browser");
  while (enumerator.hasMoreElements()) {
    let win = enumerator.getNext();
    if (win.document.readyState === "complete") {
      callback(win);
    } else {
      runOnLoad(win, callback);
    }
  }
}

function runOnLoad(window, callback) {
  window.addEventListener("load", function() {
    window.removeEventListener("load", arguments.callee, false);
    callback(window);
  }, false);
}

function windowWatcher(subject, topic) {
  if (topic === "domwindowopened") {
    runOnLoad(subject, loadIntoWindow);
  }
}

function startup(data, reason) AddonManager.getAddonByID(data.id, function(addon) {
  include(addon, "content/main.js");
  include(addon, "content/bookmarks.js");
  icon = addon.getResourceURI("content/icon.png").spec;

  // workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=632898
  let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  timer.initWithCallback({notify: function() {
    // new windows
    Services.ww.registerNotification(windowWatcher);

    // existing windows
    eachWindow(loadIntoWindow);
  }}, 0, Ci.nsITimer.TYPE_ONE_SHOT);
});

function shutdown(data, reason) {
  Services.ww.unregisterNotification(windowWatcher);
  eachWindow(unloadFromWindow);
}
<|endoftext|>


<commit_before>function Loader(){
  this.slides = $(".slides");
  var that = this;

  this.loadFile = function (fileName, onload){
    return $.get(fileName + '.html').success(function(data){
      that.slides.append(data);
      if(onload != undefined){ onload(); }
    });
  }

  that.loadFile('slides_0_3');
  /*
  that.loadFile('slides_0_3', function(){
    that.loadFile('slides_4_7', function(){
      that.loadFile('slides_8_11', function(){
        that.loadFile('slides_12_15', function(){
          Reveal.initialize({
            width: 1276,
            height: 638,
            controls: false,
            progress: false,
            history: false,
            center: true,
            keyboard: true,
            overview: false,

            theme: Reveal.getQueryHash().theme,
            transition: Reveal.getQueryHash().transition || 'default',

            dependencies: [
              { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
              { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
              { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
              { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
              { src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
              { src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
            ]
          });
        });
      });
    });
  });
  */
}

var loader = window.loader = new Loader();
<commit_msg>testing iponey<commit_after>function Loader(){
  this.slides = $(".slides");
  var that = this;

  this.loadFile = function (fileName, onload){
    return $.get(fileName + '.html').success(function(data){
      that.slides.append(data);
      if(onload != undefined){ onload(); }
    });
  }

  that.loadFile('slides_0_3', function(){
    Reveal.initialize({
      width: 1276,
      height: 638,
      controls: false,
      progress: false,
      history: false,
      center: true,
      keyboard: true,
      overview: false,

      theme: Reveal.getQueryHash().theme,
      transition: Reveal.getQueryHash().transition || 'default',

      dependencies: [
        { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
        { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
        { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
        { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
        { src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
        { src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
      ]
    });
  });
  /*
  that.loadFile('slides_0_3', function(){
    that.loadFile('slides_4_7', function(){
      that.loadFile('slides_8_11', function(){
        that.loadFile('slides_12_15', function(){
          Reveal.initialize({
            width: 1276,
            height: 638,
            controls: false,
            progress: false,
            history: false,
            center: true,
            keyboard: true,
            overview: false,

            theme: Reveal.getQueryHash().theme,
            transition: Reveal.getQueryHash().transition || 'default',

            dependencies: [
              { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
              { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
              { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
              { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
              { src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
              { src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
            ]
          });
        });
      });
    });
  });
  */
}

var loader = window.loader = new Loader();
<|endoftext|>


<commit_before>var _concat = require('./_concat');
var _curry2 = require('./_curry2');
var _slice = require('./_slice');
var _xfBase = require('./_xfBase');

module.exports = (function() {
  function XAperture(n, xf) {
    this.xf = xf;
    this.pos = 0;
    this.full = false;
    this.acc = new Array(n);
  }
  XAperture.prototype['@@transducer/init'] = _xfBase.init;
  XAperture.prototype['@@transducer/result'] = _xfBase.result;
  XAperture.prototype['@@transducer/step'] = function(result, input) {
    this.store(input);
    return this.full ? this.xf['@@transducer/step'](result, this.getCopy()) : result;
  };
  XAperture.prototype.store = function(input) {
    this.acc[this.pos] = input;
    this.pos += 1;
    if (this.pos === this.acc.length) {
      this.pos = 0;
      this.full = true;
    }
  };
  XAperture.prototype.getCopy = function() {
    return _concat(_slice(this.acc, this.pos), _slice(this.acc, 0, this.pos));
  };

  return _curry2(function _xaperture(n, xf) { return new XAperture(n, xf); });
})();
<commit_msg>fix(aperture): free references to inputs when processing result in transducer<commit_after>var _concat = require('./_concat');
var _curry2 = require('./_curry2');
var _slice = require('./_slice');
var _xfBase = require('./_xfBase');

module.exports = (function() {
  function XAperture(n, xf) {
    this.xf = xf;
    this.pos = 0;
    this.full = false;
    this.acc = new Array(n);
  }
  XAperture.prototype['@@transducer/init'] = _xfBase.init;
  XAperture.prototype['@@transducer/result'] = function(result) {
    this.acc = null;
    return this.xf['@@transducer/result'](result);
  };
  XAperture.prototype['@@transducer/step'] = function(result, input) {
    this.store(input);
    return this.full ? this.xf['@@transducer/step'](result, this.getCopy()) : result;
  };
  XAperture.prototype.store = function(input) {
    this.acc[this.pos] = input;
    this.pos += 1;
    if (this.pos === this.acc.length) {
      this.pos = 0;
      this.full = true;
    }
  };
  XAperture.prototype.getCopy = function() {
    return _concat(_slice(this.acc, this.pos), _slice(this.acc, 0, this.pos));
  };

  return _curry2(function _xaperture(n, xf) { return new XAperture(n, xf); });
})();
<|endoftext|>


<commit_before>module.exports = create;

create.usage = "\trappidjs create lib <libName> [<dir>] - Creates a rappidjs lib directory structure"
    + "\n\trappidjs create app <AppName> [<dir>] - Creates empty rappidjs application";

var fs = require("fs"),
    path = require("path"),
    flow = require("flow.js").flow,
    ejs = require('ejs'),
    args = process.argv.splice(2),
    rl = require("readline"),
    install = require(path.join(__dirname, "install.js"));

var Helper = {
    template:function (source, destination, options) {
        var data = fs.readFileSync(source, "utf8");
        fs.writeFileSync(destination, this.render(data, options));

    },
    render:function (string, options) {
        if (options == null) options = {};
        return ejs.render(string, options);
    },
    copy:function (source, destination) {
        var data = fs.readFileSync(source, "utf8");
        fs.writeFileSync(destination, data);
    }
};

fs.mkdirIfNotExist = function (dirPath) {
    if (!path.existsSync(dirPath)) {
        fs.mkdirSync(dirPath);
    }
};

fs.mkdirParent = function (dirPath) {
    if (!path.existsSync(dirPath)) {
        var parentDir = path.normalize(path.join(dirPath, ".."));
        if (!path.existsSync(parentDir)) {
            fs.mkdirParent(parentDir);
        }

        fs.mkdirSync(dirPath);
    }
};

function createDirectories(directories, where){
    for (var i = 0; i < directories.length; i++) {
        fs.mkdirIfNotExist(path.join(where, directories[i]));
    }
}

function create(args, callback){
    if(args.length === 0){
        callback("No args defined");
    }
    var cmd = args.shift();

    var dir = process.cwd();
    var name = args.shift();
    if(args.length > 0){
        dir = args.shift();
    }

    dir = path.resolve(dir.replace(/^~\//, process.env.HOME + '/'));

    if(cmd == "lib" || cmd == "library"){
        createLibrary(name,dir,callback);
    }else if(cmd == "app" || cmd == "application"){
        createApplication(name,dir,callback);
    }else{
        callback(true);
    }
}

function createLibrary(libName, dir, callback) {
    dir = dir || process.cwd();

    fs.mkdirParent(dir);

    // create directories
    var dirs = ["bin", "doc", "test", libName, "xsd"];
    createDirectories(dirs,dir);

    Helper.template(path.join(__dirname, "templates", "package.json"), path.join(dir, libName, "package.json"), {name:libName, type:"lib"});
}

function createApplication(appName, dir, callback) {

    dir = dir || process.cwd();

    fs.mkdirParent(dir);

    if (!path.existsSync(dir)) {
        callback("Directory " + dir + " could not be created");
    }

    if (appName) {
        // create sub directories
        var subDirs = ["bin", "doc", "test", "public", "xsd"];

        // create sub directories
        createDirectories(subDirs,dir);

        // make first character of appName UPPERCASE
        appName = appName.charAt(0).toUpperCase() + appName.substr(1);

        var publicDir = path.join(dir, "public");

        // create app directory in public
        var appDir = path.join(publicDir, "app");

        fs.mkdirIfNotExist(appDir);

        createDirectories(["collection", "model", "view", "locale", "modules"],appDir);
        // do the templating stuff

        // scaffold index.html
        Helper.template(path.join(__dirname, "templates", "index.html"), path.join(publicDir, "index.html"), {appName:appName});

        // scaffold app/<AppName>.xml
        Helper.template(path.join(__dirname, "templates", "app", "App.xml"), path.join(publicDir, "app", appName + ".xml"), {appName:appName});
        // scaffold app/<AppName>Class.xml
        Helper.template(path.join(__dirname, "templates", "app", "AppClass.js"), path.join(publicDir, "app", appName + "Class.js"), {appName:appName});

        Helper.template(path.join(__dirname, "templates", "package.json"), path.join(dir, "package.json"), {name:appName, type: "app"});

        // TODO: add interactive mode
        install(["rAppid.js", "latest", dir], function (err) {
            if (!err) {

                // scaffold default app directory structure
                console.log("");
                console.log("Application '" + appName + "' in directory '" + publicDir + "' successfully created.");
                console.log("");
            } else {
                callback(err);
            }
        });
    }
}<commit_msg>fixed directory name in create script<commit_after>module.exports = create;

create.usage = "\trappidjs create lib <libName> [<dir>] - Creates a rappidjs lib directory structure"
    + "\n\trappidjs create app <AppName> [<dir>] - Creates empty rappidjs application";

var fs = require("fs"),
    path = require("path"),
    flow = require("flow.js").flow,
    ejs = require('ejs'),
    args = process.argv.splice(2),
    rl = require("readline"),
    install = require(path.join(__dirname, "install.js"));

var Helper = {
    template:function (source, destination, options) {
        var data = fs.readFileSync(source, "utf8");
        fs.writeFileSync(destination, this.render(data, options));

    },
    render:function (string, options) {
        if (options == null) options = {};
        return ejs.render(string, options);
    },
    copy:function (source, destination) {
        var data = fs.readFileSync(source, "utf8");
        fs.writeFileSync(destination, data);
    }
};

fs.mkdirIfNotExist = function (dirPath) {
    if (!path.existsSync(dirPath)) {
        fs.mkdirSync(dirPath);
    }
};

fs.mkdirParent = function (dirPath) {
    if (!path.existsSync(dirPath)) {
        var parentDir = path.normalize(path.join(dirPath, ".."));
        if (!path.existsSync(parentDir)) {
            fs.mkdirParent(parentDir);
        }

        fs.mkdirSync(dirPath);
    }
};

function createDirectories(directories, where){
    for (var i = 0; i < directories.length; i++) {
        fs.mkdirIfNotExist(path.join(where, directories[i]));
    }
}

function create(args, callback){
    if(args.length === 0){
        callback("No args defined");
    }
    var cmd = args.shift();

    var dir = process.cwd();
    var name = args.shift();
    if(args.length > 0){
        dir = args.shift();
    }

    dir = path.resolve(dir.replace(/^~\//, process.env.HOME + '/'));

    if(cmd == "lib" || cmd == "library"){
        createLibrary(name,dir,callback);
    }else if(cmd == "app" || cmd == "application"){
        createApplication(name,dir,callback);
    }else{
        callback(true);
    }
}

function createLibrary(libName, dir, callback) {
    dir = dir || process.cwd();

    fs.mkdirParent(dir);

    // create directories
    var dirs = ["bin", "doc", "test", libName, "xsd"];
    createDirectories(dirs,dir);

    Helper.template(path.join(__dirname, "templates", "package.json"), path.join(dir, libName, "package.json"), {name:libName, type:"lib"});
}

function createApplication(appName, dir, callback) {

    dir = dir || process.cwd();

    fs.mkdirParent(dir);

    if (!path.existsSync(dir)) {
        callback("Directory " + dir + " could not be created");
    }

    if (appName) {
        // create sub directories
        var subDirs = ["bin", "doc", "test", "public", "xsd"];

        // create sub directories
        createDirectories(subDirs,dir);

        // make first character of appName UPPERCASE
        appName = appName.charAt(0).toUpperCase() + appName.substr(1);

        var publicDir = path.join(dir, "public");

        // create app directory in public
        var appDir = path.join(publicDir, "app");

        fs.mkdirIfNotExist(appDir);

        createDirectories(["collection", "model", "view", "locale", "module"],appDir);
        // do the templating stuff

        // scaffold index.html
        Helper.template(path.join(__dirname, "templates", "index.html"), path.join(publicDir, "index.html"), {appName:appName});

        // scaffold app/<AppName>.xml
        Helper.template(path.join(__dirname, "templates", "app", "App.xml"), path.join(publicDir, "app", appName + ".xml"), {appName:appName});
        // scaffold app/<AppName>Class.xml
        Helper.template(path.join(__dirname, "templates", "app", "AppClass.js"), path.join(publicDir, "app", appName + "Class.js"), {appName:appName});

        Helper.template(path.join(__dirname, "templates", "package.json"), path.join(dir, "package.json"), {name:appName, type: "app"});

        // TODO: add interactive mode
        install(["rAppid.js", "latest", dir], function (err) {
            if (!err) {

                // scaffold default app directory structure
                console.log("");
                console.log("Application '" + appName + "' in directory '" + publicDir + "' successfully created.");
                console.log("");
            } else {
                callback(err);
            }
        });
    }
}<|endoftext|>


<commit_before>/**
 * @license
 * js-interview-questions <http://github.com/Tyriar/js-interview-questions>
 * Copyright 2015 Daniel Imms <http://www.growingwiththeweb.com>
 * Released under the MIT license <http://github.com/Tyriar/js-interview-questions/blob/master/LICENSE>
 */
'use strict';

/**
 * Determines whether a string is a palindrome.
 * @param {string} text The string to check.
 * @returns {boolean} Whether the string is a palindrome.
 */
function isTextPalindrome(text) {
  if (text == null) {
    return false;
  }
  var left = 0;
  var right = text.length - 1;
  while (left < right) {
    if (text[left++] != text[right--]) {
      return false;
    }
  }
  return true;
}

/**
 * Determines whether a phrase is a palindrome.
 * @param {string} text The phrase to check.
 * @returns {boolean} Whether the phrase is a palindrome.
 */
function isPhrasePalindrome(text) {
  var chars = text.replace(/[^a-zA-Z]/g, '').toLowerCase();
  console.log(chars);
  return isTextPalindrome(chars);
}

module.exports = {
  isTextPalindrome: isTextPalindrome,
  isPhrasePalindrome: isPhrasePalindrome
};
<commit_msg>Fix eslint<commit_after>/**
 * @license
 * js-interview-questions <http://github.com/Tyriar/js-interview-questions>
 * Copyright 2015 Daniel Imms <http://www.growingwiththeweb.com>
 * Released under the MIT license <http://github.com/Tyriar/js-interview-questions/blob/master/LICENSE>
 */
'use strict';

/**
 * Determines whether a string is a palindrome.
 * @param {string} text The string to check.
 * @returns {boolean} Whether the string is a palindrome.
 */
function isTextPalindrome(text) {
  if (text === undefined) {
    return false;
  }
  var left = 0;
  var right = text.length - 1;
  while (left < right) {
    if (text[left++] !== text[right--]) {
      return false;
    }
  }
  return true;
}

/**
 * Determines whether a phrase is a palindrome.
 * @param {string} text The phrase to check.
 * @returns {boolean} Whether the phrase is a palindrome.
 */
function isPhrasePalindrome(text) {
  var chars = text.replace(/[^a-zA-Z]/g, '').toLowerCase();
  console.log(chars);
  return isTextPalindrome(chars);
}

module.exports = {
  isTextPalindrome: isTextPalindrome,
  isPhrasePalindrome: isPhrasePalindrome
};
<|endoftext|>


<commit_before>"use strict";
console.log("Loading content script...");

var s = document.createElement('script');
s.src = chrome.extension.getURL('js/override.js');
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);

var gzipHeader = [0x1F, 0x8B];

function download(url) {
	console.time("Download");
	var xhr = new XMLHttpRequest();
	xhr.responseType = "arraybuffer";
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			console.timeEnd("Download");
			if (xhr.status !== 200) {
				return failed('Got wrong response ' + xhr.status);
			}
			var contentType = xhr.getResponseHeader('content-type');
			decrypt(xhr.response, contentType);
		}
	};
	xhr.open("GET", url, true);
	xhr.send();
}

function decrypt(data, contentType) {
	console.time("Decrypt");
	chrome.runtime.sendMessage({
		to:"background",
		message: "decrypt",
		data: forge.util.binary.base64.encode(new Uint8Array(data))
	}, function(response) {
		console.timeEnd("Decrypt");
		if (response.error) {
			return emit('decryption-failed', { error: response.error });
		}
		handleDecrypted(stringToUint8Array(response.data), contentType);
	});
}

function handleDecrypted(decrypted, contentType) {
	var data = decompress(decrypted);
	if (contentType.indexOf('html') > 0) {
		data = sanitize_html(data);
	}
	var blobUrl = createBlob(data, contentType);

	emit('decrypted', {
		url: blobUrl,
		contentType: contentType
	});
}

function emit(event, data) {
	document.dispatchEvent(new CustomEvent(event, { detail : data }));
}

function decompress(data) {
	if (data[0] === gzipHeader[0] && data[1] === gzipHeader[1]) {
		try {
			return gzip.unzip(data);
		} catch(e) {
			console.error("Unzipping av brev feilet", e);
		}
	}
	return data;
}

function sanitize_html(data) {
	var bom = [0xef, 0xbb, 0xbf];
	if (data[0] !== bom[0] || data[1] !== bom[1] || data[2] !== bom[2]) {
		data = bom.concat(data);
	}
	var html = String.fromCharCode.apply(this, data);
	var purified = DOMPurify.sanitize(html, {WHOLE_DOCUMENT: true});
	return stringToUint8Array(purified);
}

function createBlob(decrypted, contentType) {
	var blob = new Blob( [ new Uint8Array(decrypted) ], { type: contentType } );
	return (window.URL || window.webkitURL).createObjectURL(blob);
}

function stringToUint8Array(str) {
	var arr = new Uint8Array(str.length);
	var j = str.length;
	for(var i = 0; i < j ; ++i){
	  arr[i] = str.charCodeAt(i);
	}
	return arr;
}

function failed(message) {
	document.dispatchEvent(new CustomEvent('failed', { detail : message } ));
}

document.addEventListener('start', function(e, x){
	download(e.detail);
});
<commit_msg>Added more explanation of what's going on when we load the override script so people won't have to deduce so much when reading the code<commit_after>"use strict";

(function loadOverrideScript() {
	console.debug("Loading override script into the Digipost DOM. This allows it to hook into Digiposts frontend display logic.");
	var s = document.createElement('script');
	s.src = chrome.extension.getURL('js/override.js');
	s.onload = function () {
		this.parentNode.removeChild(this);
	};
	(document.head || document.documentElement).appendChild(s);
})();

var gzipHeader = [0x1F, 0x8B];

function download(url) {
	console.time("Download");
	var xhr = new XMLHttpRequest();
	xhr.responseType = "arraybuffer";
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			console.timeEnd("Download");
			if (xhr.status !== 200) {
				return failed('Got wrong response ' + xhr.status);
			}
			var contentType = xhr.getResponseHeader('content-type');
			decrypt(xhr.response, contentType);
		}
	};
	xhr.open("GET", url, true);
	xhr.send();
}

function decrypt(data, contentType) {
	console.time("Decrypt");
	chrome.runtime.sendMessage({
		to:"background",
		message: "decrypt",
		data: forge.util.binary.base64.encode(new Uint8Array(data))
	}, function(response) {
		console.timeEnd("Decrypt");
		if (response.error) {
			return emit('decryption-failed', { error: response.error });
		}
		handleDecrypted(stringToUint8Array(response.data), contentType);
	});
}

function handleDecrypted(decrypted, contentType) {
	var data = decompress(decrypted);
	if (contentType.indexOf('html') > 0) {
		data = sanitize_html(data);
	}
	var blobUrl = createBlob(data, contentType);

	emit('decrypted', {
		url: blobUrl,
		contentType: contentType
	});
}

function emit(event, data) {
	document.dispatchEvent(new CustomEvent(event, { detail : data }));
}

function decompress(data) {
	if (data[0] === gzipHeader[0] && data[1] === gzipHeader[1]) {
		try {
			return gzip.unzip(data);
		} catch(e) {
			console.error("Unzipping av brev feilet", e);
		}
	}
	return data;
}

function sanitize_html(data) {
	var bom = [0xef, 0xbb, 0xbf];
	if (data[0] !== bom[0] || data[1] !== bom[1] || data[2] !== bom[2]) {
		data = bom.concat(data);
	}
	var html = String.fromCharCode.apply(this, data);
	var purified = DOMPurify.sanitize(html, {WHOLE_DOCUMENT: true});
	return stringToUint8Array(purified);
}

function createBlob(decrypted, contentType) {
	var blob = new Blob( [ new Uint8Array(decrypted) ], { type: contentType } );
	return (window.URL || window.webkitURL).createObjectURL(blob);
}

function stringToUint8Array(str) {
	var arr = new Uint8Array(str.length);
	var j = str.length;
	for(var i = 0; i < j ; ++i){
	  arr[i] = str.charCodeAt(i);
	}
	return arr;
}

function failed(message) {
	document.dispatchEvent(new CustomEvent('failed', { detail : message } ));
}

document.addEventListener('start', function(e, x){
	download(e.detail);
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

require('../dist/cli')
<commit_msg>make bin/lissie.js executable<commit_after>#!/usr/bin/env node

require('../dist/cli')
<|endoftext|>


<commit_before>/*
 * This file is part of TbSync.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

//no need to create namespace, we are in a sandbox

Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/Task.jsm");
Components.utils.import("resource://gre/modules/osfile.jsm");

let window = null;

//Observer to catch loading of thunderbird main window
let onLoadObserver = {
    observe: function(aSubject, aTopic, aData) {
        if (window === null) {
            window = Services.wm.getMostRecentWindow("mail:3pane");
            if (window) {
                //init TbSync
                window.tbSync = tbSync;
                tbSync.init(window);
            } else {
                tbSync.dump("FAIL", "Could not init TbSync, because mail:3pane window not found.");
            }
        }
    }
}

let onLoadDoneObserver = {
    observe: function(aSubject, aTopic, aData) {
        forEachOpenWindow(loadIntoWindow);
        Services.wm.addListener(WindowListener);
    }
}

function install(data, reason) {
}

function uninstall(data, reason) {
}

function startup(data, reason) {
    //Do not do anything, if version > 60
    if (Services.vc.compare(Services.appinfo.platformVersion, "60.*") <= 0)  {
        //possible reasons: APP_STARTUP, ADDON_ENABLE, ADDON_INSTALL, ADDON_UPGRADE, or ADDON_DOWNGRADE.

        //set default prefs
        let branch = Services.prefs.getDefaultBranch("extensions.tbsync.");
        branch.setIntPref("timeout", 90000);
        branch.setBoolPref("debug.testoptions", false);

        branch.setBoolPref("log.toconsole", false);
        branch.setBoolPref("log.tofile", false);
        branch.setIntPref("log.userdatalevel", 0); //0 - metadata (no incomming xml/wbxml, only parsed data without userdata (except failing items))   1 - including userdata,  2 - raw xml , 3 - raw wbxml

        Components.utils.import("chrome://tbsync/content/tbsync.jsm");
        Components.utils.import("chrome://tbsync/content/OverlayManager.jsm");

        //Map local writeAsyncJSON into tbSync
        tbSync.writeAsyncJSON = writeAsyncJSON;

        //add startup observers
        Services.obs.addObserver(onLoadObserver, "mail-startup-done", false);
        Services.obs.addObserver(onLoadObserver, "tbsync.init", false);
        Services.obs.addObserver(onLoadDoneObserver, "tbsync.init.done", false);

        tbSync.addonData = data;
        tbSync.overlayManager = new OverlayManager(data, {verbose:0});

        if (reason != APP_STARTUP) {
            //during startup, we wait until mail-startup-done fired, for all other reasons we need to fire our own init
            Services.obs.notifyObservers(null, 'tbsync.init', null)
        }

        //DO NOT ADD ANYTHING HERE!
        //The final init of TbSync was triggered by issuing a "tbsync.init". If that is done, it will issue a "tbsync.init.done".
        //So if there is stuff to do after init is done, add it at the local onLoadDoneObserver
    }
}

function shutdown(data, reason) {
    if (Services.vc.compare(Services.appinfo.platformVersion, "60.*") <= 0)  {
        //possible reasons: APP_SHUTDOWN, ADDON_DISABLE, ADDON_UNINSTALL, ADDON_UPGRADE, or ADDON_DOWNGRADE

        //remove startup observer
        Services.obs.removeObserver(onLoadObserver, "mail-startup-done");
        Services.obs.removeObserver(onLoadObserver, "tbsync.init");
        Services.obs.removeObserver(onLoadDoneObserver, "tbsync.init.done");

        //call cleanup of the tbSync module
        forEachOpenWindow(unloadFromWindow);
        Services.wm.removeListener(WindowListener);
        tbSync.cleanup();

        //abort write timers and write current file content to disk
        if (tbSync.enabled) {
            tbSync.db.changelogTimer.cancel();
            tbSync.db.accountsTimer.cancel();
            tbSync.db.foldersTimer.cancel();
            writeAsyncJSON(tbSync.db.accounts, tbSync.db.accountsFile);
            writeAsyncJSON(tbSync.db.folders, tbSync.db.foldersFile);
            writeAsyncJSON(tbSync.db.changelog, tbSync.db.changelogFile);
        }

        //unload tbSync module
        tbSync.dump("TbSync shutdown","Unloading TbSync module.");
        Components.utils.unload("chrome://tbsync/content/tbsync.jsm");
        Components.utils.unload("chrome://tbsync/content/OverlayManager.jsm");

        // HACK WARNING:
        //  - the Addon Manager does not properly clear all addon related caches on update;
        //  - in order to fully update images and locales, their caches need clearing here
        Services.obs.notifyObservers(null, "chrome-flush-caches", null);
    }
}

function forEachOpenWindow(todo)  // Apply a function to all open windows
{
    var windows = Services.wm.getEnumerator(null);
    while (windows.hasMoreElements()) {
        todo(windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindow));
    }
}

function loadIntoWindow(window) {
    //do not inject into main window, because we have done that in tbSync.init() to provide an option to the user to get the Ooops message,
    //in case something went wrong during init (and we do not reach this point)
    if (window.location.href != "chrome://messenger/content/messenger.xul" && tbSync.overlayManager.hasRegisteredOverlays(window)) {
        window.tbSync = tbSync;
        tbSync.overlayManager.injectAllOverlays(window);
    }
}

function unloadFromWindow(window) {
    if (tbSync.overlayManager.hasRegisteredOverlays(window)) {
        tbSync.overlayManager.removeAllOverlays(window);
        window.tbSync = null;
    }
}

var WindowListener =
{
    onOpenWindow: function(xulWindow)
    {
        var window = xulWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIDOMWindow);
        function onWindowLoad()
        {
            window.removeEventListener("load", onWindowLoad);
            loadIntoWindow(window);
        }
        window.addEventListener("load", onWindowLoad);
    },
    onCloseWindow: function(xulWindow) { },
    onWindowTitleChange: function(xulWindow, newTitle) { }
};

/*
 could be replaced in TB61:
  - https://dxr.mozilla.org/comm-central/rev/18881dd127e3b0c0d3f97390c9094e309d4dd9c1/mail/test/resources/jsbridge/jsbridge/extension/bootstrap.js#17
  - https://dxr.mozilla.org/comm-central/rev/18881dd127e3b0c0d3f97390c9094e309d4dd9c1/common/src/extensionSupport.jsm#151
*/

function writeAsyncJSON (obj, filename) {
    let filepath = tbSync.getAbsolutePath(filename);
    let storageDirectory = tbSync.storageDirectory;
    let json = tbSync.encoder.encode(JSON.stringify(obj));

    //no tbSync function/methods inside spawn, because it could run after tbSync was unloaded
    Task.spawn(function* () {
        //MDN states, instead of checking if dir exists, just create it and catch error on exist (but it does not even throw)
        yield OS.File.makeDir(storageDirectory);
        yield OS.File.writeAtomic(filepath, json, {tmpPath: filepath + ".tmp"});
    }).catch(Components.utils.reportError);
}
<commit_msg>example mode header<commit_after>/* -*- Mode: javascript; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 ; js-indent-level: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */

/*
 * This file is part of TbSync.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

//no need to create namespace, we are in a sandbox

Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/Task.jsm");
Components.utils.import("resource://gre/modules/osfile.jsm");

let window = null;

//Observer to catch loading of thunderbird main window
let onLoadObserver = {
    observe: function(aSubject, aTopic, aData) {
        if (window === null) {
            window = Services.wm.getMostRecentWindow("mail:3pane");
            if (window) {
                //init TbSync
                window.tbSync = tbSync;
                tbSync.init(window);
            } else {
                tbSync.dump("FAIL", "Could not init TbSync, because mail:3pane window not found.");
            }
        }
    }
}

let onLoadDoneObserver = {
    observe: function(aSubject, aTopic, aData) {
        forEachOpenWindow(loadIntoWindow);
        Services.wm.addListener(WindowListener);
    }
}

function install(data, reason) {
}

function uninstall(data, reason) {
}

function startup(data, reason) {
    //Do not do anything, if version > 60
    if (Services.vc.compare(Services.appinfo.platformVersion, "60.*") <= 0)  {
        //possible reasons: APP_STARTUP, ADDON_ENABLE, ADDON_INSTALL, ADDON_UPGRADE, or ADDON_DOWNGRADE.

        //set default prefs
        let branch = Services.prefs.getDefaultBranch("extensions.tbsync.");
        branch.setIntPref("timeout", 90000);
        branch.setBoolPref("debug.testoptions", false);

        branch.setBoolPref("log.toconsole", false);
        branch.setBoolPref("log.tofile", false);
        branch.setIntPref("log.userdatalevel", 0); //0 - metadata (no incomming xml/wbxml, only parsed data without userdata (except failing items))   1 - including userdata,  2 - raw xml , 3 - raw wbxml

        Components.utils.import("chrome://tbsync/content/tbsync.jsm");
        Components.utils.import("chrome://tbsync/content/OverlayManager.jsm");

        //Map local writeAsyncJSON into tbSync
        tbSync.writeAsyncJSON = writeAsyncJSON;

        //add startup observers
        Services.obs.addObserver(onLoadObserver, "mail-startup-done", false);
        Services.obs.addObserver(onLoadObserver, "tbsync.init", false);
        Services.obs.addObserver(onLoadDoneObserver, "tbsync.init.done", false);

        tbSync.addonData = data;
        tbSync.overlayManager = new OverlayManager(data, {verbose:0});

        if (reason != APP_STARTUP) {
            //during startup, we wait until mail-startup-done fired, for all other reasons we need to fire our own init
            Services.obs.notifyObservers(null, 'tbsync.init', null)
        }

        //DO NOT ADD ANYTHING HERE!
        //The final init of TbSync was triggered by issuing a "tbsync.init". If that is done, it will issue a "tbsync.init.done".
        //So if there is stuff to do after init is done, add it at the local onLoadDoneObserver
    }
}

function shutdown(data, reason) {
    if (Services.vc.compare(Services.appinfo.platformVersion, "60.*") <= 0)  {
        //possible reasons: APP_SHUTDOWN, ADDON_DISABLE, ADDON_UNINSTALL, ADDON_UPGRADE, or ADDON_DOWNGRADE

        //remove startup observer
        Services.obs.removeObserver(onLoadObserver, "mail-startup-done");
        Services.obs.removeObserver(onLoadObserver, "tbsync.init");
        Services.obs.removeObserver(onLoadDoneObserver, "tbsync.init.done");

        //call cleanup of the tbSync module
        forEachOpenWindow(unloadFromWindow);
        Services.wm.removeListener(WindowListener);
        tbSync.cleanup();

        //abort write timers and write current file content to disk
        if (tbSync.enabled) {
            tbSync.db.changelogTimer.cancel();
            tbSync.db.accountsTimer.cancel();
            tbSync.db.foldersTimer.cancel();
            writeAsyncJSON(tbSync.db.accounts, tbSync.db.accountsFile);
            writeAsyncJSON(tbSync.db.folders, tbSync.db.foldersFile);
            writeAsyncJSON(tbSync.db.changelog, tbSync.db.changelogFile);
        }

        //unload tbSync module
        tbSync.dump("TbSync shutdown","Unloading TbSync module.");
        Components.utils.unload("chrome://tbsync/content/tbsync.jsm");
        Components.utils.unload("chrome://tbsync/content/OverlayManager.jsm");

        // HACK WARNING:
        //  - the Addon Manager does not properly clear all addon related caches on update;
        //  - in order to fully update images and locales, their caches need clearing here
        Services.obs.notifyObservers(null, "chrome-flush-caches", null);
    }
}

function forEachOpenWindow(todo)  // Apply a function to all open windows
{
    var windows = Services.wm.getEnumerator(null);
    while (windows.hasMoreElements()) {
        todo(windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindow));
    }
}

function loadIntoWindow(window) {
    //do not inject into main window, because we have done that in tbSync.init() to provide an option to the user to get the Ooops message,
    //in case something went wrong during init (and we do not reach this point)
    if (window.location.href != "chrome://messenger/content/messenger.xul" && tbSync.overlayManager.hasRegisteredOverlays(window)) {
        window.tbSync = tbSync;
        tbSync.overlayManager.injectAllOverlays(window);
    }
}

function unloadFromWindow(window) {
    if (tbSync.overlayManager.hasRegisteredOverlays(window)) {
        tbSync.overlayManager.removeAllOverlays(window);
        window.tbSync = null;
    }
}

var WindowListener =
{
    onOpenWindow: function(xulWindow)
    {
        var window = xulWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIDOMWindow);
        function onWindowLoad()
        {
            window.removeEventListener("load", onWindowLoad);
            loadIntoWindow(window);
        }
        window.addEventListener("load", onWindowLoad);
    },
    onCloseWindow: function(xulWindow) { },
    onWindowTitleChange: function(xulWindow, newTitle) { }
};

/*
 could be replaced in TB61:
  - https://dxr.mozilla.org/comm-central/rev/18881dd127e3b0c0d3f97390c9094e309d4dd9c1/mail/test/resources/jsbridge/jsbridge/extension/bootstrap.js#17
  - https://dxr.mozilla.org/comm-central/rev/18881dd127e3b0c0d3f97390c9094e309d4dd9c1/common/src/extensionSupport.jsm#151
*/

function writeAsyncJSON (obj, filename) {
    let filepath = tbSync.getAbsolutePath(filename);
    let storageDirectory = tbSync.storageDirectory;
    let json = tbSync.encoder.encode(JSON.stringify(obj));

    //no tbSync function/methods inside spawn, because it could run after tbSync was unloaded
    Task.spawn(function* () {
        //MDN states, instead of checking if dir exists, just create it and catch error on exist (but it does not even throw)
        yield OS.File.makeDir(storageDirectory);
        yield OS.File.writeAtomic(filepath, json, {tmpPath: filepath + ".tmp"});
    }).catch(Components.utils.reportError);
}
<|endoftext|>


<commit_before>$(document).ready(function () {
  $("a.navbar-brand, ul.nav li a, .jumbotron .btn").click(function (event) {
    event.preventDefault();
    $(".navbar-collapse.in").collapse("hide");
    $("html, body").stop().animate({
      scrollTop: $($(this).attr("href")).offset().top - 73
    }, 500);
    if (history.pushState) {
      history.pushState(null, null, $(this).attr("href"));
    } else {
      location.hash = $(this).attr("href");
    }
  });

  $("#send").click(function() {
    var data = {
      email: $("#email").val(),
      name: $("#name").val(),
      message: $("#message").val()
    };
    $.ajax({
      type: "POST",
      url: "//formspree.io/mike@mhenry.io",
      dataType: "json",
      data: data,
      success: function() {
        $("form div.col-md-8").prepend('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Success! We\'ll be in touch soon.
');
        $("form").trigger("reset");
      },
      error:function() {
        $("form div.col-md-8").prepend('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>D\'oh! Something went wrong.
');
      }
    });
  });
});
<commit_msg>Update mhenry.js<commit_after>$(document).ready(function () {
  $("a.navbar-brand, ul.nav li a, .jumbotron .btn").click(function (event) {
    event.preventDefault();
    $(".navbar-collapse.in").collapse("hide");
    $("html, body").stop().animate({
      scrollTop: $($(this).attr("href")).offset().top - 73
    }, 500);
    if (history.pushState) {
      history.pushState(null, null, $(this).attr("href"));
    } else {
      location.hash = $(this).attr("href");
    }
  });

  $("#send").click(function() {
    var data = {
      email: $("#email").val(),
      name: $("#name").val(),
      message: $("#message").val()
    };
    $.ajax({
      type: "POST",
      url: "https://formspree.io/mpzywglr",
      dataType: "json",
      data: data,
      success: function() {
        $("form div.col-md-8").prepend('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Success! We\'ll be in touch soon.
');
        $("form").trigger("reset");
      },
      error:function() {
        $("form div.col-md-8").prepend('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>D\'oh! Something went wrong.
');
      }
    });
  });
});
<|endoftext|>


<commit_before>/**
 * The reveal.js markdown plugin. Handles parsing of
 * markdown inside of presentations as well as loading
 * of external markdown documents.
 */
(function( root, factory ) {
	if (typeof define === 'function' && define.amd) {
		root.marked = require( './marked' );
		root.RevealMarkdown = factory( root.marked );
		root.RevealMarkdown.initialize();
	} else if( typeof exports === 'object' ) {
		module.exports = factory( require( './marked' ) );
	} else {
		// Browser globals (root is window)
		root.RevealMarkdown = factory( root.marked );
		root.RevealMarkdown.initialize();
	}
}( this, function( marked ) {

	var DEFAULT_SLIDE_SEPARATOR = '^\r?\n---\r?\n$',
		DEFAULT_NOTES_SEPARATOR = 'note:',
		DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$',
		DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$';

	var SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__';

	/**
	 * Retrieves the markdown contents of a slide section
	 * element. Normalizes leading tabs/whitespace.
	 */
	function getMarkdownFromSlide( section ) {
		// support <textarea data-template> `some code` </textarea>
		var template = section.querySelector( '[data-tempate]' ) || section.querySelector( 'script' );

		// strip leading whitespace so it isn't evaluated as code
		var text = ( template || section ).textContent;

		// restore script end tags
		text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' );

		var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
			leadingTabs = text.match( /^\n?(\t*)/ )[1].length;

		if( leadingTabs > 0 ) {
			text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
		}
		else if( leadingWs > 1 ) {
			text = text.replace( new RegExp('\\n? {' + leadingWs + '}', 'g'), '\n' );
		}

		return text;

	}

	/**
	 * Given a markdown slide section element, this will
	 * return all arguments that aren't related to markdown
	 * parsing. Used to forward any other user-defined arguments
	 * to the output markdown slide.
	 */
	function getForwardedAttributes( section ) {

		var attributes = section.attributes;
		var result = [];

		for( var i = 0, len = attributes.length; i < len; i++ ) {
			var name = attributes[i].name,
				value = attributes[i].value;

			// disregard attributes that are used for markdown loading/parsing
			if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;

			if( value ) {
				result.push( name + '="' + value + '"' );
			}
			else {
				result.push( name );
			}
		}

		return result.join( ' ' );

	}

	/**
	 * Inspects the given options and fills out default
	 * values for what's not defined.
	 */
	function getSlidifyOptions( options ) {

		options = options || {};
		options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
		options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
		options.attributes = options.attributes || '';

		return options;

	}

	/**
	 * Helper function for constructing a markdown slide.
	 */
	function createMarkdownSlide( content, options ) {

		options = getSlidifyOptions( options );

		var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );

		if( notesMatch.length === 2 ) {
			content = notesMatch[0] + '' + marked(notesMatch[1].trim()) + '';
		}

		// prevent script end tags in the content from interfering
		// with parsing
		content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER );

		return '';

	}

	/**
	 * Parses a data string into multiple slides based
	 * on the passed in separator arguments.
	 */
	function slidify( markdown, options ) {

		options = getSlidifyOptions( options );

		var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
			horizontalSeparatorRegex = new RegExp( options.separator );

		var matches,
			lastIndex = 0,
			isHorizontal,
			wasHorizontal = true,
			content,
			sectionStack = [];

		// iterate until all blocks between separators are stacked up
		while( matches = separatorRegex.exec( markdown ) ) {
			notes = null;

			// determine direction (horizontal by default)
			isHorizontal = horizontalSeparatorRegex.test( matches[0] );

			if( !isHorizontal && wasHorizontal ) {
				// create vertical stack
				sectionStack.push( [] );
			}

			// pluck slide content from markdown input
			content = markdown.substring( lastIndex, matches.index );

			if( isHorizontal && wasHorizontal ) {
				// add to horizontal stack
				sectionStack.push( content );
			}
			else {
				// add to vertical stack
				sectionStack[sectionStack.length-1].push( content );
			}

			lastIndex = separatorRegex.lastIndex;
			wasHorizontal = isHorizontal;
		}

		// add the remaining slide
		( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );

		var markdownSections = '';

		// flatten the hierarchical stack, and insert
 tags
		for( var i = 0, len = sectionStack.length; i < len; i++ ) {
			// vertical
			if( sectionStack[i] instanceof Array ) {
				markdownSections += '
';

				sectionStack[i].forEach( function( child ) {
					markdownSections += '
' + createMarkdownSlide( child, options ) + '
';
				} );

				markdownSections += '
';
			}
			else {
				markdownSections += '
' + createMarkdownSlide( sectionStack[i], options ) + '
';
			}
		}

		return markdownSections;

	}

	/**
	 * Parses any current data-markdown slides, splits
	 * multi-slide markdown into separate sections and
	 * handles loading of external markdown.
	 */
	function processSlides() {

		var sections = document.querySelectorAll( '[data-markdown]'),
			section;

		for( var i = 0, len = sections.length; i < len; i++ ) {

			section = sections[i];

			if( section.getAttribute( 'data-markdown' ).length ) {

				var xhr = new XMLHttpRequest(),
					url = section.getAttribute( 'data-markdown' );

				datacharset = section.getAttribute( 'data-charset' );

				// see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
				if( datacharset != null && datacharset != '' ) {
					xhr.overrideMimeType( 'text/html; charset=' + datacharset );
				}

				xhr.onreadystatechange = function() {
					if( xhr.readyState === 4 ) {
						// file protocol yields status code 0 (useful for local debug, mobile applications etc.)
						if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) {

							section.outerHTML = slidify( xhr.responseText, {
								separator: section.getAttribute( 'data-separator' ),
								verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
								notesSeparator: section.getAttribute( 'data-separator-notes' ),
								attributes: getForwardedAttributes( section )
							});

						}
						else {

							section.outerHTML = '
' +
								'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
								'Check your browser\'s JavaScript console for more details.' +
								'
Remember that you need to serve the presentation HTML from a HTTP server.
' +
								'
';

						}
					}
				};

				xhr.open( 'GET', url, false );

				try {
					xhr.send();
				}
				catch ( e ) {
					alert( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e );
				}

			}
			else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-separator-vertical' ) || section.getAttribute( 'data-separator-notes' ) ) {

				section.outerHTML = slidify( getMarkdownFromSlide( section ), {
					separator: section.getAttribute( 'data-separator' ),
					verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
					notesSeparator: section.getAttribute( 'data-separator-notes' ),
					attributes: getForwardedAttributes( section )
				});

			}
			else {
				section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
			}
		}

	}

	/**
	 * Check if a node value has the attributes pattern.
	 * If yes, extract it and add that value as one or several attributes
	 * the the terget element.
	 *
	 * You need Cache Killer on Chrome to see the effect on any FOM transformation
	 * directly on refresh (F5)
	 * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
	 */
	function addAttributeInElement( node, elementTarget, separator ) {

		var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
		var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
		var nodeValue = node.nodeValue;
		if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {

			var classes = matches[1];
			nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
			node.nodeValue = nodeValue;
			while( matchesClass = mardownClassRegex.exec( classes ) ) {
				elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
			}
			return true;
		}
		return false;
	}

	/**
	 * Add attributes to the parent element of a text node,
	 * or the element of an attribute node.
	 */
	function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {

		if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
			previousParentElement = element;
			for( var i = 0; i < element.childNodes.length; i++ ) {
				childElement = element.childNodes[i];
				if ( i > 0 ) {
					j = i - 1;
					while ( j >= 0 ) {
						aPreviousChildElement = element.childNodes[j];
						if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
							previousParentElement = aPreviousChildElement;
							break;
						}
						j = j - 1;
					}
				}
				parentSection = section;
				if( childElement.nodeName ==  "section" ) {
					parentSection = childElement ;
					previousParentElement = childElement ;
				}
				if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
					addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
				}
			}
		}

		if ( element.nodeType == Node.COMMENT_NODE ) {
			if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
				addAttributeInElement( element, section, separatorSectionAttributes );
			}
		}
	}

	/**
	 * Converts any current data-markdown slides in the
	 * DOM to HTML.
	 */
	function convertSlides() {

		var sections = document.querySelectorAll( '[data-markdown]');

		for( var i = 0, len = sections.length; i < len; i++ ) {

			var section = sections[i];

			// Only parse the same slide once
			if( !section.getAttribute( 'data-markdown-parsed' ) ) {

				section.setAttribute( 'data-markdown-parsed', true )

				var notes = section.querySelector( 'aside.notes' );
				var markdown = getMarkdownFromSlide( section );

				section.innerHTML = marked( markdown );
				addAttributes( 	section, section, null, section.getAttribute( 'data-element-attributes' ) ||
								section.parentNode.getAttribute( 'data-element-attributes' ) ||
								DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
								section.getAttribute( 'data-attributes' ) ||
								section.parentNode.getAttribute( 'data-attributes' ) ||
								DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);

				// If there were notes, we need to re-add them after
				// having overwritten the section's HTML
				if( notes ) {
					section.appendChild( notes );
				}

			}

		}

	}

	// API
	return {

		initialize: function() {
			if( typeof marked === 'undefined' ) {
				throw 'The reveal.js Markdown plugin requires marked to be loaded';
			}

			if( typeof hljs !== 'undefined' ) {
				marked.setOptions({
					highlight: function( code, lang ) {
						return hljs.highlightAuto( code, [lang] ).value;
					}
				});
			}

			var options = Reveal.getConfig().markdown;

			if ( options ) {
				marked.setOptions( options );
			}

			processSlides();
			convertSlides();
		},

		// TODO: Do these belong in the API?
		processSlides: processSlides,
		convertSlides: convertSlides,
		slidify: slidify

	};

}));
<commit_msg>fix markdown typo, update comment #1780<commit_after>/**
 * The reveal.js markdown plugin. Handles parsing of
 * markdown inside of presentations as well as loading
 * of external markdown documents.
 */
(function( root, factory ) {
	if (typeof define === 'function' && define.amd) {
		root.marked = require( './marked' );
		root.RevealMarkdown = factory( root.marked );
		root.RevealMarkdown.initialize();
	} else if( typeof exports === 'object' ) {
		module.exports = factory( require( './marked' ) );
	} else {
		// Browser globals (root is window)
		root.RevealMarkdown = factory( root.marked );
		root.RevealMarkdown.initialize();
	}
}( this, function( marked ) {

	var DEFAULT_SLIDE_SEPARATOR = '^\r?\n---\r?\n$',
		DEFAULT_NOTES_SEPARATOR = 'note:',
		DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$',
		DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$';

	var SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__';

	/**
	 * Retrieves the markdown contents of a slide section
	 * element. Normalizes leading tabs/whitespace.
	 */
	function getMarkdownFromSlide( section ) {

		// look for a ' );

		var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
			leadingTabs = text.match( /^\n?(\t*)/ )[1].length;

		if( leadingTabs > 0 ) {
			text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
		}
		else if( leadingWs > 1 ) {
			text = text.replace( new RegExp('\\n? {' + leadingWs + '}', 'g'), '\n' );
		}

		return text;

	}

	/**
	 * Given a markdown slide section element, this will
	 * return all arguments that aren't related to markdown
	 * parsing. Used to forward any other user-defined arguments
	 * to the output markdown slide.
	 */
	function getForwardedAttributes( section ) {

		var attributes = section.attributes;
		var result = [];

		for( var i = 0, len = attributes.length; i < len; i++ ) {
			var name = attributes[i].name,
				value = attributes[i].value;

			// disregard attributes that are used for markdown loading/parsing
			if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;

			if( value ) {
				result.push( name + '="' + value + '"' );
			}
			else {
				result.push( name );
			}
		}

		return result.join( ' ' );

	}

	/**
	 * Inspects the given options and fills out default
	 * values for what's not defined.
	 */
	function getSlidifyOptions( options ) {

		options = options || {};
		options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
		options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
		options.attributes = options.attributes || '';

		return options;

	}

	/**
	 * Helper function for constructing a markdown slide.
	 */
	function createMarkdownSlide( content, options ) {

		options = getSlidifyOptions( options );

		var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );

		if( notesMatch.length === 2 ) {
			content = notesMatch[0] + '' + marked(notesMatch[1].trim()) + '';
		}

		// prevent script end tags in the content from interfering
		// with parsing
		content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER );

		return '';

	}

	/**
	 * Parses a data string into multiple slides based
	 * on the passed in separator arguments.
	 */
	function slidify( markdown, options ) {

		options = getSlidifyOptions( options );

		var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
			horizontalSeparatorRegex = new RegExp( options.separator );

		var matches,
			lastIndex = 0,
			isHorizontal,
			wasHorizontal = true,
			content,
			sectionStack = [];

		// iterate until all blocks between separators are stacked up
		while( matches = separatorRegex.exec( markdown ) ) {
			notes = null;

			// determine direction (horizontal by default)
			isHorizontal = horizontalSeparatorRegex.test( matches[0] );

			if( !isHorizontal && wasHorizontal ) {
				// create vertical stack
				sectionStack.push( [] );
			}

			// pluck slide content from markdown input
			content = markdown.substring( lastIndex, matches.index );

			if( isHorizontal && wasHorizontal ) {
				// add to horizontal stack
				sectionStack.push( content );
			}
			else {
				// add to vertical stack
				sectionStack[sectionStack.length-1].push( content );
			}

			lastIndex = separatorRegex.lastIndex;
			wasHorizontal = isHorizontal;
		}

		// add the remaining slide
		( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );

		var markdownSections = '';

		// flatten the hierarchical stack, and insert
 tags
		for( var i = 0, len = sectionStack.length; i < len; i++ ) {
			// vertical
			if( sectionStack[i] instanceof Array ) {
				markdownSections += '
';

				sectionStack[i].forEach( function( child ) {
					markdownSections += '
' + createMarkdownSlide( child, options ) + '
';
				} );

				markdownSections += '
';
			}
			else {
				markdownSections += '
' + createMarkdownSlide( sectionStack[i], options ) + '
';
			}
		}

		return markdownSections;

	}

	/**
	 * Parses any current data-markdown slides, splits
	 * multi-slide markdown into separate sections and
	 * handles loading of external markdown.
	 */
	function processSlides() {

		var sections = document.querySelectorAll( '[data-markdown]'),
			section;

		for( var i = 0, len = sections.length; i < len; i++ ) {

			section = sections[i];

			if( section.getAttribute( 'data-markdown' ).length ) {

				var xhr = new XMLHttpRequest(),
					url = section.getAttribute( 'data-markdown' );

				datacharset = section.getAttribute( 'data-charset' );

				// see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
				if( datacharset != null && datacharset != '' ) {
					xhr.overrideMimeType( 'text/html; charset=' + datacharset );
				}

				xhr.onreadystatechange = function() {
					if( xhr.readyState === 4 ) {
						// file protocol yields status code 0 (useful for local debug, mobile applications etc.)
						if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) {

							section.outerHTML = slidify( xhr.responseText, {
								separator: section.getAttribute( 'data-separator' ),
								verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
								notesSeparator: section.getAttribute( 'data-separator-notes' ),
								attributes: getForwardedAttributes( section )
							});

						}
						else {

							section.outerHTML = '
' +
								'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
								'Check your browser\'s JavaScript console for more details.' +
								'
Remember that you need to serve the presentation HTML from a HTTP server.
' +
								'
';

						}
					}
				};

				xhr.open( 'GET', url, false );

				try {
					xhr.send();
				}
				catch ( e ) {
					alert( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e );
				}

			}
			else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-separator-vertical' ) || section.getAttribute( 'data-separator-notes' ) ) {

				section.outerHTML = slidify( getMarkdownFromSlide( section ), {
					separator: section.getAttribute( 'data-separator' ),
					verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
					notesSeparator: section.getAttribute( 'data-separator-notes' ),
					attributes: getForwardedAttributes( section )
				});

			}
			else {
				section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
			}
		}

	}

	/**
	 * Check if a node value has the attributes pattern.
	 * If yes, extract it and add that value as one or several attributes
	 * the the terget element.
	 *
	 * You need Cache Killer on Chrome to see the effect on any FOM transformation
	 * directly on refresh (F5)
	 * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
	 */
	function addAttributeInElement( node, elementTarget, separator ) {

		var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
		var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
		var nodeValue = node.nodeValue;
		if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {

			var classes = matches[1];
			nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
			node.nodeValue = nodeValue;
			while( matchesClass = mardownClassRegex.exec( classes ) ) {
				elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
			}
			return true;
		}
		return false;
	}

	/**
	 * Add attributes to the parent element of a text node,
	 * or the element of an attribute node.
	 */
	function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {

		if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
			previousParentElement = element;
			for( var i = 0; i < element.childNodes.length; i++ ) {
				childElement = element.childNodes[i];
				if ( i > 0 ) {
					j = i - 1;
					while ( j >= 0 ) {
						aPreviousChildElement = element.childNodes[j];
						if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
							previousParentElement = aPreviousChildElement;
							break;
						}
						j = j - 1;
					}
				}
				parentSection = section;
				if( childElement.nodeName ==  "section" ) {
					parentSection = childElement ;
					previousParentElement = childElement ;
				}
				if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
					addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
				}
			}
		}

		if ( element.nodeType == Node.COMMENT_NODE ) {
			if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
				addAttributeInElement( element, section, separatorSectionAttributes );
			}
		}
	}

	/**
	 * Converts any current data-markdown slides in the
	 * DOM to HTML.
	 */
	function convertSlides() {

		var sections = document.querySelectorAll( '[data-markdown]');

		for( var i = 0, len = sections.length; i < len; i++ ) {

			var section = sections[i];

			// Only parse the same slide once
			if( !section.getAttribute( 'data-markdown-parsed' ) ) {

				section.setAttribute( 'data-markdown-parsed', true )

				var notes = section.querySelector( 'aside.notes' );
				var markdown = getMarkdownFromSlide( section );

				section.innerHTML = marked( markdown );
				addAttributes( 	section, section, null, section.getAttribute( 'data-element-attributes' ) ||
								section.parentNode.getAttribute( 'data-element-attributes' ) ||
								DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
								section.getAttribute( 'data-attributes' ) ||
								section.parentNode.getAttribute( 'data-attributes' ) ||
								DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);

				// If there were notes, we need to re-add them after
				// having overwritten the section's HTML
				if( notes ) {
					section.appendChild( notes );
				}

			}

		}

	}

	// API
	return {

		initialize: function() {
			if( typeof marked === 'undefined' ) {
				throw 'The reveal.js Markdown plugin requires marked to be loaded';
			}

			if( typeof hljs !== 'undefined' ) {
				marked.setOptions({
					highlight: function( code, lang ) {
						return hljs.highlightAuto( code, [lang] ).value;
					}
				});
			}

			var options = Reveal.getConfig().markdown;

			if ( options ) {
				marked.setOptions( options );
			}

			processSlides();
			convertSlides();
		},

		// TODO: Do these belong in the API?
		processSlides: processSlides,
		convertSlides: convertSlides,
		slidify: slidify

	};

}));
<|endoftext|>


<commit_before>/*
 * Init login overlay
 */
$('document').ready(function () {
    $('#modaloverlay').click(function () {
        hideModal();
    });

    $('.modal_box').click(function (e) {
        e.stopPropagation();
    });

    $('#usermanagement').click(function () {
        showLogin();
    });

    $('#loginform').submit(function (e) {
        // Hide the error message
        $('#login_error').hide();

        // Post the form
        $.ajax({
            type: "POST",
            url: "/login/" + encodeURIComponent($('#loginform').find('input[name="email"]').val()),
            data: $('#loginform').serialize(),
            success: function () {
                // Reload page when logged in
                location.reload();
            },
            error: function () {
                // Display error message
                $('#login_error').html(i18n.__("ServiceNotReachableError"));
                $('#login_error').show();
            }
        });

        // Stop form submit via normal post
        e.preventDefault();
    });
});

/*
 * Log out a user from the system
 */
function logoutUser() {
    $.ajax({
        url: 'logout',
        success: function () {
            location.reload();
        }
    });
}

/*
 * Show the login modal
 */
function showLogin() {
    // Clear the form
    $('#login_error').hide();
    $('#loginform')[0].reset();

    // Show the login window
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#login_modal').show();
    $('#modaloverlay').show();
}

/*
 * Show the Yes and No modal with callback
 */
function showYesNoModal(body, callback) {
    // Hide the login window
    $('#login_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#yes_no_modal').show();

    // Fill up the body
    $('#modal_title_body').html = body;

    // Show the modal
    $('#modaloverlay').show();

    $('#ynmodel-y-btn').click(function () {
        callback(true);
        hideModal();
    });

    $('#ynmodal-n-btn').click(function () {
        callback(false);
        hideModal();
    });
}

function showUploadModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').show();

    $('#modaloverlay').show();
}

function showGeneralModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#upload_modal').hide();
    $('#general_modal').show();

    // Show the modal
    $('#modaloverlay').show();
}

function setGeneralModalTitle(title)
{
    $('#general_modal_title').html(title);
}

function setGeneralModalBody(body)
{
    $('#general_modal_body').html(body);
}

function getGeneralModalBody()
{
    return $('#general_modal_body').html();
}

function addGeneralModalButton(text, action)
{
    var button = document.createElement('button');
    $(button).addClass('btn btn-primary inline btn-extra-margin');
    $(button).click(function () {
        action();
    });
    $(button).html(text);
    $('#general_modal_buttons').append(button);
}

function resetGeneralModal()
{
    $('#general_modal_title').empty();
    $('#general_modal_body').empty();
    $('#general_modal_buttons').empty();
}

function hideModal() {
    $('#modaloverlay').hide();
}

$(document).ready(function () {
    $('#uploadformbtn').click(function () {
        // Get the form data. This serializes the entire form. pritty easy huh!
        var form = new FormData($('#uploadform')[0]);

        // Make the ajax call
        $.ajax({
            url: '/api/upload',
            type: 'POST',
            xhr: function () {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', progress, false);
                }
                return myXhr;
            },
            //add beforesend handler to validate or something
            beforeSend: function () {
                $('progress').attr({value: 0, max: 100});
                $('#upload-result').html('Progress: <progress value="0" max="100" id="progressbar"></progress>');
            },
            success: function (res) {
                $('#upload-result').html('
Uploaded files:

');

                $.each(res, function (index, elem) {
                    var div = document.createElement('div');
                    div.className += 'upimage';
                    $('#uploaded-files').appendChild(div);

                    div.innerHTML += '
';
                    div.innerHTML += 'id: ' + elem['id'] + '
';
                    div.innerHTML += 'type: ' + elem['type'] + '
';
                    div.innerHTML += 'name: ' + elem['name'] + '
';
                    div.innerHTML += 'size: ' + elem['size'] + '';
                });
            },
            //add error handler for when a error occurs if you want!
            error: function (xhr, status, error) {
                setGeneralModalTitle('Upload error');
                setGeneralModalBody(xhr.responseText);
                showGeneralModal();

            },
            data: form,
            // this is the important stuf you need to overide the usual post behavior
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

// Yes outside of the .ready space becouse this is a function not an event listner!
function progress(e) {
    if (e.lengthComputable) {
        //this makes a nice fancy progress bar
        $('progress').attr({value: e.loaded, max: e.total});
    }
}<commit_msg>updated upload to fit in dptcms<commit_after>/*
 * Init login overlay
 */
$('document').ready(function () {
    $('#modaloverlay').click(function () {
        hideModal();
    });

    $('.modal_box').click(function (e) {
        e.stopPropagation();
    });

    $('#usermanagement').click(function () {
        showLogin();
    });

    $('#loginform').submit(function (e) {
        // Hide the error message
        $('#login_error').hide();

        // Post the form
        $.ajax({
            type: "POST",
            url: "/login/" + encodeURIComponent($('#loginform').find('input[name="email"]').val()),
            data: $('#loginform').serialize(),
            success: function () {
                // Reload page when logged in
                location.reload();
            },
            error: function () {
                // Display error message
                $('#login_error').html(i18n.__("ServiceNotReachableError"));
                $('#login_error').show();
            }
        });

        // Stop form submit via normal post
        e.preventDefault();
    });
});

/*
 * Log out a user from the system
 */
function logoutUser() {
    $.ajax({
        url: 'logout',
        success: function () {
            location.reload();
        }
    });
}

/*
 * Show the login modal
 */
function showLogin() {
    // Clear the form
    $('#login_error').hide();
    $('#loginform')[0].reset();

    // Show the login window
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#login_modal').show();
    $('#modaloverlay').show();
}

/*
 * Show the Yes and No modal with callback
 */
function showYesNoModal(body, callback) {
    // Hide the login window
    $('#login_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#yes_no_modal').show();

    // Fill up the body
    $('#modal_title_body').html = body;

    // Show the modal
    $('#modaloverlay').show();

    $('#ynmodel-y-btn').click(function () {
        callback(true);
        hideModal();
    });

    $('#ynmodal-n-btn').click(function () {
        callback(false);
        hideModal();
    });
}

function showUploadModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').show();

    $('#modaloverlay').show();
}

function showGeneralModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#upload_modal').hide();
    $('#general_modal').show();

    // Show the modal
    $('#modaloverlay').show();
}

function setGeneralModalTitle(title)
{
    $('#general_modal_title').html(title);
}

function setGeneralModalBody(body)
{
    $('#general_modal_body').html(body);
}

function getGeneralModalBody()
{
    return $('#general_modal_body').html();
}

function addGeneralModalButton(text, action)
{
    var button = document.createElement('button');
    $(button).addClass('btn btn-primary inline btn-extra-margin');
    $(button).click(function () {
        action();
    });
    $(button).html(text);
    $('#general_modal_buttons').append(button);
}

function resetGeneralModal()
{
    $('#general_modal_title').empty();
    $('#general_modal_body').empty();
    $('#general_modal_buttons').empty();
}

function hideModal() {
    $('#modaloverlay').hide();
}

$(document).ready(function () {
    $('#uploadformbtn').click(function () {
        // Get the form data. This serializes the entire form. pritty easy huh!
        var form = new FormData($('#uploadform')[0]);

        // Make the ajax call
        $.ajax({
            url: '/api/upload',
            type: 'POST',
            xhr: function () {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', progress, false);
                }
                return myXhr;
            },
            //add beforesend handler to validate or something
            beforeSend: function () {
                $('progress').attr({value: 0, max: 100});
                $('#upload-result').html('Progress: <progress value="0" max="100" id="progressbar"></progress>');
            },
            success: function (res) {
                $('#upload-result').html('
Uploaded files:

');

                $.each(res, function (index, elem) {
                    var div = document.createElement('div');
                    div.className += 'upimage';
                    $('#uploaded-files').append(div);

                    div.innerHTML += '
';
                    div.innerHTML += 'id: ' + elem['id'] + '
';
                    div.innerHTML += 'type: ' + elem['type'] + '
';
                    div.innerHTML += 'name: ' + elem['name'] + '
';
                    div.innerHTML += 'size: ' + elem['size'] + '';
                });
            },
            //add error handler for when a error occurs if you want!
            error: function (xhr, status, error) {
                setGeneralModalTitle('Upload error');
                setGeneralModalBody(xhr.responseText);
                showGeneralModal();

            },
            data: form,
            // this is the important stuf you need to overide the usual post behavior
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

// Yes outside of the .ready space becouse this is a function not an event listner!
function progress(e) {
    if (e.lengthComputable) {
        //this makes a nice fancy progress bar
        $('progress').attr({value: e.loaded, max: e.total});
    }
}<|endoftext|>