<commit_before>"use strict";

const url = require("url");
const util = require("util");

const cheerio = require("cheerio");
let request = require("request");

const registered_domains = {};

const max_req_len = 1000000; // 1MB

request = request.defaults({
  sendImmediately: true,
  timeout: 10000,
  headers: {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
    "Accept" :"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.8",
    "Cache-Control": "max-age=0",
  }
});

// Modified/extended version of Cheerio's elems.text()
function textify(elems, filter, sep) {
  sep = sep || "";
  let ret = "";
  elems = filter(elems);
  const len = elems.length;

  for (let i = 0; i < len; i++) {
    let elem = elems[i];
    if (elem.type === "text") {
      ret += elem.data + sep;
    } else if (elem.children && elem.type !== "comment") {
      if (elem.name === "img" && elem.attribs.alt && elem.attribs.alt.length < 3) {
        // Javascript strings are UCS-2 or whatever, so it counts one emoji as 2ish chars
        ret += elem.attribs.alt;
      } else {
        ret += textify(elem.children, filter, sep);
      }
    }
  }

  return ret;
}

function parse_generic(url_path, $) {
  let title = $("html head title").text();

  if (title.length > 100) {
    title = title.slice(0, 100);
    title += "...";
  }

  return title;
}

function parse_github(url_path, $) {
  if (url_path.match("^\\/[\\w-]+\\/[\\w-]+\\/?$") === null) {
    return parse_generic(url_path, $);
  }

  let ul = $("ul.pagehead-actions > li > a.js-social-count");
  const stargazers = $(ul[0]).text().replace(/\s/g, "");
  ul = $("ul.pagehead-actions > li > a.social-count");
  let forks = $(ul[2]).text().replace(/\s/g, "");
  // Horrible hack. Github sometimes switches the order of these.
  if (forks === stargazers) {
    forks = $(ul[1]).text().replace(/\s/g, "");
  }
  const description = $("div.repository-meta").text().trim();
  const name = $("h1.public > strong > a").text();
  if (name) {
    return util.format("%s (%s stars %s forks) %s", name, stargazers, forks, description);
  }
  return parse_generic(url_path, $);
}

function parse_hn(url_path, $) {
  if (url_path.match("^\\/item\\?id=\\d+") === null) {
    return parse_generic(url_path, $);
  }
  const title = $(".title > a");
  let subtext = $(".subtext").text().replace(/\s+/g, " ");
  const href = title.attr("href");
  if (title.text() && subtext && href) {
    subtext = subtext.replace(/\| hide \| past \| web /g, "");
    subtext = subtext.replace(/\| favorite/g, "");
    return util.format("%s (%s) %s", title.text(), href, subtext);
  }
  return parse_generic(url_path, $);
}

function parse_reddit(url_path, $) {
  if (url_path.match("^\\/r\\/\\w+\\/comments/\\d+") === null) {
    return parse_generic(url_path, $);
  }
  const thing = $("#siteTable div.thing");
  let href = thing.attr("data-url");
  const author = thing.attr("data-author");
  const title = $("#siteTable div.thing div.entry p.title a.title").text();
  const time = $("#siteTable div.thing div.entry p.tagline time").text();
  const comments = $("#siteTable div.thing div.entry ul li.first a.comments").text();
  const score = $("#siteTable div.thing div.unvoted div.score.unvoted").text();

  if (title && time && comments && score) {
    const parsed_url = url.parse(href);
    // debugger;
    if (parsed_url.host) {
      href = util.format("(%s) ", href);
    } else {
      href = "";
    }
    return util.format("%s %s| submitted %s by %s | %s points, %s", title, href, time, author, score, comments);
  }
  return parse_generic(url_path, $);
}

function parse_twitter(url_path, $) {
  if (url_path.match("^\\/\\w+\\/status\\/\\d+") === null) {
    return parse_generic(url_path, $);
  }

  // TODO: only do this for paths that make sense
  const username = $("div.permalink-tweet-container div.permalink-header a > span.username.js-action-profile-name > b").text();
  const title = textify($("div.permalink-tweet-container p.tweet-text"), function (elems) {
    return elems = $(elems).not(".invisible");
  }, " ");
  const retweets = $("div.tweet-stats-container > ul.stats > li.js-stat-count.js-stat-retweets.stat-count > a > strong").text().replace(/\s/g, "");
  const favorites = $("div.tweet-stats-container > ul.stats > li.js-stat-count.js-stat-favorites.stat-count > a > strong").text().replace(/\s/g, "");

  return util.format("<@%s> %s (%s retweets, %s favorites)", username, title, retweets || 0, favorites || 0);
}

function parse_youtube(url_path, $) {
  // Durations are ISO 8601 format: "PT48M42S"
  const duration_regex = /^PT(?:(\d+)H)?(?:(\d+)M)?(\d+)S$/;

  if (url_path.match("^\\/watch") === null) {
    return parse_generic(url_path, $);
  }

  // TODO: only do this for paths that make sense
  const title = $("meta[itemprop=name]").attr("content");
  const views = $("#watch7-views-info > div.watch-view-count").text().split(" ")[0] || 0;
  let likes = $("#watch-header .like-button-renderer span.yt-uix-button-content").first().text().replace(/[\s,]/g, "") || 0;
  let dislikes = $("#watch-header .like-button-renderer span.yt-uix-button-content").get(3);
  dislikes = $(dislikes).text().replace(/[\s,]/g, "") || 0;
  likes = parseInt(likes, 10);
  dislikes = parseInt(dislikes, 10);
  const rating = Math.round(100 * likes / (likes + dislikes));
  let duration = $("meta[itemprop=duration]").attr("content");
  let matches = duration_regex.exec(duration);
  if (matches) {
    matches = {
      hours: parseInt(matches[1], 10),
      minutes: parseInt(matches[2], 10),
      seconds: parseInt(matches[3], 10),
    };
    // Youtube often sets hours to zero and minutes to >= 60
    if (matches.minutes >= 60) {
      matches.hours = Math.floor(matches.minutes / 60);
      matches.minutes = matches.minutes % 60;
    }
    if (matches.minutes < 10) {
      matches.minutes = "0" + matches.minutes;
    }
    if (matches.seconds < 10) {
      matches.seconds = "0" + matches.seconds;
    }
    duration = util.format("%s:%s", matches.minutes, matches.seconds);
    if (matches.hours) {
      duration = util.format("%s:%s", matches.hours, duration);
    }
  } else {
    duration = "";
  }
  return util.format("%s %s %s views %s%% like", title, duration, views, rating);
}

function parse(msg_url, body) {
  // This can throw. Caught in describe_url()
  const $ = cheerio.load(body);

  const parsed_url = url.parse(msg_url);
  // So hacky
  const domain = parsed_url.hostname.split(".").slice(-2).join(".");
  const f = registered_domains[domain];
  let title;
  if (f) {
    title = f(parsed_url.path, $);
  } else {
    title = parse_generic(parsed_url.path, $);
  }

  return title.replace(/[\r\n]/g, " ").trim();
}

function describe_url(msg_url, cb) {
  let req_len = 0;
  const req = request.get(msg_url, function (err, response, body) {
    if (err) {
      return cb(err, body || response);
    }

    let title;
    if (response.statusCode >= 400) {
      title = util.format("%s", response.statusCode);
      return cb(null, title);
    }

    if (!body) {
      return cb("No body in response", response);
    }

    try {
      title = parse(msg_url, body);
    } catch (e) {
      return cb(e, title);
    }

    return cb(null, title);
  });
  req.on("data", function (d) {
    req_len += d.length;
    if (req_len > max_req_len) {
      req.destroy();
    }
  });
}

function register(domain, f) {
  registered_domains[domain] = f;
}

register("github.com", parse_github);
register("ycombinator.com", parse_hn);
register("reddit.com", parse_reddit);
register("twitter.com", parse_twitter);
register("youtube.com", parse_youtube);

module.exports = {
  describe_url: describe_url,
  parse: parse,
  parse_generic: parse_generic,
  register: register,
};
<commit_msg>Fix parsing of Twitter usernames. Don't try to parse mobile.twitter.com<commit_after>"use strict";

const url = require("url");
const util = require("util");

const cheerio = require("cheerio");
let request = require("request");

const registered_domains = {};

const max_req_len = 1000000; // 1MB

request = request.defaults({
  sendImmediately: true,
  timeout: 10000,
  headers: {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
    "Accept" :"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.8",
    "Cache-Control": "max-age=0",
  }
});

// Modified/extended version of Cheerio's elems.text()
function textify(elems, filter, sep) {
  sep = sep || "";
  let ret = "";
  elems = filter(elems);
  const len = elems.length;

  for (let i = 0; i < len; i++) {
    let elem = elems[i];
    if (elem.type === "text") {
      ret += elem.data + sep;
    } else if (elem.children && elem.type !== "comment") {
      if (elem.name === "img" && elem.attribs.alt && elem.attribs.alt.length < 3) {
        // Javascript strings are UCS-2 or whatever, so it counts one emoji as 2ish chars
        ret += elem.attribs.alt;
      } else {
        ret += textify(elem.children, filter, sep);
      }
    }
  }

  return ret;
}

function parse_generic(url_path, $) {
  let title = $("html head title").text();

  if (title.length > 100) {
    title = title.slice(0, 100);
    title += "...";
  }

  return title;
}

function parse_github(url_path, $) {
  if (url_path.match("^\\/[\\w-]+\\/[\\w-]+\\/?$") === null) {
    return parse_generic(url_path, $);
  }

  let ul = $("ul.pagehead-actions > li > a.js-social-count");
  const stargazers = $(ul[0]).text().replace(/\s/g, "");
  ul = $("ul.pagehead-actions > li > a.social-count");
  let forks = $(ul[2]).text().replace(/\s/g, "");
  // Horrible hack. Github sometimes switches the order of these.
  if (forks === stargazers) {
    forks = $(ul[1]).text().replace(/\s/g, "");
  }
  const description = $("div.repository-meta").text().trim();
  const name = $("h1.public > strong > a").text();
  if (name) {
    return util.format("%s (%s stars %s forks) %s", name, stargazers, forks, description);
  }
  return parse_generic(url_path, $);
}

function parse_hn(url_path, $) {
  if (url_path.match("^\\/item\\?id=\\d+") === null) {
    return parse_generic(url_path, $);
  }
  const title = $(".title > a");
  let subtext = $(".subtext").text().replace(/\s+/g, " ");
  const href = title.attr("href");
  if (title.text() && subtext && href) {
    subtext = subtext.replace(/\| hide \| past \| web /g, "");
    subtext = subtext.replace(/\| favorite/g, "");
    return util.format("%s (%s) %s", title.text(), href, subtext);
  }
  return parse_generic(url_path, $);
}

function parse_reddit(url_path, $) {
  if (url_path.match("^\\/r\\/\\w+\\/comments/\\d+") === null) {
    return parse_generic(url_path, $);
  }
  const thing = $("#siteTable div.thing");
  let href = thing.attr("data-url");
  const author = thing.attr("data-author");
  const title = $("#siteTable div.thing div.entry p.title a.title").text();
  const time = $("#siteTable div.thing div.entry p.tagline time").text();
  const comments = $("#siteTable div.thing div.entry ul li.first a.comments").text();
  const score = $("#siteTable div.thing div.unvoted div.score.unvoted").text();

  if (title && time && comments && score) {
    const parsed_url = url.parse(href);
    // debugger;
    if (parsed_url.host) {
      href = util.format("(%s) ", href);
    } else {
      href = "";
    }
    return util.format("%s %s| submitted %s by %s | %s points, %s", title, href, time, author, score, comments);
  }
  return parse_generic(url_path, $);
}

function parse_twitter(url_path, $) {
  const matches = new RegExp("^\\/(\\w+)\\/status\\/\\d+").exec(url_path);
  if (!matches) {
    return parse_generic(url_path, $);
  }
  const username = matches[1];
  const title = textify($("div.permalink-tweet-container p.tweet-text"), function (elems) {
    return elems = $(elems).not(".invisible");
  }, " ");
  const retweets = $("div.tweet-stats-container > ul.stats > li.js-stat-count.js-stat-retweets.stat-count > a > strong").text().replace(/\s/g, "");
  const favorites = $("div.tweet-stats-container > ul.stats > li.js-stat-count.js-stat-favorites.stat-count > a > strong").text().replace(/\s/g, "");

  return util.format("<@%s> %s (%s retweets, %s favorites)", username, title, retweets || 0, favorites || 0);
}

function parse_youtube(url_path, $) {
  // Durations are ISO 8601 format: "PT48M42S"
  const duration_regex = /^PT(?:(\d+)H)?(?:(\d+)M)?(\d+)S$/;

  if (url_path.match("^\\/watch") === null) {
    return parse_generic(url_path, $);
  }

  // TODO: only do this for paths that make sense
  const title = $("meta[itemprop=name]").attr("content");
  const views = $("#watch7-views-info > div.watch-view-count").text().split(" ")[0] || 0;
  let likes = $("#watch-header .like-button-renderer span.yt-uix-button-content").first().text().replace(/[\s,]/g, "") || 0;
  let dislikes = $("#watch-header .like-button-renderer span.yt-uix-button-content").get(3);
  dislikes = $(dislikes).text().replace(/[\s,]/g, "") || 0;
  likes = parseInt(likes, 10);
  dislikes = parseInt(dislikes, 10);
  const rating = Math.round(100 * likes / (likes + dislikes));
  let duration = $("meta[itemprop=duration]").attr("content");
  let matches = duration_regex.exec(duration);
  if (matches) {
    matches = {
      hours: parseInt(matches[1], 10),
      minutes: parseInt(matches[2], 10),
      seconds: parseInt(matches[3], 10),
    };
    // Youtube often sets hours to zero and minutes to >= 60
    if (matches.minutes >= 60) {
      matches.hours = Math.floor(matches.minutes / 60);
      matches.minutes = matches.minutes % 60;
    }
    if (matches.minutes < 10) {
      matches.minutes = "0" + matches.minutes;
    }
    if (matches.seconds < 10) {
      matches.seconds = "0" + matches.seconds;
    }
    duration = util.format("%s:%s", matches.minutes, matches.seconds);
    if (matches.hours) {
      duration = util.format("%s:%s", matches.hours, duration);
    }
  } else {
    duration = "";
  }
  return util.format("%s %s %s views %s%% like", title, duration, views, rating);
}

function parse(msg_url, body) {
  // This can throw. Caught in describe_url()
  const $ = cheerio.load(body);

  const parsed_url = url.parse(msg_url);
  // So hacky
  const domain = parsed_url.hostname.split(".").slice(-2).join(".");
  const f = registered_domains[domain];
  let title;
  if (f) {
    title = f(parsed_url.path, $);
  } else {
    title = parse_generic(parsed_url.path, $);
  }

  return title.replace(/[\r\n]/g, " ").trim();
}

function describe_url(msg_url, cb) {
  let req_len = 0;
  const req = request.get(msg_url, function (err, response, body) {
    if (err) {
      return cb(err, body || response);
    }

    let title;
    if (response.statusCode >= 400) {
      title = util.format("%s", response.statusCode);
      return cb(null, title);
    }

    if (!body) {
      return cb("No body in response", response);
    }

    try {
      title = parse(msg_url, body);
    } catch (e) {
      return cb(e, title);
    }

    return cb(null, title);
  });
  req.on("data", function (d) {
    req_len += d.length;
    if (req_len > max_req_len) {
      req.destroy();
    }
  });
}

function register(domain, f) {
  registered_domains[domain] = f;
}

register("github.com", parse_github);
register("ycombinator.com", parse_hn);
register("reddit.com", parse_reddit);
register("mobile.twitter.com", parse_generic);
register("twitter.com", parse_twitter);
register("youtube.com", parse_youtube);

module.exports = {
  describe_url: describe_url,
  parse: parse,
  parse_generic: parse_generic,
  register: register,
};
<|endoftext|>


<commit_before>/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

var exec      = require('cordova/exec'),
    ua        = navigator.userAgent.toLowerCase(),
    isAndroid = !window.Windows && ua.indexOf('android') > -1,
    mailto    = 'mailto:';

/**
 * List of all registered mail app aliases.
 */
exports.aliases = {
    gmail:   isAndroid ? 'com.google.android.gm' : 'googlegmail://co',
    outlook: isAndroid ? 'com.microsoft.office.outlook' : 'ms-outlook://compose'
};

/**
 * List of all available options with their default value.
 *
 * @return [ Object ]
 */
exports.getDefaults = function () {
    return {
        app:           mailto,
        subject:       '',
        body:          '',
        to:            [],
        cc:            [],
        bcc:           [],
        attachments:   [],
        isHtml:        true,
        chooserHeader: 'Open with'
    };
};

/**
 * Informs if the app has the needed permission.
 *
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope of the callback.
 *
 * @return [ Void ]
 */
exports.hasPermission = function(callback, scope) {
    var fn = this.createCallbackFn(callback, scope);

    if (!isAndroid) {
        if (fn) fn(true);
        return;
    }

    exec(fn, null, 'EmailComposer','hasPermission', []);
 };

/**
 * Request permission if not already granted.
 *
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope of the callback.
 *
 * @return [ Void ]
 */
exports.requestPermission = function(callback, scope) {
    var fn = this.createCallbackFn(callback, scope);

    if (!isAndroid) {
        if (fn) fn(true);
        return;
    }

    exec(fn, null, 'EmailComposer','requestPermission', []);
};

/**
 * Verifies if sending emails is supported on the device.
 *
 * @param [ String ]   app      An optional app id or uri scheme.
 *                              Defaults to mailto.
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope of the callback.
 *
 * @return [ Void ]
 */
exports.isAvailable = function (app, callback, scope) {

    if (typeof callback != 'function') {
        scope    = null;
        callback = app;
        app      = mailto;
    }

    var fn  = this.createCallbackFn(callback, scope);
        app = app || mailto;

    if (this.aliases.hasOwnProperty(app)) {
        app = this.aliases[app];
    }

    exec(fn, null, 'EmailComposer', 'isAvailable', [app]);
};

/**
 * Verifies if sending emails is supported on the device.
 *
 * @param [ String ]   app      An optional app id or uri scheme.
 *                              Defaults to mailto.
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope of the callback.
 *
 * @return [ Void ]
 */
exports.isAvailable2 = function (app, callback, scope) {

    if (typeof callback != 'function') {
        scope    = null;
        callback = app;
        app      = mailto;
    }

    var fn  = this.createCallbackFn(callback, scope), fn2;
        app = app || mailto;

    if (this.aliases.hasOwnProperty(app)) {
        app = this.aliases[app];
    }

    if (fn) {
        fn2 = function (a, b) { fn(b, a); };
    }

    exec(fn2, null, 'EmailComposer', 'isAvailable', [app]);
};

/**
 * Displays the email composer pre-filled with data.
 *
 * @param [ Object ]   options  The email properties like the body,...
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope of the callback.
 *
 * @return [ Void ]
 */
exports.open = function (options, callback, scope) {

    if (typeof options == 'function') {
        scope    = callback;
        callback = options;
        options  = {};
    }

    var fn      = this.createCallbackFn(callback, scope);
        options = this.mergeWithDefaults(options || {});

    if (!isAndroid && options.app != mailto && fn) {
        this.registerCallbackForScheme(fn);
    }

    exec(fn, null, 'EmailComposer', 'open', [options]);
};

/**
 * Adds a new mail app alias.
 *
 * @param [ String ] alias   The alias name.
 * @param [ String ] package The package name.
 *
 * @return [ Void ]
 */
exports.addAlias = function (alias, package) {
    this.aliases[alias] = package;
};

/**
 * Alias für `open()`.
 */
exports.openDraft = function () {
    this.open.apply(this, arguments);
};

/**
 * @private
 *
 * Merge settings with default values.
 *
 * @param [ Object ] options The custom options
 *
 * @retrun [ Object ] Default values merged with custom values.
 */
exports.mergeWithDefaults = function (options) {
    var defaults = this.getDefaults();

    if (options.hasOwnProperty('isHTML')) {
        options.isHtml = options.isHTML;
    }

    if (!options.hasOwnProperty('isHtml')) {
        options.isHtml = defaults.isHtml;
    }

    if (options.hasOwnProperty('app')) {
        var package = this.aliases[options.app];
        options.app = package || options.app;
    }

    options.subject       = String(options.subject || defaults.subject);
    options.body          = String(options.body || defaults.body);
    options.chooserHeader = String(options.chooserHeader || defaults.chooserHeader);
    options.to            = options.to || defaults.to;
    options.cc            = options.cc || defaults.cc;
    options.bcc           = options.bcc || defaults.bcc;
    options.isHtml        = !!options.isHtml;

    if (!Array.isArray(options.to)) {
        options.to = [options.to];
    }

    if (!Array.isArray(options.cc)) {
        options.cc = [options.cc];
    }

    if (!Array.isArray(options.bcc)) {
        options.bcc = [options.bcc];
    }

    return options;
};

/**
 * @private
 *
 * Creates a callback, which will be executed
 * within a specific scope.
 *
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope for the function.
 *
 * @return [ Function ] The new callback function
 */
exports.createCallbackFn = function (callback, scope) {

    if (typeof callback !== 'function')
        return;

    return function () {
        callback.apply(scope || this, arguments);
    };
};

/**
 * @private
 *
 * Register an Eventlistener on resume-Event to
 * execute callback after open a draft.
 *
 * @return [ Void ]
 */
exports.registerCallbackForScheme = function (fn) {

    var callback = function () {
        fn();
        document.removeEventListener('resume',callback);
    };

    document.addEventListener('resume', callback, false);
};
<commit_msg>IOS Composer not starting with 0.8.14 [fixes #289]<commit_after>/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

var exec      = require('cordova/exec'),
    ua        = navigator.userAgent.toLowerCase(),
    isAndroid = !window.Windows && ua.indexOf('android') > -1,
    mailto    = 'mailto:';

/**
 * List of all registered mail app aliases.
 */
exports.aliases = {
    gmail:   isAndroid ? 'com.google.android.gm' : 'googlegmail://co',
    outlook: isAndroid ? 'com.microsoft.office.outlook' : 'ms-outlook://compose'
};

/**
 * List of all available options with their default value.
 *
 * @return [ Object ]
 */
exports.getDefaults = function () {
    return {
        app:           mailto,
        subject:       '',
        body:          '',
        to:            [],
        cc:            [],
        bcc:           [],
        attachments:   [],
        isHtml:        true,
        chooserHeader: 'Open with'
    };
};

/**
 * Informs if the app has the needed permission.
 *
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope of the callback.
 *
 * @return [ Void ]
 */
exports.hasPermission = function(callback, scope) {
    var fn = this.createCallbackFn(callback, scope);

    if (!isAndroid) {
        if (fn) fn(true);
        return;
    }

    exec(fn, null, 'EmailComposer','hasPermission', []);
 };

/**
 * Request permission if not already granted.
 *
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope of the callback.
 *
 * @return [ Void ]
 */
exports.requestPermission = function(callback, scope) {
    var fn = this.createCallbackFn(callback, scope);

    if (!isAndroid) {
        if (fn) fn(true);
        return;
    }

    exec(fn, null, 'EmailComposer','requestPermission', []);
};

/**
 * Verifies if sending emails is supported on the device.
 *
 * @param [ String ]   app      An optional app id or uri scheme.
 *                              Defaults to mailto.
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope of the callback.
 *
 * @return [ Void ]
 */
exports.isAvailable = function (app, callback, scope) {

    if (typeof callback != 'function') {
        scope    = null;
        callback = app;
        app      = mailto;
    }

    var fn  = this.createCallbackFn(callback, scope);
        app = app || mailto;

    if (this.aliases.hasOwnProperty(app)) {
        app = this.aliases[app];
    }

    exec(fn, null, 'EmailComposer', 'isAvailable', [app]);
};

/**
 * Verifies if sending emails is supported on the device.
 *
 * @param [ String ]   app      An optional app id or uri scheme.
 *                              Defaults to mailto.
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope of the callback.
 *
 * @return [ Void ]
 */
exports.isAvailable2 = function (app, callback, scope) {

    if (typeof callback != 'function') {
        scope    = null;
        callback = app;
        app      = mailto;
    }

    var fn  = this.createCallbackFn(callback, scope), fn2;
        app = app || mailto;

    if (this.aliases.hasOwnProperty(app)) {
        app = this.aliases[app];
    }

    if (fn) {
        fn2 = function (a, b) { fn(b, a); };
    }

    exec(fn2, null, 'EmailComposer', 'isAvailable', [app]);
};

/**
 * Displays the email composer pre-filled with data.
 *
 * @param [ Object ]   options  The email properties like the body,...
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope of the callback.
 *
 * @return [ Void ]
 */
exports.open = function (options, callback, scope) {

    if (typeof options == 'function') {
        scope    = callback;
        callback = options;
        options  = {};
    }

    var fn      = this.createCallbackFn(callback, scope);
        options = this.mergeWithDefaults(options || {});

    if (!isAndroid && options.app != mailto && fn) {
        this.registerCallbackForScheme(fn);
    }

    exec(fn, null, 'EmailComposer', 'open', [options]);
};

/**
 * Adds a new mail app alias.
 *
 * @param [ String ] alias   The alias name.
 * @param [ String ] package The package name.
 *
 * @return [ Void ]
 */
exports.addAlias = function (alias, package) {
    this.aliases[alias] = package;
};

/**
 * Alias für `open()`.
 */
exports.openDraft = function () {
    this.open.apply(this, arguments);
};

/**
 * @private
 *
 * Merge settings with default values.
 *
 * @param [ Object ] options The custom options
 *
 * @retrun [ Object ] Default values merged with custom values.
 */
exports.mergeWithDefaults = function (options) {
    var defaults = this.getDefaults();

    if (options.hasOwnProperty('isHTML')) {
        options.isHtml = options.isHTML;
    }

    if (!options.hasOwnProperty('isHtml')) {
        options.isHtml = defaults.isHtml;
    }

    if (options.hasOwnProperty('app')) {
        options.app = this.aliases[options.app];
    }

    options.app           = String(options.app || defaults.app);
    options.subject       = String(options.subject || defaults.subject);
    options.body          = String(options.body || defaults.body);
    options.chooserHeader = String(options.chooserHeader || defaults.chooserHeader);
    options.to            = options.to || defaults.to;
    options.cc            = options.cc || defaults.cc;
    options.bcc           = options.bcc || defaults.bcc;
    options.isHtml        = !!options.isHtml;

    if (!Array.isArray(options.to)) {
        options.to = [options.to];
    }

    if (!Array.isArray(options.cc)) {
        options.cc = [options.cc];
    }

    if (!Array.isArray(options.bcc)) {
        options.bcc = [options.bcc];
    }

    return options;
};

/**
 * @private
 *
 * Creates a callback, which will be executed
 * within a specific scope.
 *
 * @param [ Function ] callback The callback function.
 * @param [ Object ]   scope    The scope for the function.
 *
 * @return [ Function ] The new callback function
 */
exports.createCallbackFn = function (callback, scope) {

    if (typeof callback !== 'function')
        return;

    return function () {
        callback.apply(scope || this, arguments);
    };
};

/**
 * @private
 *
 * Register an Eventlistener on resume-Event to
 * execute callback after open a draft.
 *
 * @return [ Void ]
 */
exports.registerCallbackForScheme = function (fn) {

    var callback = function () {
        fn();
        document.removeEventListener('resume',callback);
    };

    document.addEventListener('resume', callback, false);
};
<|endoftext|>


<commit_before>cordova.define("cordova-plugin-ios-gpumediaplayer.GPUMediaPlayer", function(require, exports, module) {
/*global cordova,window,console*/
/**
 * A GPU Media Player plugin for Cordova
 *
 * Developed by John Weaver for Varsity Software
 */

    var GPUMediaPlayer = function ()
    {

    };

    GPUMediaPlayer.prototype.start = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaURL: options.mediaURL ? options.mediaURL : null,
            mediaOrientation: options.mediaOrientation ? options.mediaOrientation : 0,
            mediaType: options.mediaType ? options.mediaType : 0,

            mediaPosX: options.mediaPosX ? options.mediaPosX : 0,
            mediaPosY: options.mediaPosY ? options.mediaPosY : 0,
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,

            framesPerSecond: options.framesPerSecond ? options.framesPerSecond : 0,

            playerPosX: options.playerPosX ? options.playerPosX : 0,
            playerPosY: options.playerPosY ? options.playerPosY : 0,
            playerWidth: options.playerWidth ? options.playerWidth : 0,
            playerHeight: options.playerHeight ? options.playerHeight : 0,

            captionEnabled: options.captionEnabled ? options.captionEnabled : 0,
            captionText: options.captionText ? options.captionText : null,
            captionFontSize: options.captionFontSize ? options.captionFontSize : 0,

            frameEnabled: options.frameEnabled ? options.frameEnabled : 0,
            frameShapeURL: options.frameShapeURL ? options.frameShapeURL : null,
            frameThemeURL: options.frameThemeURL ? options.frameThemeURL : null,

            overlayEnabled: options.overlayEnabled ? options.overlayEnabled : 0,
            overlayURL: options.overlayURL ? options.overlayURL : null,

            loop: options.loop ? options.loop : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "start", [params]);

    };

    GPUMediaPlayer.prototype.pause = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "pause", null);
    };

    GPUMediaPlayer.prototype.play = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "play", null);
    };

    GPUMediaPlayer.prototype.stop = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "stop", null);
    };

    GPUMediaPlayer.prototype.restart = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "restart", null);
    };

    GPUMediaPlayer.prototype.hide = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "hide", null);
    };

    GPUMediaPlayer.prototype.show = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "show", null);
    };

    GPUMediaPlayer.prototype.destroy = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "destroy", null);
    };

    GPUMediaPlayer.prototype.seek = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {

            seekTo: options.seekTo ? options.seekTo : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "seek", [params]);
    };

    GPUMediaPlayer.prototype.save = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaURL: options.mediaURL ? options.mediaURL : null,
            mediaType: options.mediaType ? options.mediaType : 0,
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,
            avgBitRate: options.avgBitRate ? options.avgBitRate : 0,
            gifFramesPerSecond: options.gifFramesPerSecond ? options.gifFramesPerSecond : 0,
            gifPlaybackSpeed: options.gifPlaybackSpeed ? options.gifPlaybackSpeed : 0,
            gifMaxDuration: options.gifMaxDuration ? options.gifMaxDuration : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "save", [params]);
    };

    GPUMediaPlayer.prototype.addSticker = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            stickerURL: options.stickerURL ? options.stickerURL : null,
            stickerID: options.stickerID ? options.stickerID : 0,
            stickerPosX: options.stickerPosX ? options.stickerPosX : 0,
            stickerPosY: options.stickerPosY ? options.stickerPosY : 0,
            stickerWidth: options.stickerWidth ? options.stickerWidth : 0,
            stickerHeight: options.stickerHeight ? options.stickerHeight : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "addSticker", [params]);
    };

    GPUMediaPlayer.prototype.addLabel = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            labelID: options.labelID ? options.labelID : 0,
            labelPosX: options.labelPosX ? options.labelPosX : 0,
            labelPosY: options.labelPosY ? options.labelPosY : 0,
            labelWidth: options.labelWidth ? options.labelWidth : 0,
            labelHeight: options.labelHeight ? options.labelHeight : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "addLabel", [params]);
    };

    GPUMediaPlayer.prototype.updateLabel = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            //labelID: options.labelID ? options.labelID : 0,
            labelColor: options.labelColor ? options.labelColor : null,
            labelSize: options.labelSize ? options.labelSize : 0,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "updateLabel", [params]);
    };

    GPUMediaPlayer.prototype.updateSticker = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            //stickerID: options.stickerID ? options.stickerID : 0,
            stickerColor: options.stickerColor ? options.stickerColor : null,
            stickerSize: options.stickerSize ? options.stickerSize : 0,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "updateSticker", [params]);
    };

    GPUMediaPlayer.prototype.changeFilter = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            filterID: options.filterID ? options.filterID : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "changeFilter", [params]);
    };

    GPUMediaPlayer.prototype.changeFrame = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,
            frameShapeURL: options.frameShapeURL ? options.frameShapeURL : null,
            frameThemeURL: options.frameThemeURL ? options.frameThemeURL : null,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "changeFrame", [params]);
    };

    window.gpuMediaPlayer = new GPUMediaPlayer();

});
<commit_msg>Update gpumediaplayer.js<commit_after>

    var GPUMediaPlayer = function ()
    {

    };

    GPUMediaPlayer.prototype.start = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaURL: options.mediaURL ? options.mediaURL : null,
            mediaOrientation: options.mediaOrientation ? options.mediaOrientation : 0,
            mediaType: options.mediaType ? options.mediaType : 0,

            mediaPosX: options.mediaPosX ? options.mediaPosX : 0,
            mediaPosY: options.mediaPosY ? options.mediaPosY : 0,
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,

            framesPerSecond: options.framesPerSecond ? options.framesPerSecond : 0,

            playerPosX: options.playerPosX ? options.playerPosX : 0,
            playerPosY: options.playerPosY ? options.playerPosY : 0,
            playerWidth: options.playerWidth ? options.playerWidth : 0,
            playerHeight: options.playerHeight ? options.playerHeight : 0,

            captionEnabled: options.captionEnabled ? options.captionEnabled : 0,
            captionText: options.captionText ? options.captionText : null,
            captionFontSize: options.captionFontSize ? options.captionFontSize : 0,

            frameEnabled: options.frameEnabled ? options.frameEnabled : 0,
            frameShapeURL: options.frameShapeURL ? options.frameShapeURL : null,
            frameThemeURL: options.frameThemeURL ? options.frameThemeURL : null,

            overlayEnabled: options.overlayEnabled ? options.overlayEnabled : 0,
            overlayURL: options.overlayURL ? options.overlayURL : null,

            loop: options.loop ? options.loop : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "start", [params]);

    };

    GPUMediaPlayer.prototype.pause = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "pause", null);
    };

    GPUMediaPlayer.prototype.play = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "play", null);
    };

    GPUMediaPlayer.prototype.stop = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "stop", null);
    };

    GPUMediaPlayer.prototype.restart = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "restart", null);
    };

    GPUMediaPlayer.prototype.hide = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "hide", null);
    };

    GPUMediaPlayer.prototype.show = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "show", null);
    };

    GPUMediaPlayer.prototype.destroy = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "destroy", null);
    };

    GPUMediaPlayer.prototype.seek = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {

            seekTo: options.seekTo ? options.seekTo : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "seek", [params]);
    };

    GPUMediaPlayer.prototype.save = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaURL: options.mediaURL ? options.mediaURL : null,
            mediaType: options.mediaType ? options.mediaType : 0,
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,
            avgBitRate: options.avgBitRate ? options.avgBitRate : 0,
            gifFramesPerSecond: options.gifFramesPerSecond ? options.gifFramesPerSecond : 0,
            gifPlaybackSpeed: options.gifPlaybackSpeed ? options.gifPlaybackSpeed : 0,
            gifMaxDuration: options.gifMaxDuration ? options.gifMaxDuration : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "save", [params]);
    };

    GPUMediaPlayer.prototype.addSticker = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            stickerURL: options.stickerURL ? options.stickerURL : null,
            stickerID: options.stickerID ? options.stickerID : 0,
            stickerPosX: options.stickerPosX ? options.stickerPosX : 0,
            stickerPosY: options.stickerPosY ? options.stickerPosY : 0,
            stickerWidth: options.stickerWidth ? options.stickerWidth : 0,
            stickerHeight: options.stickerHeight ? options.stickerHeight : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "addSticker", [params]);
    };

    GPUMediaPlayer.prototype.addLabel = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            labelID: options.labelID ? options.labelID : 0,
            labelPosX: options.labelPosX ? options.labelPosX : 0,
            labelPosY: options.labelPosY ? options.labelPosY : 0,
            labelWidth: options.labelWidth ? options.labelWidth : 0,
            labelHeight: options.labelHeight ? options.labelHeight : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "addLabel", [params]);
    };

    GPUMediaPlayer.prototype.updateLabel = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            //labelID: options.labelID ? options.labelID : 0,
            labelColor: options.labelColor ? options.labelColor : null,
            labelSize: options.labelSize ? options.labelSize : 0,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "updateLabel", [params]);
    };

    GPUMediaPlayer.prototype.updateSticker = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            //stickerID: options.stickerID ? options.stickerID : 0,
            stickerColor: options.stickerColor ? options.stickerColor : null,
            stickerSize: options.stickerSize ? options.stickerSize : 0,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "updateSticker", [params]);
    };

    GPUMediaPlayer.prototype.changeFilter = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            filterID: options.filterID ? options.filterID : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "changeFilter", [params]);
    };

    GPUMediaPlayer.prototype.changeFrame = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,
            frameShapeURL: options.frameShapeURL ? options.frameShapeURL : null,
            frameThemeURL: options.frameThemeURL ? options.frameThemeURL : null,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "changeFrame", [params]);
    };

    window.gpuMediaPlayer = new GPUMediaPlayer();
<|endoftext|>


<commit_before>
// add event handlers when the page has loaded
$(document).ready(function(){

    new_file = $("#new_file");

    // remove filesystem path from selected file name
	new_file.change(function(){
		$("#file-label").text(new_file.val().replace(/^.*\\/, "").replace(/^.*\//, ""));});

    // respond to expires checkbox
	$("#expires").change(function(){
        c = $("#clicks");
		if($(this).is(":checked")){
						c.prop("disabled",false);
						c.prop("value",1);
		} else {
				c.prop("disabled",true);
				c.prop("value","");
		}});

    // URL mode is default
	$("#file-group").attr("disabled", true);
	$("#file-button").attr("disabled", true);

    // respond to URL vs file mode
	$("input[name='sub_type']").change(function (){
		radioValue = $(this).val();
        url = $("#new_url");
        glyph = $("#newsub_glyph");

        // disable URL input, enable file input
		if(radioValue === "file"){
				url.prop("value","");
				url.prop("disabled",true);
				url.prop("placeholder","");

				new_file.prop("disabled",false);
				$("#file-group").attr("disabled", false);
				$("#file-button").attr("disabled", false);
				$("#file-label").text("No file selected");

				glyph.removeClass("glyphicon-link");
				glyph.addClass("glyphicon-cloud-upload");
		} else {
        // disable file input, enable URL input
				url.prop("value","");
				url.prop("disabled",false);
				url.prop("placeholder","http://www.example.com/");

				new_file.prop("disabled",true);
				$("#file-group").attr("disabled", true);
				$("#file-button").attr("disabled", true);
				$("#file-label").text("")

				new_file.wrap('<form>').closest('form').get(0).reset();
				new_file.unwrap();

			    glyph.removeClass("glyphicon-cloud-upload");
				glyph.addClass("glyphicon-link");
		}
    });

    // prevent duplicate file submissions
    $("#new_submit").submit(function(){
		type = $("input[name='sub_type']:checked").val();
		if(type == "file"){
            newsub = $("#newsub");

				newsub.html(newsub.html().replace("Submit","Uploading..."));
				newsub.prop("disabled",true);
		} else if(type == "url"){

		}

    });

    // super secret easter egg
    var mouseDist = 0;
    var lastPos = [0, 0];
    var text = [
        "I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration. I will face my fear. I will permit it to pass over me and through me. And when it has gone past I will turn the inner eye to see its path. Where the fear has gone there will be nothing. Only I will remain.",
        "Once men turned their thinking over to machines in the hope that this would set them free. But that only permitted other men with machines to enslave them.",
        "If you ask 'Should we be in space?' you ask a nonsense question. We are in space. We will be in space.",
        "Those who believe in telekinetics, raise my hand.",
        "Advertising is legalized lying.",
        "The path of least resistance is the path of the loser.",
        "A learning experience is one of those things that say, 'You know that thing you just did? Don't do that'.",
        "Time is an illusion. Lunchtime doubly so.",
        "I do not fear computers. I fear the lack of them.",
        "Violence is the last refuge of the incompetent.",
        "Insanity is relative. It depends on who has who locked in what cage.",
        "The 'Net' is a waste of time, and that's exactly what's right about it.",
        "The future is not google-able.",
        "Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn.",
        "Fool me once, shame on you. Fool me twice, shame on me.",
        "You see, in this world there's two kinds of people, my friend: Those with loaded guns and those who dig. You dig.",
        "I'm from buenos aires, and I say kill them all!",
        "There are no dangerous weapons; there are only dangerous men.",
        "Bazinga",
        "Smee! Do something intelligent!",
        "That's a paddlin'",
        "Just because I don't care doesn't mean I don't understand.",
        "We will forsake our countries. " +
            "We will leave our motherland behind us " +
            "and become one with this earth. We have " +
            "no nation, no philosophy, no ideology. " +
            "We go where we're needed, fighting, not " +
            "for government, but for ourselves. " +
            "We need no reason to fight. " +
            "We fight because we are needed. ",
        "Si vis pacem, para bellum.",
        "Get busy living, or get busy dying.",
        "By failing to prepare, you are preparing to fail.",
        "Life is either a great adventure or nothing.",
        "Electricity is really just organized lightning.",
        "The only thing necessary for the triumph of evil is that good men do nothing.",
        "There are countless ingredients that make up the human body and mind, like all the components that make up me as an individual with my own personality. Sure, I have a face and voice to distinguish myself from others, but my thoughts and memories are unique only to me, and I carry a sense of my own destiny. Each of those things are just a small part of it. I collect information to use in my own way. All of that blends to create a mixture that forms me and gives rise to my conscience.",
        "I reject your reality and substitute my own.",
        "In this moment, I am euphoric. Not because of any phony god’s blessing. But because, I am enlightened by my intelligence."
            ];

    var speech_anims = [
        //"Alert",
        "CheckingSomething",
        "Explain",
        "GetArtsy",
        "GetAttention",
        "GetTechy",
        "GetWizardy",
        "Thinking",
        "Wave"
            ];

    $(document).mousemove(function(event) {
        if(lastPos[0] > 0){
            mouseDist += Math.sqrt(
                Math.pow(
                    event.pageX - lastPos[0],
                    2.0
                    ) +
                Math.pow(
                    event.pageY - lastPos[1],
                    2.0
                )
            );
        }
        lastPos[0] = event.pageX;
        lastPos[1] = event.pageY;

        if(mouseDist >= 6000){
            $(document).unbind("mousemove");
            clippy.load('Clippy', function(agent){

                c = $("#form_container");
                p = c.position();
                a = $(".clippy");

                agent.moveTo(p.left + c.width()/2 - a.width()/2, p.top + c.height()/2 - a.height()/2);

                a.click(function(event){
                            agent.stop();
                            agent.play(speech_anims[Math.floor(Math.random() * speech_anims.length)]);
                            agent.speak(text[Math.floor(Math.random() * text.length)]);
                });

                agent.play('Greeting');
            });
        }
    });
});

// callbacks are fantastic
<commit_msg>added quotes<commit_after>
// add event handlers when the page has loaded
$(document).ready(function(){

    new_file = $("#new_file");

    // remove filesystem path from selected file name
	new_file.change(function(){
		$("#file-label").text(new_file.val().replace(/^.*\\/, "").replace(/^.*\//, ""));});

    // respond to expires checkbox
	$("#expires").change(function(){
        c = $("#clicks");
		if($(this).is(":checked")){
						c.prop("disabled",false);
						c.prop("value",1);
		} else {
				c.prop("disabled",true);
				c.prop("value","");
		}});

    // URL mode is default
	$("#file-group").attr("disabled", true);
	$("#file-button").attr("disabled", true);

    // respond to URL vs file mode
	$("input[name='sub_type']").change(function (){
		radioValue = $(this).val();
        url = $("#new_url");
        glyph = $("#newsub_glyph");

        // disable URL input, enable file input
		if(radioValue === "file"){
				url.prop("value","");
				url.prop("disabled",true);
				url.prop("placeholder","");

				new_file.prop("disabled",false);
				$("#file-group").attr("disabled", false);
				$("#file-button").attr("disabled", false);
				$("#file-label").text("No file selected");

				glyph.removeClass("glyphicon-link");
				glyph.addClass("glyphicon-cloud-upload");
		} else {
        // disable file input, enable URL input
				url.prop("value","");
				url.prop("disabled",false);
				url.prop("placeholder","http://www.example.com/");

				new_file.prop("disabled",true);
				$("#file-group").attr("disabled", true);
				$("#file-button").attr("disabled", true);
				$("#file-label").text("")

				new_file.wrap('<form>').closest('form').get(0).reset();
				new_file.unwrap();

			    glyph.removeClass("glyphicon-cloud-upload");
				glyph.addClass("glyphicon-link");
		}
    });

    // prevent duplicate file submissions
    $("#new_submit").submit(function(){
		type = $("input[name='sub_type']:checked").val();
		if(type == "file"){
            newsub = $("#newsub");

				newsub.html(newsub.html().replace("Submit","Uploading..."));
				newsub.prop("disabled",true);
		} else if(type == "url"){

		}

    });

    // super secret easter egg
    var mouseDist = 0;
    var lastPos = [0, 0];
    var text = [
        "I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration. I will face my fear. I will permit it to pass over me and through me. And when it has gone past I will turn the inner eye to see its path. Where the fear has gone there will be nothing. Only I will remain.",
        "Once men turned their thinking over to machines in the hope that this would set them free. But that only permitted other men with machines to enslave them.",
        "If you ask 'Should we be in space?' you ask a nonsense question. We are in space. We will be in space.",
        "Those who believe in telekinetics, raise my hand.",
        "Advertising is legalized lying.",
        "The path of least resistance is the path of the loser.",
        "A learning experience is one of those things that say, 'You know that thing you just did? Don't do that'.",
        "Time is an illusion. Lunchtime doubly so.",
        "I do not fear computers. I fear the lack of them.",
        "Violence is the last refuge of the incompetent.",
        "Insanity is relative. It depends on who has who locked in what cage.",
        "The 'Net' is a waste of time, and that's exactly what's right about it.",
        "The future is not google-able.",
        "Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn.",
        "Fool me once, shame on you. Fool me twice, shame on me.",
        "You see, in this world there's two kinds of people, my friend: Those with loaded guns and those who dig. You dig.",
        "I'm from buenos aires, and I say kill them all!",
        "There are no dangerous weapons; there are only dangerous men.",
        "Bazinga",
        "Smee! Do something intelligent!",
        "That's a paddlin'",
        "Just because I don't care doesn't mean I don't understand.",
        "We will forsake our countries. " +
            "We will leave our motherland behind us " +
            "and become one with this earth. We have " +
            "no nation, no philosophy, no ideology. " +
            "We go where we're needed, fighting, not " +
            "for government, but for ourselves. " +
            "We need no reason to fight. " +
            "We fight because we are needed. ",
        "Si vis pacem, para bellum.",
        "Get busy living, or get busy dying.",
        "By failing to prepare, you are preparing to fail.",
        "Life is either a great adventure or nothing.",
        "Electricity is really just organized lightning.",
        "The only thing necessary for the triumph of evil is that good men do nothing.",
        "There are countless ingredients that make up the human body and mind, like all the components that make up me as an individual with my own personality. Sure, I have a face and voice to distinguish myself from others, but my thoughts and memories are unique only to me, and I carry a sense of my own destiny. Each of those things are just a small part of it. I collect information to use in my own way. All of that blends to create a mixture that forms me and gives rise to my conscience.",
        "I reject your reality and substitute my own.",
        "In this moment, I am euphoric. Not because of any phony god’s blessing. But because, I am enlightened by my intelligence.",
        "you're a dirty memer, aren't you",
        "look out, here comes the jews",
        "omg, gmos!",
        "loading unloader",
        "memeing maymays",
        "from whence comes the realization that not only do we live, but we live as individuals?",
        "lol philosomemes",
        "yes",
        "aoh no, we're all out of bacon!",
        "if things get bad, always remember someone, somewhere loves you.",
        "gods fall and thrones fall, with laws of nature and man crumble at the world's end",
        "if memes can be dreams, so can spleens (and dreams)",
        "reticulating spleens",
        "three times a day, you realize you're breathing manually. this is one of those times",
        "if you sneeze hard enough, can you turn yourself inside out?,"

            ];

    var speech_anims = [
        //"Alert",
        "CheckingSomething",
        "Explain",
        "GetArtsy",
        "GetAttention",
        "GetTechy",
        "GetWizardy",
        "Thinking",
        "Wave"
            ];

    $(document).mousemove(function(event) {
        if(lastPos[0] > 0){
            mouseDist += Math.sqrt(
                Math.pow(
                    event.pageX - lastPos[0],
                    2.0
                    ) +
                Math.pow(
                    event.pageY - lastPos[1],
                    2.0
                )
            );
        }
        lastPos[0] = event.pageX;
        lastPos[1] = event.pageY;

        if(mouseDist >= 6000){
            $(document).unbind("mousemove");
            clippy.load('Clippy', function(agent){

                c = $("#form_container");
                p = c.position();
                a = $(".clippy");

                agent.moveTo(p.left + c.width()/2 - a.width()/2, p.top + c.height()/2 - a.height()/2);

                a.click(function(event){
                            agent.stop();
                            agent.play(speech_anims[Math.floor(Math.random() * speech_anims.length)]);
                            agent.speak(text[Math.floor(Math.random() * text.length)]);
                });

                agent.play('Greeting');
            });
        }
    });
});

// callbacks are fantastic
<|endoftext|>


<commit_before>var Github = require('github'),
	_ = require('underscore');

module.exports = (function() {
	var Client, authenticate;

	Client = function(token) {
		this.token = token;
		this.ghClient = new Github({
			version: '3.0.0',
			protocol: 'https'
		});
	};

	Client.prototype.getPullRequests = function(repo, state, callback) {
		var repoInfo;
		authenticate(this);

		repoInfo = repo.split('/');
		this.ghClient.pullRequests.getAll({
			user: repoInfo[0],
			repo: repoInfo[1],
			state: state
		}, function(err, res) {
			if (err) {
				return callback(err);
			}
			callback(null, res);
		});
	};

	Client.prototype.setLabels = function(repo, prNumber, labels, callback) {
		var repoInfo;
		authenticate(this);

		repoInfo = repo.split('/');
		this.ghClient.issues.edit({
			user: repoInfo[0],
			repo: repoInfo[1],
			number: prNumber,
			labels: labels || []
		}, function (err, res) {
			if (err) {
				return callback(err);
			}
			callback(null, res);
		});
	};

	Client.prototype.setClient = function(client) {
		this.ghClient = client;
	};

	authenticate = function(client) {
		client.ghClient.authenticate({
			type: 'oauth',
			token: client.token
		});
	};

	return Client;

}());
<commit_msg>Updated setLabels api to append labels instead of replace.<commit_after>var Github = require('github'),
	_ = require('underscore');

module.exports = (function() {
	var Client, authenticate;

	Client = function(token) {
		this.token = token;
		this.ghClient = new Github({
			version: '3.0.0',
			protocol: 'https'
		});
	};

	Client.prototype.getPullRequests = function(repo, state, callback) {
		var repoInfo;
		authenticate(this);

		repoInfo = repo.split('/');
		this.ghClient.pullRequests.getAll({
			user: repoInfo[0],
			repo: repoInfo[1],
			state: state
		}, function(err, res) {
			if (err) {
				return callback(err);
			}
			callback(null, res);
		});
	};

	Client.prototype.setLabels = function(repo, prNumber, labels, callback) {
		var repoInfo, updateLabels;
		authenticate(this);

		repoInfo = repo.split('/');

		updateLabels = function(user, repo, number, appendLabels) {
			this.ghClient.issues.edit({
				user: user,
				repo: repo,
				number: number,
				labels: appendLabels || []
			}, function (err, res) {
				if (err) {
					return callback(err);
				}
				callback(null, res);
			});
		}.bind(this, repoInfo[0], repoInfo[1], prNumber);

		this.ghClient.issues.getRepoIssue({
			user: repoInfo[0],
			repo: repoInfo[1],
			number: prNumber
		}, function(err, res) {
			var mapper = function(label) {
				return label.name;
			};
			if (err) {
				return callback(err);
			}
			updateLabels(_.union(res.labels.map(mapper), labels));
		});
	};

	Client.prototype.setClient = function(client) {
		this.ghClient = client;
	};

	authenticate = function(client) {
		client.ghClient.authenticate({
			type: 'oauth',
			token: client.token
		});
	};

	return Client;

}());
<|endoftext|>


<commit_before>angular.module( 'omniwallet' )
  .factory( 'enumerated_addresses', function ( $http, $q, $timeout, $injector ) {
    var count = 1;
    return {
      "getData": function() {
        var deferred = $q.defer();

        _.defer( function() {
          var wallet = $injector.get( 'userService' ).getWallet();
          if( wallet && wallet.addresses.length > 0 )
          {

            deferred.resolve( {
              addresses: wallet.addresses
            } );
          }
          else
          {
            deferred.resolve( { addresses: [] } );
          }
        } );
        return deferred.promise;
      }
    };
  })
  .controller( 'AddAddressController', function( $modal, $injector, $scope, userService, enumerated_addresses ) {

    function decodeAddressFromPrivateKey( key ) {

      //  Return the address decoded from the private key.
      var eckey = new Bitcoin.ECKey( key );
      var addr = eckey.getBitcoinAddress().toString();

      return addr;
    };

    function encodePrivateKey( key, passphrase ) {

      //  Return encoded key.  Forget the passphrase forever.
      var eckey = new Bitcoin.ECKey( key );
      var enc = eckey.getEncryptedFormat( passphrase );

      return enc;
    };

    $scope.backupWallet = function() {
      console.log(userService.data.wallet);
      var blob = {
        addresses: userService.data.wallet.addresses
      };
      var exportBlob = new Blob([JSON.stringify(blob)], {type: 'application/json;charset=utf-8'});
      saveAs(exportBlob, "wallet.json");
    }

    // Begin Import watch only Form Code
    $scope.openImportWatchOnlyForm = function() {
      var modalInstance = $modal.open({
        templateUrl: '/partials/import_watch_only.html',
        controller: AddBtcAddressModal
      });

      modalInstance.result.then(function ( result ) {

        if( result.address )
        {
          $injector.get( 'userService' ).addAddress( result.address );
        }
        $scope.refresh();

      }, function () {});
    };

    var AddBtcAddressModal = function ($scope, $modalInstance ) {
      $scope.validate = function( address ) {
        return Bitcoin.Address.validate( address );
      };

      $scope.ok = function ( result ) {
        if( Bitcoin.Address.validate( result.address ))
          $modalInstance.close( result );
        else
          console.log( '*** Invalid address: ' + result.address );
      };

      $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
      };
    };
    // Done Import Watch Only Form Code.

    // Begin Import Private Key Form Code
    $scope.openImportPrivateKeyForm = function() {
      var modalInstance = $modal.open({
        templateUrl: '/partials/import_private.html',
        controller: AddPrivateKeyModal
      });

      modalInstance.result.then(function ( result ) {

        if( result.privKey )
        {
          // Use address as passphrase for now
          var addr = decodeAddressFromPrivateKey( result.privKey );
          $injector.get( 'userService' ).addAddress(
            addr,
            encodePrivateKey( result.privKey, addr));
        }
        $scope.refresh();

      }, function () {});
    };

    var AddPrivateKeyModal = function ($scope, $modalInstance ) {
      $scope.validate = function( address ) {
        if(!address) return false;

        try {
          var eckey = new Bitcoin.ECKey(address);
          var addr = eckey.getBitcoinAddress().toString();
          return true;
        } catch (e) {
          return false;
        }
      };

      $scope.ok = function ( result ) {
        $modalInstance.close( result );
      };

      $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
      };
    };
    // Done Import Private Key Form Code.
    // Begin Import Encrypted Key Form Code
    $scope.openImportEncryptedKeyForm = function() {
      var modalInstance = $modal.open({
        templateUrl: '/partials/import_encrypted_private.html',
        controller: AddEncryptedPrivateModal
      });

      modalInstance.result.then(function ( result ) {

        if( result.encryptedPrivKey && result.password )
        {
          // Decrypt key then store with default password of addr
          var key = Bitcoin.ECKey.decodeEncryptedFormat( result.encryptedPrivKey, result.password);
          var privkey = Bitcoin.Util.bytesToHex(key.getPrivateKeyByteArray());
          // Use address as passphrase for now
          var addr = decodeAddressFromPrivateKey( privkey );
          $injector.get( 'userService' ).addAddress(
            addr,
            encodePrivateKey( privkey, addr));
        }
        $scope.refresh();

      }, function () {});
    };

    var AddEncryptedPrivateModal = function ($scope, $modalInstance ) {
      $scope.ok = function ( result ) {
        $modalInstance.close( result );
      };

      $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
      };
    };
    // Done Import Encrypted Private Key Code.

    // Begine Create Form Code.
    $scope.createBTCAddress = createBTCAddress;
    function createBTCAddress () {
      var ecKey = new Bitcoin.ECKey();
      var address = ecKey.getBitcoinAddress().toString();
      var encryptedPrivateKey = ecKey.getEncryptedFormat( address );
      $injector.get( 'userService' ).addAddress(address, encryptedPrivateKey);
      $scope.refresh();
    };
    // Done Create Form Code.

    $scope.enumerateAddresses = function () {

      $scope.items = enumerated_addresses.getData().then( function( result ) {
        if(result.addresses.length == 0) { createBTCAddress(); }
        $scope.addresses = result.addresses;
      } );
    };

  } );

<commit_msg>Format commit for add_address.js , no errors found.<commit_after>angular.module('omniwallet')
  .factory('enumerated_addresses', function($http, $q, $timeout, $injector) {
    var count = 1;
    return {
      "getData": function() {
        var deferred = $q.defer();

        _.defer(function() {
          var wallet = $injector.get('userService').getWallet();
          if (wallet && wallet.addresses.length > 0) {

            deferred.resolve({
              addresses: wallet.addresses
            });
          } else {
            deferred.resolve({
              addresses: []
            });
          }
        });
        return deferred.promise;
      }
    };
  })
  .controller('AddAddressController', function($modal, $injector, $scope, userService, enumerated_addresses) {

  function decodeAddressFromPrivateKey(key) {

    //  Return the address decoded from the private key.
    var eckey = new Bitcoin.ECKey(key);
    var addr = eckey.getBitcoinAddress().toString();

    return addr;
  }
  ;

  function encodePrivateKey(key, passphrase) {

    //  Return encoded key.  Forget the passphrase forever.
    var eckey = new Bitcoin.ECKey(key);
    var enc = eckey.getEncryptedFormat(passphrase);

    return enc;
  }
  ;

  $scope.backupWallet = function() {
    console.log(userService.data.wallet);
    var blob = {
      addresses: userService.data.wallet.addresses
    };
    var exportBlob = new Blob([JSON.stringify(blob)], {
      type: 'application/json;charset=utf-8'
    });
    saveAs(exportBlob, "wallet.json");
  }

  // Begin Import watch only Form Code
  $scope.openImportWatchOnlyForm = function() {
    var modalInstance = $modal.open({
      templateUrl: '/partials/import_watch_only.html',
      controller: AddBtcAddressModal
    });

    modalInstance.result.then(function(result) {

      if (result.address) {
        $injector.get('userService').addAddress(result.address);
      }
      $scope.refresh();

    }, function() {});
  };

  var AddBtcAddressModal = function($scope, $modalInstance) {
    $scope.validate = function(address) {
      return Bitcoin.Address.validate(address);
    };

    $scope.ok = function(result) {
      if (Bitcoin.Address.validate(result.address))
        $modalInstance.close(result);
      else
        console.log('*** Invalid address: ' + result.address);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  };
  // Done Import Watch Only Form Code.

  // Begin Import Private Key Form Code
  $scope.openImportPrivateKeyForm = function() {
    var modalInstance = $modal.open({
      templateUrl: '/partials/import_private.html',
      controller: AddPrivateKeyModal
    });

    modalInstance.result.then(function(result) {

      if (result.privKey) {
        // Use address as passphrase for now
        var addr = decodeAddressFromPrivateKey(result.privKey);
        $injector.get('userService').addAddress(
        addr,
        encodePrivateKey(result.privKey, addr));
      }
      $scope.refresh();

    }, function() {});
  };

  var AddPrivateKeyModal = function($scope, $modalInstance) {
    $scope.validate = function(address) {
      if (!address) return false;

      try {
        var eckey = new Bitcoin.ECKey(address);
        var addr = eckey.getBitcoinAddress().toString();
        return true;
      } catch (e) {
        return false;
      }
    };

    $scope.ok = function(result) {
      $modalInstance.close(result);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  };
  // Done Import Private Key Form Code.
  // Begin Import Encrypted Key Form Code
  $scope.openImportEncryptedKeyForm = function() {
    var modalInstance = $modal.open({
      templateUrl: '/partials/import_encrypted_private.html',
      controller: AddEncryptedPrivateModal
    });

    modalInstance.result.then(function(result) {

      if (result.encryptedPrivKey && result.password) {
        // Decrypt key then store with default password of addr
        var key = Bitcoin.ECKey.decodeEncryptedFormat(result.encryptedPrivKey, result.password);
        var privkey = Bitcoin.Util.bytesToHex(key.getPrivateKeyByteArray());
        // Use address as passphrase for now
        var addr = decodeAddressFromPrivateKey(privkey);
        $injector.get('userService').addAddress(
        addr,
        encodePrivateKey(privkey, addr));
      }
      $scope.refresh();

    }, function() {});
  };

  var AddEncryptedPrivateModal = function($scope, $modalInstance) {
    $scope.ok = function(result) {
      $modalInstance.close(result);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  };
  // Done Import Encrypted Private Key Code.

  // Begine Create Form Code.
  $scope.createBTCAddress = createBTCAddress;
  function createBTCAddress() {
    var ecKey = new Bitcoin.ECKey();
    var address = ecKey.getBitcoinAddress().toString();
    var encryptedPrivateKey = ecKey.getEncryptedFormat(address);
    $injector.get('userService').addAddress(address, encryptedPrivateKey);
    $scope.refresh();
  }
  ;
  // Done Create Form Code.

  $scope.enumerateAddresses = function() {

    $scope.items = enumerated_addresses.getData().then(function(result) {
      if (result.addresses.length == 0) {
        createBTCAddress();
      }
      $scope.addresses = result.addresses;
    });
  };

});

<|endoftext|>


<commit_before>global.WRTC = require('wrtc')
global.WEBTORRENT_ANNOUNCE = [ 'wss://tracker.webtorrent.io' ]
<commit_msg>Added bTorrent's wss tracker<commit_after>global.WRTC = require('wrtc')
global.WEBTORRENT_ANNOUNCE = [ 'wss://tracker.webtorrent.io', 'wss://tracker.btorrent.xyz' ]
<|endoftext|>


<commit_before>$(document).ready(function() {

    var videoPlayer = videojs("video-player");

    $.get("videos", function(data) {
        videoPlayer.playlist(data);
        videoPlayer.playlistUi();

var slider = document.getElementById('slider');

noUiSlider.create(slider, {
    start: [1, 100],
    connect: true,
    range: {
        'min': 1,
    'max': 100
    }
});

    $("#select-vocab select").select2({
        ajax: {
            url: "/vocabulary",
            dataType: 'json',
            delay: 250,
            data: {},
            processResults: function (data) {
                return {
                    results: data,
                };
            },
            cache: true
        }
    });

   slider.noUiSlider.on('update', function(values, handle){
      videoPlayer = videojs("video-player");
        t = videoPlayer.currentTime();
	duration = videoPlayer.duration();
        slider_values = slider.noUiSlider.get();

	if (handle == 0){
	  newt = slider_values[0]/100*duration;
          videoPlayer.currentTime(newt);
	  document.getElementById("t_start").value = parseFloat(videoPlayer.currentTime()).toFixed(2);
	}
	else
	  if (handle==1){
	    newt = slider_values[1]/100*duration;
            videoPlayer.currentTime(newt);
	    document.getElementById("t_end").value = parseFloat(videoPlayer.currentTime()).toFixed(2);
	  }
    });

    video_list = videojs("video-player").playlist();
    $.post("get_all_annotations",  {
	                             selected_video: video_list[videojs("video-player").playlist.currentItem()].name,

	                            },
	                           function(result){
				   $('.ann-elem').remove();
				   $('.li_class').remove();
				   for (var i = 0; i<result.length;i++)
				   {
				     //text_to_display = '';
				     $('
', {id: 'li_'+result[i].id, class: 'li_class'}).appendTo('ul.ann-menu');
				     text_length = 15;
				      text_to_display = result[i].description;
				    if (result[i].description.length>=text_length)
				       text_to_display = result[i].description.substring(0, text_length)
				      // else
				     //  {
					 //text_extra = Array.from('\x20'.repeat(text_length-result[i].description.length+1 ));
					// text_to_display = result[i].description
					 //for (i = 1; i<( text_length-result[i].description.length);i++)
					 //text_to_display = text_to_display + ' ';
					// difference =  text_length-result[i].description.length;
					// text_to_display = text_to_display + new Array(difference).join(' . ')
				    //   }

				     //text_to_display[1][Math.min(20, result[i].description.length)] = result[i].description;
				      jQuery('
', {
                                                   id: 'id_' + result[i].id,
                                                   text: text_to_display,
                                                   class: 'ann-elem'
                                                }).appendTo('#li_'+result[i].id);

                                   var newInputEdit = '<button type="submit" class="edit_button" name="Button" value="Edit" id="edit-' + result[i].id + '"></button>';
				   $("#id_" + result[i].id).append(newInputEdit);
				   var newInputDelete = '<button type = "submit" class = "delete_button" name = "Button" value = "Delete" id = "delete-' + result[i].id+'"></button>';
				   $("#id_"+ result[i].id).append(newInputDelete);
				   }

	    });

    });

    /*videojs('#video-player').on('timeupdate', function(ev){
    var isPlaying =  !videojs("video-player").paused();
    if (document.getElementById("rb1").checked == true){;
	document.getElementById("t_start").value = parseFloat(videoPlayer.currentTime()).toFixed(2);
      }

      if (document.getElementById("rb2").checked == true){;
	document.getElementById("t_end").value = parseFloat(videoPlayer.currentTime()).toFixed(2);
      }

    });
    */

    $('.vjs-playlist').on('click', function() {
    video_list = videojs("video-player").playlist();
    $.post("get_all_annotations",  {
	                             selected_video: video_list[videojs("video-player").playlist.currentItem()].name,

	                            },
	                           function(result){
				   $('.ann-elem').remove();
				   $('.li_class').remove();
				  // jQuery('', {id:'ann_nav_id', class:'ann_nav'}).appendTo("#annotation_list");
				   //jQuery('
', {id:'list_id', class:'list'}).appendTo("#annotation_list");

				   for (var i = 0; i<result.length;i++)
				   {
				      $('
', {id: 'li_'+result[i].id, class: 'li_class'}).appendTo('ul.ann-menu');
				      jQuery('
', {
                                                   id: 'id_' + result[i].id,
                                                   text: result[i].description,
                                                   class: 'ann-elem'
                                                }).appendTo('#li_'+result[i].id);

			           var newInputEdit = '<button type="submit" class="edit_button" name="Button" value="Edit" id="edit-' + result[i].id + '"></button>';
				   $("#id_" + result[i].id).append(newInputEdit);
				   var newInputDelete = '<button type = "submit" class = "delete_button" name = "Button" value = "Delete" id = "delete-' + result[i].id+'"></button>';
				   $("#id_"+ result[i].id).append(newInputDelete);
				   }

	    });
    });

    $('#add-ann').click( function(ev) {

	 //alert(videoPlayer.currentTime())
         var selected_data = $("#select-vocab select").select2("data");
         var selected_text = selected_data.map(function(x) {return x.text});
	 //current_video = document.getElementById("select-video").value;
	 video_list = videojs("video-player").playlist();
	 $.post("save_annotation",  {
	                             selected_video: video_list[videojs("video-player").playlist.currentItem()].name,
	                             time_start: document.getElementById("t_start").value,
	                             time_end: document.getElementById("t_end").value,
		                     select_vocab: selected_text.join(" "),
	                             description: document.getElementById("description").value,
	                             ann_number: document.getElementById("ann_number").innerText
	                            },
	                           function(result){
				   ann_number = document.getElementById("ann_number").innerText;
				   if  (ann_number == 0){
				   $('
', {id: 'li_'+result[0].id, class: 'li_class'}).appendTo('ul.ann-menu');
				   jQuery('
', {
                                                   id: 'id_'+result[0].id,
                                                   text: result[0].description,
                                                   class: 'ann-elem'
                                                }).appendTo('#li_'+result[0].id);

			           var newInputEdit = '<button type="submit" class="edit_button" name="Button" value="Edit" id="edit-' + result[0].id + '"></button>';
				   $("#id_"+result[0].id).append(newInputEdit);
				   var newInputDelete = '<button type = "submit" class = "delete_button" name = "Button" value = "Delete" id = "delete-' + result[0].id+'"></button>';
				   $("#id_"+result[0].id).append(newInputDelete);
				   }
				   else
				   {
				     document.getElementById("ann_number").innerText = 0;
				     document.getElementById("id_" + ann_number).innerText = result[0].description;
				     var newInputEdit = '<button type="submit" class="edit_button" name="Button" value="Edit" id="edit-' + result[0].id + '"></button>';
				     $("#id_"+result[0].id).append(newInputEdit);
				     var newInputDelete = '<button type = "submit" class = "delete_button" name = "Button" value = "Delete" id = "delete-' + result[0].id+'"></button>';
				     $("#id_"+result[0].id).append(newInputDelete);
				Start   }

				   //$("#id_"+result[0].id).click(function() {
					      //alert(result[0].id);
					//      });

	    });

	// document.getElementById("select-video").value = current_video;
	document.getElementById("t_start").value = '';
	document.getElementById("t_end").value = '';
	document.getElementById("description").value = '';
        $("#select-vocab select").val(null).trigger("change");
        videojs("video-player").pause();

    });

    $('input[type = "radio"]').on('click', function(e)
    {
      videojs("video-player").pause();
    });

  $('#ann-menu-id').on("click", ".edit_button", function() {
            id = this.id;
	    id_annotation = id.substring(5,id.length);
	    $.post("get_annotation", {
	                             annotation_id: id_annotation,
	                             },
	                           function(result){

				 document.getElementById("t_start").value = result[0].t_start;
	                         document.getElementById("t_end").value = result[0].t_end;
	                         document.getElementById("description").value = result[0].description;

				 selected_vocab = result[0].selected_vocab;
				 selected_words = selected_vocab.split(" ");
                                 $("#select-vocab select").val(selected_words).trigger("change");

                                 document.getElementById("ann_number").innerText =  id_annotation;

	    });
	});

  $('#ann-menu-id').on("click", ".delete_button", function() {
            id = this.id;
	    id_annotation = id.substring(7,id.length);
	    x =  window.confirm("Are you sure you want to delete the annotation?");
	    if (x ==true){
	    $.post("delete_annotation", {
	                             annotation_id: id_annotation,
	                             });
	    document.getElementById('id_'+id_annotation).remove();
	    }

	});

 document.addEventListener('keydown', function (evt) {
       var videoPlayer = videojs("video-player");
       frameTime = 1 / 30; //assume 30 fps
       videoPlayer.pause()
       t = videoPlayer.currentTime();
       if (evt.keyCode === 37) { //left arrows
          if (t  > 0) {
          //one frame back
          videoPlayer.currentTime(t-frameTime);
          }
       }
       else if (evt.keyCode === 39) { //right arrow
            if (videoPlayer.currentTime() < videoPlayer.duration()) {
            //one frame forward
            //Don't go past the end, otherwise you may get an error
            videoPlayer.currentTime(Math.min(videoPlayer.duration(), t + frameTime));
            }

       }
 });

 $('input[type="radio"]').keydown(function(e)
{
    var arrowKeys = [37, 38, 39, 40];
    if (arrowKeys.indexOf(e.which) !== -1)
    {
        $(this).blur();

    }
});

  $('#start_btn').click( function(ev) {
 document.getElementById("t_start").value = parseFloat(videoPlayer.currentTime()).toFixed(2);
});

  $('#end_btn').click( function(ev) {
 document.getElementById("t_end").value = parseFloat(videoPlayer.currentTime()).toFixed(2);
});
});
<commit_msg>adjust slider ends<commit_after>$(document).ready(function() {

    var videoPlayer = videojs("video-player");

    $.get("videos", function(data) {
        videoPlayer.playlist(data);
        videoPlayer.playlistUi();

var slider = document.getElementById('slider');

noUiSlider.create(slider, {
    start: [1, 100],
    connect: true,
    range: {
        'min': 1,
    'max': 100
    }
});

    $("#select-vocab select").select2({
        ajax: {
            url: "/vocabulary",
            dataType: 'json',
            delay: 250,
            data: {},
            processResults: function (data) {
                return {
                    results: data,
                };
            },
            cache: true
        }
    });

   slider.noUiSlider.on('update', function(values, handle){
      videoPlayer = videojs("video-player");
        t = videoPlayer.currentTime();
	duration = videoPlayer.duration();
        slider_values = slider.noUiSlider.get();

	if (handle == 0){
	  newt = slider_values[0]/100*duration;
          videoPlayer.currentTime(newt);
	  document.getElementById("t_start").value = parseFloat(videoPlayer.currentTime()).toFixed(2);
	}
	else
	  if (handle==1){
	    newt = slider_values[1]/100*duration;
            videoPlayer.currentTime(newt);
	    document.getElementById("t_end").value = parseFloat(videoPlayer.currentTime()).toFixed(2);
	  }
    });

    video_list = videojs("video-player").playlist();
    $.post("get_all_annotations",  {
	                             selected_video: video_list[videojs("video-player").playlist.currentItem()].name,

	                            },
	                           function(result){
				   $('.ann-elem').remove();
				   $('.li_class').remove();
				   for (var i = 0; i<result.length;i++)
				   {
				     //text_to_display = '';
				     $('
', {id: 'li_'+result[i].id, class: 'li_class'}).appendTo('ul.ann-menu');
				     text_length = 15;
				      text_to_display = result[i].description;
				    if (result[i].description.length>=text_length)
				       text_to_display = result[i].description.substring(0, text_length)
				      // else
				     //  {
					 //text_extra = Array.from('\x20'.repeat(text_length-result[i].description.length+1 ));
					// text_to_display = result[i].description
					 //for (i = 1; i<( text_length-result[i].description.length);i++)
					 //text_to_display = text_to_display + ' ';
					// difference =  text_length-result[i].description.length;
					// text_to_display = text_to_display + new Array(difference).join(' . ')
				    //   }

				     //text_to_display[1][Math.min(20, result[i].description.length)] = result[i].description;
				      jQuery('
', {
                                                   id: 'id_' + result[i].id,
                                                   text: text_to_display,
                                                   class: 'ann-elem'
                                                }).appendTo('#li_'+result[i].id);

                                   var newInputEdit = '<button type="submit" class="edit_button" name="Button" value="Edit" id="edit-' + result[i].id + '"></button>';
				   $("#id_" + result[i].id).append(newInputEdit);
				   var newInputDelete = '<button type = "submit" class = "delete_button" name = "Button" value = "Delete" id = "delete-' + result[i].id+'"></button>';
				   $("#id_"+ result[i].id).append(newInputDelete);
				   }

	    });

    });

    /*videojs('#video-player').on('timeupdate', function(ev){
    var isPlaying =  !videojs("video-player").paused();
    if (document.getElementById("rb1").checked == true){;
	document.getElementById("t_start").value = parseFloat(videoPlayer.currentTime()).toFixed(2);
      }

      if (document.getElementById("rb2").checked == true){;
	document.getElementById("t_end").value = parseFloat(videoPlayer.currentTime()).toFixed(2);
      }

    });
    */

    $('.vjs-playlist').on('click', function() {
    video_list = videojs("video-player").playlist();
    $.post("get_all_annotations",  {
	                             selected_video: video_list[videojs("video-player").playlist.currentItem()].name,

	                            },
	                           function(result){
				   $('.ann-elem').remove();
				   $('.li_class').remove();
				  // jQuery('', {id:'ann_nav_id', class:'ann_nav'}).appendTo("#annotation_list");
				   //jQuery('
', {id:'list_id', class:'list'}).appendTo("#annotation_list");

				   for (var i = 0; i<result.length;i++)
				   {
				      $('
', {id: 'li_'+result[i].id, class: 'li_class'}).appendTo('ul.ann-menu');
				      jQuery('
', {
                                                   id: 'id_' + result[i].id,
                                                   text: result[i].description,
                                                   class: 'ann-elem'
                                                }).appendTo('#li_'+result[i].id);

			           var newInputEdit = '<button type="submit" class="edit_button" name="Button" value="Edit" id="edit-' + result[i].id + '"></button>';
				   $("#id_" + result[i].id).append(newInputEdit);
				   var newInputDelete = '<button type = "submit" class = "delete_button" name = "Button" value = "Delete" id = "delete-' + result[i].id+'"></button>';
				   $("#id_"+ result[i].id).append(newInputDelete);
				   }

	    });
    });

    $('#add-ann').click( function(ev) {

	 //alert(videoPlayer.currentTime())
         var selected_data = $("#select-vocab select").select2("data");
         var selected_text = selected_data.map(function(x) {return x.text});
	 //current_video = document.getElementById("select-video").value;
	 video_list = videojs("video-player").playlist();
	 $.post("save_annotation",  {
	                             selected_video: video_list[videojs("video-player").playlist.currentItem()].name,
	                             time_start: document.getElementById("t_start").value,
	                             time_end: document.getElementById("t_end").value,
		                     select_vocab: selected_text.join(" "),
	                             description: document.getElementById("description").value,
	                             ann_number: document.getElementById("ann_number").innerText
	                            },
	                           function(result){
				   ann_number = document.getElementById("ann_number").innerText;
				   if  (ann_number == 0){
				   $('
', {id: 'li_'+result[0].id, class: 'li_class'}).appendTo('ul.ann-menu');
				   jQuery('
', {
                                                   id: 'id_'+result[0].id,
                                                   text: result[0].description,
                                                   class: 'ann-elem'
                                                }).appendTo('#li_'+result[0].id);

			           var newInputEdit = '<button type="submit" class="edit_button" name="Button" value="Edit" id="edit-' + result[0].id + '"></button>';
				   $("#id_"+result[0].id).append(newInputEdit);
				   var newInputDelete = '<button type = "submit" class = "delete_button" name = "Button" value = "Delete" id = "delete-' + result[0].id+'"></button>';
				   $("#id_"+result[0].id).append(newInputDelete);
				   }
				   else
				   {
				     document.getElementById("ann_number").innerText = 0;
				     document.getElementById("id_" + ann_number).innerText = result[0].description;
				     var newInputEdit = '<button type="submit" class="edit_button" name="Button" value="Edit" id="edit-' + result[0].id + '"></button>';
				     $("#id_"+result[0].id).append(newInputEdit);
				     var newInputDelete = '<button type = "submit" class = "delete_button" name = "Button" value = "Delete" id = "delete-' + result[0].id+'"></button>';
				     $("#id_"+result[0].id).append(newInputDelete);
				Start   }

				   //$("#id_"+result[0].id).click(function() {
					      //alert(result[0].id);
					//      });

	    });

	// document.getElementById("select-video").value = current_video;
	document.getElementById("t_start").value = '';
	document.getElementById("t_end").value = '';
	document.getElementById("description").value = '';
        $("#select-vocab select").val(null).trigger("change");
        videojs("video-player").pause();

    });

    $('input[type = "radio"]').on('click', function(e)
    {
      videojs("video-player").pause();
    });

  $('#ann-menu-id').on("click", ".edit_button", function() {
            id = this.id;
	    id_annotation = id.substring(5,id.length);
	    $.post("get_annotation", {
	                             annotation_id: id_annotation,
	                             },
	                           function(result){

				 document.getElementById("t_start").value = result[0].t_start;
	                         document.getElementById("t_end").value = result[0].t_end;
	                         document.getElementById("description").value = result[0].description;

				 selected_vocab = result[0].selected_vocab;
				 selected_words = selected_vocab.split(" ");
                                 $("#select-vocab select").val(selected_words).trigger("change");

                                 document.getElementById("ann_number").innerText =  id_annotation;

	    });
	});

  $('#ann-menu-id').on("click", ".delete_button", function() {
            id = this.id;
	    id_annotation = id.substring(7,id.length);
	    x =  window.confirm("Are you sure you want to delete the annotation?");
	    if (x ==true){
	    $.post("delete_annotation", {
	                             annotation_id: id_annotation,
	                             });
	    document.getElementById('id_'+id_annotation).remove();
	    }

	});

 document.addEventListener('keydown', function (evt) {
       var videoPlayer = videojs("video-player");
       frameTime = 1 / 30; //assume 30 fps
       videoPlayer.pause()
       t = videoPlayer.currentTime();
       if (evt.keyCode === 37) { //left arrows
          if (t  > 0) {
          //one frame back
          videoPlayer.currentTime(t-frameTime);
          }
       }
       else if (evt.keyCode === 39) { //right arrow
            if (videoPlayer.currentTime() < videoPlayer.duration()) {
            //one frame forward
            //Don't go past the end, otherwise you may get an error
            videoPlayer.currentTime(Math.min(videoPlayer.duration(), t + frameTime));
            }

       }
 });

 $('input[type="radio"]').keydown(function(e)
{
    var arrowKeys = [37, 38, 39, 40];
    if (arrowKeys.indexOf(e.which) !== -1)
    {
        $(this).blur();

    }
});

  $('#start_btn').click( function(ev) {

    videoPlayer = videojs("video-player");
     x =  parseFloat(videoPlayer.currentTime()).toFixed(2);
         t = videoPlayer.currentTime();
	duration = videoPlayer.duration();
 document.getElementById("t_start").value = x;
 slider.noUiSlider.set([(x/duration)*100, null]);
});

  $('#end_btn').click( function(ev) {
    videoPlayer = videojs("video-player");
     x =  parseFloat(videoPlayer.currentTime()).toFixed(2);
         t = videoPlayer.currentTime();
	duration = videoPlayer.duration();
 document.getElementById("t_end").value = parseFloat(videoPlayer.currentTime()).toFixed(2);
  videojs("video-player").pause();
  slider.noUiSlider.set([null, (x/duration)*100]);
});
});
<|endoftext|>