<commit_before>import { Utils } from 'meteor/vulcan:core';
import cheerio from 'cheerio';

// Number of headings below which a table of contents won't be generated.
const minHeadingsForToC = 3;

const headingTags = {
  h1: 1,
  h2: 2,
  h3: 3,
  h4: 4,
  h5: 5,
  h6: 6,
}

const headingIfWholeParagraph = {
  strong: 7,
  b: 8,
};

const headingSelector = _.keys(headingTags).concat(_.keys(headingIfWholeParagraph)).join(",");

// Given an HTML document, extract a list of sections for a table of contents
// from it, and add anchors. The result is modified HTML with added anchors,
// plus a JSON array of sections, where each section has a
// `title`, `anchor`, and `level`, like this:
//   {
//     html: ",
//     sections: [
//       {title: "Preamble", anchor: "preamble", level: 1},
//       {title: "My Cool Idea", anchor: "mycoolidea", level: 1},
//         {title: "An Aspect of My Cool Idea", anchor:"anaspectofmycoolidea", level: 2},
//         {title: "Why This Is Neat", anchor:"whythisisneat", level: 2},
//       {title: "Conclusion", anchor: "conclusion", level: 1},
//     ]
//   }
export function extractTableOfContents(postHTML)
{
  const postBody = cheerio.load(postHTML);
  let headings = [];
  let usedAnchors = {};

  // First, find the headings in the document, create a linear list of them,
  // and insert anchors at each one.
  let headingTags = postBody(headingSelector);
  for (let i=0; i<headingTags.length; i++) {
    let tag = headingTags[i];

    if (tagIsHeadingIfWholeParagraph(tag.tagName) && !tagIsWholeParagraph(tag)) {
      continue;
    }

    let title = cheerio(tag).text();
    let anchor = titleToAnchor(title, usedAnchors);
    cheerio(tag).attr("id", anchor);
    headings.push({
      title: title,
      anchor: anchor,
      level: tagToHeadingLevel(tag.tagName),
    });
  }

  if (headings.length < minHeadingsForToC)
    return null;

  // Filter out unused heading levels, mapping the heading levels to consecutive
  // numbers starting from 1. So if a post uses
,
 and , those
  // will be levels 1, 2, and 3 (not 1, 3 and 7).

  // Get a list of heading levels used
  let headingLevelsUsedDict = {};
  for(let i=0; i<headings.length; i++)
    headingLevelsUsedDict[headings[i].level] = true;

  // Generate a mapping from raw heading levels to compressed heading levels
  let headingLevelsUsed = _.keys(headingLevelsUsedDict).sort();
  let headingLevelMap = {};
  for(let i=0; i<headingLevelsUsed.length; i++)
    headingLevelMap[ headingLevelsUsed[i] ] = i+1;

  // Mark sections with compressed heading levels
  for(let i=0; i<headings.length; i++)
    headings[i].level = headingLevelMap[headings[i].level];

  return {
    html: postBody.html(),
    sections: headings,
  }
}

// Given the text in a heading block and a dict of anchors that have been used
// in the post so far, generate an anchor, add that anchor to usedAnchors, and
// return it. An anchor is a URL-safe string that can be used for
// within-document links.
function titleToAnchor(title, usedAnchors)
{
  let charsToUse = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789";
  let sb = [];

  for(let i=0; i<title.length; i++) {
    let ch = title.charAt(i);
    if(charsToUse.indexOf(ch) >= 0) {
      sb.push(ch);
    } else {
      sb.push('_');
    }
  }

  let anchor = sb.join('');
  if(!usedAnchors[anchor])
    return anchor;

  let anchorSuffix = 1;
  while(usedAnchors[anchor + anchorSuffix])
    anchorSuffix++;
  return anchor+anchorSuffix;
}

// `<b>` and `<strong>` tags are headings iff they are the only thing in their
// paragraph.
function tagIsHeadingIfWholeParagraph(tagName)
{
  return tagName.toLowerCase() in headingIfWholeParagraph;
}

function tagIsWholeParagraph(tag) {
  if (!tag) return false;
  let parents = cheerio(tag).parent();
  if (!parents || !parents.length) return false;
  let parent = parents[0];
  if (parent.tagName.toLowerCase() !== 'p') return false;
  let siblings = cheerio(tag).siblings();
  if (siblings.length > 0) return false;

  return true;
}

function tagToHeadingLevel(tagName)
{
  let lowerCaseTagName = tagName.toLowerCase();
  if (lowerCaseTagName in headingTags)
    return headingTags[lowerCaseTagName];
  else if (lowerCaseTagName in headingIfWholeParagraph)
    return headingIfWholeParagraph[lowerCaseTagName];
  else
    return 0;
}

Utils.extractTableOfContents = extractTableOfContents;<commit_msg>ToC: Bugfixes and refinements from looking at real posts<commit_after>import { Utils } from 'meteor/vulcan:core';
import cheerio from 'cheerio';

// Number of headings below which a table of contents won't be generated.
const minHeadingsForToC = 3;

const headingTags = {
  h1: 1,
  h2: 2,
  h3: 3,
  h4: 4,
  //h5: 5,
  //h6: 6,
}

const headingIfWholeParagraph = {
  strong: 7,
  b: 8,
};

const headingSelector = _.keys(headingTags).concat(_.keys(headingIfWholeParagraph)).join(",");

// Given an HTML document, extract a list of sections for a table of contents
// from it, and add anchors. The result is modified HTML with added anchors,
// plus a JSON array of sections, where each section has a
// `title`, `anchor`, and `level`, like this:
//   {
//     html: ",
//     sections: [
//       {title: "Preamble", anchor: "preamble", level: 1},
//       {title: "My Cool Idea", anchor: "mycoolidea", level: 1},
//         {title: "An Aspect of My Cool Idea", anchor:"anaspectofmycoolidea", level: 2},
//         {title: "Why This Is Neat", anchor:"whythisisneat", level: 2},
//       {title: "Conclusion", anchor: "conclusion", level: 1},
//     ]
//   }
export function extractTableOfContents(postHTML)
{
  const postBody = cheerio.load(postHTML);
  let headings = [];
  let usedAnchors = {};

  // First, find the headings in the document, create a linear list of them,
  // and insert anchors at each one.
  let headingTags = postBody(headingSelector);
  for (let i=0; i<headingTags.length; i++) {
    let tag = headingTags[i];

    if (tagIsHeadingIfWholeParagraph(tag.tagName) && !tagIsWholeParagraph(tag)) {
      continue;
    }

    let title = cheerio(tag).text();
    let anchor = titleToAnchor(title, usedAnchors);
    usedAnchors[anchor] = true;
    cheerio(tag).attr("id", anchor);
    headings.push({
      title: title,
      anchor: anchor,
      level: tagToHeadingLevel(tag.tagName),
    });
  }

  if (headings.length < minHeadingsForToC)
    return null;

  // Filter out unused heading levels, mapping the heading levels to consecutive
  // numbers starting from 1. So if a post uses
,
 and , those
  // will be levels 1, 2, and 3 (not 1, 3 and 7).

  // Get a list of heading levels used
  let headingLevelsUsedDict = {};
  for(let i=0; i<headings.length; i++)
    headingLevelsUsedDict[headings[i].level] = true;

  // Generate a mapping from raw heading levels to compressed heading levels
  let headingLevelsUsed = _.keys(headingLevelsUsedDict).sort();
  let headingLevelMap = {};
  for(let i=0; i<headingLevelsUsed.length; i++)
    headingLevelMap[ headingLevelsUsed[i] ] = i+1;

  // Mark sections with compressed heading levels
  for(let i=0; i<headings.length; i++)
    headings[i].level = headingLevelMap[headings[i].level];

  return {
    html: postBody.html(),
    sections: headings,
  }
}

// Given the text in a heading block and a dict of anchors that have been used
// in the post so far, generate an anchor, and return it. An anchor is a
// URL-safe string that can be used for within-document links.
function titleToAnchor(title, usedAnchors)
{
  let charsToUse = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789";
  let sb = [];

  for(let i=0; i<title.length; i++) {
    let ch = title.charAt(i);
    if(charsToUse.indexOf(ch) >= 0) {
      sb.push(ch);
    } else {
      sb.push('_');
    }
  }

  let anchor = sb.join('');
  if(!usedAnchors[anchor])
    return anchor;

  let anchorSuffix = 1;
  while(usedAnchors[anchor + anchorSuffix])
    anchorSuffix++;
  return anchor+anchorSuffix;
}

// `<b>` and `<strong>` tags are headings iff they are the only thing in their
// paragraph.
function tagIsHeadingIfWholeParagraph(tagName)
{
  return tagName.toLowerCase() in headingIfWholeParagraph;
}

function tagIsWholeParagraph(tag) {
  if (!tag) return false;
  let parents = cheerio(tag).parent();
  if (!parents || !parents.length) return false;
  let parent = parents[0];
  if (parent.tagName.toLowerCase() !== 'p') return false;
  let selfAndSiblings = cheerio(parent).contents();
  if (selfAndSiblings.length != 1) return false;

  return true;
}

function tagToHeadingLevel(tagName)
{
  let lowerCaseTagName = tagName.toLowerCase();
  if (lowerCaseTagName in headingTags)
    return headingTags[lowerCaseTagName];
  else if (lowerCaseTagName in headingIfWholeParagraph)
    return headingIfWholeParagraph[lowerCaseTagName];
  else
    return 0;
}

Utils.extractTableOfContents = extractTableOfContents;<|endoftext|>


<commit_before>var DEBUG = 1;

// AJAX setup
var AJAX_SETUP = {
	timeout: 9000,
	cache: false,
}

// Loops & intervals
var BACKGROUND_LOOP = 30000; // 30s
var BACKGROUND_LOOP_OFFLINE = 3000; // 3s, respond quickly when we get back online
var PAGE_LOOP = 10000; // 10s

// Update stuff at every X intervals
var UPDATE_OFFICE_INTERVAL = 1; // recommended: 1
var UPDATE_SERVANT_INTERVAL = 20; // recommended: 20
var UPDATE_MEETINGS_INTERVAL = 20; // recommended: 20
var UPDATE_COFFEE_INTERVAL = 1; // recommended: 1
var UPDATE_HOURS_INTERVAL = 60; // recommended: 60
var UPDATE_CANTINAS_INTERVAL = 60; // recommended: 60
var UPDATE_BUS_INTERVAL = 2; // recommended: 1
var UPDATE_NEWS_INTERVAL = 20; // recommended: 20

// OS detection
var OPERATING_SYSTEM = "Unknown";
if (navigator.appVersion.indexOf("Win")!==-1) OPERATING_SYSTEM="Windows";
else if (navigator.appVersion.indexOf("Linux")!==-1) OPERATING_SYSTEM="Linux";
else if (navigator.appVersion.indexOf("X11")!==-1) OPERATING_SYSTEM="UNIX";
else if (navigator.appVersion.indexOf("Mac")!==-1) {
	OPERATING_SYSTEM = "Old Mac";
	if (navigator.appVersion.indexOf("10_7")!==-1||navigator.appVersion.indexOf("10_8")!==-1) {
		OPERATING_SYSTEM = "Mac";
	}
}
else {
	console.log("ERROR: Potentially unsupported operating system");
}

// Browser detection
var BROWSER = "Unknown";
if (typeof chrome != "undefined")
	BROWSER = "Chrome";
else if (typeof opera != "undefined")
	BROWSER = "Opera";
else {
	console.log("ERROR: Potentially unsupported browser");
}

// Production detection
if (BROWSER == "Chrome") {
	if (typeof chrome.i18n != "undefined") {
		if (chrome.i18n.getMessage('@@extension_id') === "hfgffimlnajpbenfpaofmmffcdmgkllf") {
			DEBUG = 0;
		}
	}
}
else if (BROWSER == "Opera") {
	// TODO: Implement this
}
<commit_msg>constants: a few updates relating to browser sniffing<commit_after>var DEBUG = 1;

// AJAX setup
var AJAX_SETUP = {
	timeout: 9000,
	cache: false,
}

// Loops & intervals
var BACKGROUND_LOOP = 30000; // 30s
var BACKGROUND_LOOP_OFFLINE = 3000; // 3s, respond quickly when we get back online
var PAGE_LOOP = 10000; // 10s

// Update stuff at every X intervals
var UPDATE_OFFICE_INTERVAL = 1; // recommended: 1
var UPDATE_SERVANT_INTERVAL = 20; // recommended: 20
var UPDATE_MEETINGS_INTERVAL = 20; // recommended: 20
var UPDATE_COFFEE_INTERVAL = 1; // recommended: 1
var UPDATE_HOURS_INTERVAL = 60; // recommended: 60
var UPDATE_CANTINAS_INTERVAL = 60; // recommended: 60
var UPDATE_BUS_INTERVAL = 2; // recommended: 1
var UPDATE_NEWS_INTERVAL = 20; // recommended: 20

// OS detection
var OPERATING_SYSTEM = "Unknown";
if (navigator.appVersion.indexOf("Win")!==-1) OPERATING_SYSTEM="Windows";
else if (navigator.appVersion.indexOf("Linux")!==-1) OPERATING_SYSTEM="Linux";
else if (navigator.appVersion.indexOf("X11")!==-1) OPERATING_SYSTEM="UNIX";
else if (navigator.appVersion.indexOf("Mac")!==-1) {
	OPERATING_SYSTEM = "Old Mac";
	if (navigator.appVersion.indexOf("10_7")!==-1||navigator.appVersion.indexOf("10_8")!==-1) {
		OPERATING_SYSTEM = "Mac";
	}
}
else {
	console.log('WARNING: Potentially unsupported operating system');
}

// Browser detection
var BROWSER = "Unknown";
if (typeof chrome != "undefined" && typeof opr == "undefined")
	BROWSER = "Chrome";
else if (typeof chrome != "undefined" && typeof opr != "undefined")
	BROWSER = "Opera";
else
	console.log('WARNING: Potentially unsupported browser');

// Production detection
if (BROWSER == 'Chrome') {
	if (typeof chrome.i18n != 'undefined')
		if (chrome.i18n.getMessage('@@extension_id') === 'hfgffimlnajpbenfpaofmmffcdmgkllf')
			DEBUG = 0;
	else
		console.log('WARNING: Is this browser no longer using Chrome based webkit?');
}
else if (BROWSER == 'Opera') {
	if (typeof chrome.i18n != 'undefined')
		if (chrome.i18n.getMessage('@@extension_id') === 'TODO: OPERA EXTENSION ID HER')
			DEBUG = 0;
	else
		console.log('WARNING: Is this browser no longer using Chrome based webkit?');
}
<|endoftext|>


<commit_before>/*
 * feathers-errors
 * https://github.com/feathersjs/feathers-errors
 *
 * Copyright (c) 2014 Eric Kryski
 * Licensed under the MIT license.
 */

'use strict';

var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var errors = require('./error-types');
var html = fs.readFileSync(path.resolve(__dirname, '..', 'public/error.html')).toString();

/**
* Escape the given string of `html`.
*
* @param {String} html
* @return {String}
* @api private
*/
var escapeHTML = function(html){
  return String(html)
    .replace(/&(?!\w+;)/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"');
};

/**
 * Method for a 404 middleware
 * See http://expressjs.com/guide.html#error-handling
 * @param  {Error} err - An error
 * @param  {Object} req - the request object
 * @param  {Object} res - the response object
 * @param  {Function} next - callback to call for next step in middleware chain
 */
var fourOhFour = function(req, res, next) {
  next(new errors.NotFound('Page not found.'));
};

/**
 * The error handler middleware.
 * See http://expressjs.com/guide.html#error-handling
 * @param  {Error} err - An error
 * @param  {Object} req - the request object
 * @param  {Object} res - the response object
 * @param  {Function} next - callback to call for next step in middleware chain
 *
 */

/* jshint unused:false */
var handler = function(err, req, res, next) {
  console.log('ERR', typeof err);

  if (typeof err === 'string') {
    err = new errors.GeneralError(err);
  }

  var statusCode = typeof err.code === 'number' ? err.code : 500;

  res.status(statusCode);

  if (typeof req.app.error === 'function') {
    req.app.error(req.url, err.stack || err);
  }

  res.format({
    'text/html': function(){
      // If we have a rendering engine don't show the
      // default feathers error page.
      // TODO (EK): We should let people specify this instead
      // of making a shitty assumption.
      if (req.app.get('view engine') !== undefined) {
        if (err.code === 404) {
          return res.redirect('/404');
        }

        return res.redirect('/500');
      }

      var stack = (err.stack || '')
          .split('\n')
          .slice(1)
          .map(function(v) {
             return '
' + v + '
';
           })
          .join('');

      var errorPage = html
          .replace('{stack}', stack)
          .replace('{title}', err.message)
          .replace('{statusCode}', err.code)
          .replace(/\{error\}/g, escapeHTML(err.toString().replace(/\n/g, '
')));
      res.send(errorPage);
    },

    'application/json': function(){
      res.json({
        'code': err.code,
        'name': err.name,
        'message': err.message
      });
    },

    'text/plain': function(){
      res.send(err.message);
    }
  });
};

exports = module.exports = function (config) {
  if (typeof config === 'function') {
    handler = config;
    config = {};
  }

  config = _.defaults({}, config, {
    handler: handler,
    fourOhFour: fourOhFour
  });

  return function () {
    var app = this;

    // Enable the errors Plugin
    app.enable('feathers errors');

    // Set the error handlers
    app.use(config.fourOhFour).use(config.handler);

    // Set the available errors on the app for convenience
    app.errors = errors;
  };
};

exports.fourOhFour = fourOhFour;
exports.handler = handler;
exports.types = errors;<commit_msg>removing console.log. Getting errors to work with generic errors<commit_after>/*
 * feathers-errors
 * https://github.com/feathersjs/feathers-errors
 *
 * Copyright (c) 2014 Eric Kryski
 * Licensed under the MIT license.
 */

'use strict';

var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var errors = require('./error-types');
var html = fs.readFileSync(path.resolve(__dirname, '..', 'public/error.html')).toString();

/**
* Escape the given string of `html`.
*
* @param {String} html
* @return {String}
* @api private
*/
var escapeHTML = function(html){
  return String(html)
    .replace(/&(?!\w+;)/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"');
};

/**
 * Method for a 404 middleware
 * See http://expressjs.com/guide.html#error-handling
 * @param  {Error} err - An error
 * @param  {Object} req - the request object
 * @param  {Object} res - the response object
 * @param  {Function} next - callback to call for next step in middleware chain
 */
var fourOhFour = function(req, res, next) {
  next(new errors.NotFound('Page not found.'));
};

/**
 * The error handler middleware.
 * See http://expressjs.com/guide.html#error-handling
 * @param  {Error} err - An error
 * @param  {Object} req - the request object
 * @param  {Object} res - the response object
 * @param  {Function} next - callback to call for next step in middleware chain
 *
 */

/* jshint unused:false */
var handler = function(err, req, res, next) {
  if (typeof err === 'string') {
    err = new errors.GeneralError(err);
  }
  else if (!(err instanceof errors.AbstractError)) {
    var oldError = err;
    err = new errors.GeneralError(oldError.message);

    if (oldError.stack) {
      err.stack = oldError.stack;
    }
  }

  var statusCode = typeof err.code === 'number' ? err.code : 500;

  res.status(statusCode);

  if (typeof req.app.error === 'function') {
    req.app.error(req.url, err.stack || err);
  }

  res.format({
    'text/html': function(){
      // If we have a rendering engine don't show the
      // default feathers error page.
      // TODO (EK): We should let people specify this instead
      // of making a shitty assumption.
      if (req.app.get('view engine') !== undefined) {
        if (err.code === 404) {
          return res.redirect('/404');
        }

        return res.redirect('/500');
      }

      var stack = (err.stack || '')
          .split('\n')
          .slice(1)
          .map(function(v) {
             return '
' + v + '
';
           })
          .join('');

      var errorPage = html
          .replace('{stack}', stack)
          .replace('{title}', err.message)
          .replace('{statusCode}', err.code)
          .replace(/\{error\}/g, escapeHTML(err.toString().replace(/\n/g, '
')));
      res.send(errorPage);
    },

    'application/json': function(){
      res.json({
        'code': err.code,
        'name': err.name,
        'message': err.message
      });
    },

    'text/plain': function(){
      res.send(err.message);
    }
  });
};

exports = module.exports = function (config) {
  if (typeof config === 'function') {
    handler = config;
    config = {};
  }

  config = _.defaults({}, config, {
    handler: handler,
    fourOhFour: fourOhFour
  });

  return function () {
    var app = this;

    // Enable the errors Plugin
    app.enable('feathers errors');

    // Set the error handlers
    app.use(config.fourOhFour).use(config.handler);

    // Set the available errors on the app for convenience
    app.errors = errors;
  };
};

exports.fourOhFour = fourOhFour;
exports.handler = handler;
exports.types = errors;<|endoftext|>


<commit_before>
function getParam(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

/* Convert daily/weekly donations to monthly donations */

function isConvertedToMonthly() {
  var weeklyPages = contribConfig.weeklyPages || [];
  return weeklyPages.indexOf(contribConfig.pageId) >= 0;
}

function getMonthlyValue() {
  var $montlyInfo = jQuery('#monthlyInfo');
  var amount = jQuery('.price-set-row input').filter(':checked').attr('data-amount');
  if (amount) {
    amount = parseFloat(amount);
  } else {
    amount = parseFloat(jQuery('.other_amount-section input').val());
  }
  if (isNaN(amount)) {
    var monthlyValue = '';
  } else {
    var monthlyValue = (amount * 4.3).toFixed(2);
  }
  return monthlyValue;
}

function updateMonthlyValue() {
  var monthlyValue = getMonthlyValue();
  jQuery('#monthlyValue').text(monthlyValue);
}

/* IBAN magic */

function isIBANConverted(formId) {
  var ibanMagicPages = contribConfig.ibanMagicPages || [];
  return ibanMagicPages.indexOf(formId) >= 0;
}

var field_tpl = '

@@label@@*

<input size="34" maxlength="34" autocomplete="off" name="@@name@@" id="@@name@@" class="crm-form-text" type="text">

'

function addField(name, label) {
  var $iban = jQuery('.bank_account_number-section');
  var field = field_tpl.split('@@name@@').join(name);
  field = field.replace('@@label@@', label);
  $iban.before(field);
}

function replaceLetters(bban) {
  var value = '';
  var a = 'a'.charCodeAt(0) - 10;
  bban = bban.toLowerCase();
  for (var i = 0; i < bban.length; ++i) {
    var c = bban.charAt(i);
    var n = parseInt(c);
    if (isNaN(n)) n = bban.charCodeAt(i) - a;
    value = value + n;
  }
  return value;
}

function mod97(digits) {
  var value = 0;
  for (var i = 0; i < digits.length; ++i) {
    value = (10 * value + parseInt(digits.charAt(i))) % 97;
  }
  return value;
}

function getBBAN(country) {
  var bban = '';
  for (field_id in contribConfig.nationalFields[country]) {
    bban += jQuery('#' + field_id).val();
  }
  return bban;
}

function genIBAN(country) {
  var bban = getBBAN(country);
  var checkInput = replaceLetters(bban + country + '00');
  var checksum = (98 - mod97(checkInput)).toString();
  while (checksum.length < 2) checksum = '0' + checksum;
  return country + checksum + bban;
}

function enableNationalForm(country) {
  var switch_section =
    '
'
  +  '
'
  +   '<input id="SEPA_scheme" name="transfer_scheme" value="SEPA" type="radio" checked> '
  +   '' + contribConfig.translations['SEPA_transfer'] + ' '
  +   '<input id="National_scheme" name="transfer_scheme" value="national" type="radio"> '
  +   '' + contribConfig.translations['National_transfer'] + ''
  +  '
'
  +  '

'
  + '
';
  if (contribConfig.nationalFields[country]) {
    jQuery('.account_holder-section').before(switch_section);
    addNationalForm(country);
  }
}

function addNationalForm(country) {
  var fieldSelect = [];
  for (field_id in contribConfig.nationalFields[country]) {
    addField(field_id, contribConfig.nationalFields[country][field_id]);
    fieldSelect.push('.' + field_id + '-section');
  }
  fieldSelect = fieldSelect.join(', ');
  if (jQuery('input[name=transfer_scheme]').filter(':checked').val() === 'national') {
    jQuery(fieldSelect).show();
  }

  var $iban = jQuery('#bank_account_number');
  jQuery('input[name=transfer_scheme]').on('change', function (e) {
    jQuery(fieldSelect + ', .bank_account_number-section, .bank_identification_number-section').toggle();
    $iban.click();
  });

  jQuery(fieldSelect).on('keyup', function(e) {
    $iban.val(genIBAN(country));
    $iban.trigger('click');
  });
}

function updateNationalForm(country) {
  jQuery('.national-transfer input').off('change');
  jQuery('.national-transfer').remove();
  jQuery('input[name=transfer_scheme]').off('change');

  addNationalForm(country);
}

function readCountry(contribConfig) {
  var country = contribConfig.countries[jQuery('#country-1').val()];
  if (!country) country = contribConfig.language;
  return country;
}

function copyFrozenFields() {
  jQuery('.crm-frozen-field').each(function() {
    var $span = jQuery(this);
    var id = '#billing_' + jQuery('input', $span).attr('id');
    jQuery(id).val($span.text());
  });
}

jQuery(function($) {
  // Set by earlier in a drupal block
  var contribConfig = window.contribConfig || {};

  // set default amount based on param donation_amount in url
  var name = 'donation_amount';
  var da = getParam(name);
  if (da > 0) {
    da = da.replace('.', '\\.');
    jQuery(".price-set-row input[data-amount="+da+"]").prop("checked", true).click();
  }

  //Show / hide other amount input
  var $other = jQuery('.crm-container .crm-section.other_amount-section');
  if (jQuery('.price-set-row input[value=0]').is(':checked')) {
    $other.show();
  }
  jQuery('.price-set-row input').on('change', function(e) {
    var val = jQuery(this).val();
    if (val == 0) {
      $other.show();
    } else {
      $other.hide();
    }
  });

  if (isConvertedToMonthly()) {
    var $monthlyInfo = jQuery('

You will contribute €  per month

');
    jQuery('.other_amount-section').after($monthlyInfo);
    jQuery('.price-set-row input').on('change', function(e) {
      updateMonthlyValue();
    });
    jQuery('.other_amount-section input').on('keyup', function(e) {
      updateMonthlyValue();
    });
    updateMonthlyValue();

    jQuery('form#Main').on('submit', function(e) {
      jQuery('.other_amount-section input').val(getMonthlyValue());
      jQuery('.price-set-row input[value=0]').prop('checked', 'checked');
    });
  }

  /* Converting comma to dot in other amount field */
  jQuery(".other_amount-content input[name*=price]").change(function(e) {
    jQuery(this).val(jQuery(this).val().replace(/,/g,"."));
  });

  /* Set up IBAN magic */
  if (isIBANConverted(contribConfig.pageId)) {
    var $payProc = jQuery('input[name=payment_processor]');
    if (jQuery('.direct_debit_info-group').length) {
      var country = readCountry(contribConfig);
      enableNationalForm(country);
    }
    $payProc.on('change', function(e) {
      if ($payProc.filter(':checked').val() == '3') {
      	var country = readCountry(contribConfig);
      	enableNationalForm(country);
      }
    });
    CRM.$(function($) {
      $('#country-1').on('change', function(e) {
      	if ($payProc.filter(':checked').val() == '3') {
      	  var country = readCountry(contribConfig);
      	  updateNationalForm(country);
      	}
      });
    });
  }

  /* Pre-fill first name, last name and email */
  var fields = {
    1 : "first_name",
    2 : "last_name",
    3 : "email"
  };
  jQuery.each(fields, function(k, f) {
    var el = jQuery("input[name*="+f+"]");
    if (!el.val()) {
      el.val(getParam(f));
    }
  });
  /* pre-fill billing with frozen fields */
  if ($('#billingcheckbox').prop('checked')) {
    copyFrozenFields();
  }
  $('#billingcheckbox').click(function () {
    if (this.checked) {
      copyFrozenFields();
    }
  }

});
<commit_msg>fix copy of frozen fields<commit_after>
function getParam(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

/* Convert daily/weekly donations to monthly donations */

function isConvertedToMonthly() {
  var weeklyPages = contribConfig.weeklyPages || [];
  return weeklyPages.indexOf(contribConfig.pageId) >= 0;
}

function getMonthlyValue() {
  var $montlyInfo = jQuery('#monthlyInfo');
  var amount = jQuery('.price-set-row input').filter(':checked').attr('data-amount');
  if (amount) {
    amount = parseFloat(amount);
  } else {
    amount = parseFloat(jQuery('.other_amount-section input').val());
  }
  if (isNaN(amount)) {
    var monthlyValue = '';
  } else {
    var monthlyValue = (amount * 4.3).toFixed(2);
  }
  return monthlyValue;
}

function updateMonthlyValue() {
  var monthlyValue = getMonthlyValue();
  jQuery('#monthlyValue').text(monthlyValue);
}

/* IBAN magic */

function isIBANConverted(formId) {
  var ibanMagicPages = contribConfig.ibanMagicPages || [];
  return ibanMagicPages.indexOf(formId) >= 0;
}

var field_tpl = '

@@label@@*

<input size="34" maxlength="34" autocomplete="off" name="@@name@@" id="@@name@@" class="crm-form-text" type="text">

'

function addField(name, label) {
  var $iban = jQuery('.bank_account_number-section');
  var field = field_tpl.split('@@name@@').join(name);
  field = field.replace('@@label@@', label);
  $iban.before(field);
}

function replaceLetters(bban) {
  var value = '';
  var a = 'a'.charCodeAt(0) - 10;
  bban = bban.toLowerCase();
  for (var i = 0; i < bban.length; ++i) {
    var c = bban.charAt(i);
    var n = parseInt(c);
    if (isNaN(n)) n = bban.charCodeAt(i) - a;
    value = value + n;
  }
  return value;
}

function mod97(digits) {
  var value = 0;
  for (var i = 0; i < digits.length; ++i) {
    value = (10 * value + parseInt(digits.charAt(i))) % 97;
  }
  return value;
}

function getBBAN(country) {
  var bban = '';
  for (field_id in contribConfig.nationalFields[country]) {
    bban += jQuery('#' + field_id).val();
  }
  return bban;
}

function genIBAN(country) {
  var bban = getBBAN(country);
  var checkInput = replaceLetters(bban + country + '00');
  var checksum = (98 - mod97(checkInput)).toString();
  while (checksum.length < 2) checksum = '0' + checksum;
  return country + checksum + bban;
}

function enableNationalForm(country) {
  var switch_section =
    '
'
  +  '
'
  +   '<input id="SEPA_scheme" name="transfer_scheme" value="SEPA" type="radio" checked> '
  +   '' + contribConfig.translations['SEPA_transfer'] + ' '
  +   '<input id="National_scheme" name="transfer_scheme" value="national" type="radio"> '
  +   '' + contribConfig.translations['National_transfer'] + ''
  +  '
'
  +  '

'
  + '
';
  if (contribConfig.nationalFields[country]) {
    jQuery('.account_holder-section').before(switch_section);
    addNationalForm(country);
  }
}

function addNationalForm(country) {
  var fieldSelect = [];
  for (field_id in contribConfig.nationalFields[country]) {
    addField(field_id, contribConfig.nationalFields[country][field_id]);
    fieldSelect.push('.' + field_id + '-section');
  }
  fieldSelect = fieldSelect.join(', ');
  if (jQuery('input[name=transfer_scheme]').filter(':checked').val() === 'national') {
    jQuery(fieldSelect).show();
  }

  var $iban = jQuery('#bank_account_number');
  jQuery('input[name=transfer_scheme]').on('change', function (e) {
    jQuery(fieldSelect + ', .bank_account_number-section, .bank_identification_number-section').toggle();
    $iban.click();
  });

  jQuery(fieldSelect).on('keyup', function(e) {
    $iban.val(genIBAN(country));
    $iban.trigger('click');
  });
}

function updateNationalForm(country) {
  jQuery('.national-transfer input').off('change');
  jQuery('.national-transfer').remove();
  jQuery('input[name=transfer_scheme]').off('change');

  addNationalForm(country);
}

function readCountry(contribConfig) {
  var country = contribConfig.countries[jQuery('#country-1').val()];
  if (!country) country = contribConfig.language;
  return country;
}

function copyFrozenFields() {
  jQuery('.crm-frozen-field').each(function() {
    var $span = jQuery(this);
    var id = '#billing_' + jQuery('input', $span).attr('id');
    jQuery(id).val($span.text());
  });
}

jQuery(function($) {
  // Set by earlier in a drupal block
  var contribConfig = window.contribConfig || {};

  // set default amount based on param donation_amount in url
  var name = 'donation_amount';
  var da = getParam(name);
  if (da > 0) {
    da = da.replace('.', '\\.');
    jQuery(".price-set-row input[data-amount="+da+"]").prop("checked", true).click();
  }

  //Show / hide other amount input
  var $other = jQuery('.crm-container .crm-section.other_amount-section');
  if (jQuery('.price-set-row input[value=0]').is(':checked')) {
    $other.show();
  }
  jQuery('.price-set-row input').on('change', function(e) {
    var val = jQuery(this).val();
    if (val == 0) {
      $other.show();
    } else {
      $other.hide();
    }
  });

  if (isConvertedToMonthly()) {
    var $monthlyInfo = jQuery('

You will contribute €  per month

');
    jQuery('.other_amount-section').after($monthlyInfo);
    jQuery('.price-set-row input').on('change', function(e) {
      updateMonthlyValue();
    });
    jQuery('.other_amount-section input').on('keyup', function(e) {
      updateMonthlyValue();
    });
    updateMonthlyValue();

    jQuery('form#Main').on('submit', function(e) {
      jQuery('.other_amount-section input').val(getMonthlyValue());
      jQuery('.price-set-row input[value=0]').prop('checked', 'checked');
    });
  }

  /* Converting comma to dot in other amount field */
  jQuery(".other_amount-content input[name*=price]").change(function(e) {
    jQuery(this).val(jQuery(this).val().replace(/,/g,"."));
  });

  /* Set up IBAN magic */
  if (isIBANConverted(contribConfig.pageId)) {
    var $payProc = jQuery('input[name=payment_processor]');
    if (jQuery('.direct_debit_info-group').length) {
      var country = readCountry(contribConfig);
      enableNationalForm(country);
    }
    $payProc.on('change', function(e) {
      if ($payProc.filter(':checked').val() == '3') {
      	var country = readCountry(contribConfig);
      	enableNationalForm(country);
      }
    });
    CRM.$(function($) {
      $('#country-1').on('change', function(e) {
      	if ($payProc.filter(':checked').val() == '3') {
      	  var country = readCountry(contribConfig);
      	  updateNationalForm(country);
      	}
      });
    });
  }

  /* Pre-fill first name, last name and email */
  var fields = {
    1 : "first_name",
    2 : "last_name",
    3 : "email"
  };
  jQuery.each(fields, function(k, f) {
    var el = jQuery("input[name*="+f+"]");
    if (!el.val()) {
      el.val(getParam(f));
    }
  });
  /* pre-fill billing with frozen fields */
  if ($('#billingcheckbox').prop('checked')) {
    copyFrozenFields();
  }
  $('#billingcheckbox').click(function () {
    if (this.checked) {
      copyFrozenFields();
    }
  });

});
<|endoftext|>


<commit_before>/**
 Copyright 2014 Gordon Williams (gw@pur3.co.uk)

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

 ------------------------------------------------------------------
  Handling the getting and setting of code
 ------------------------------------------------------------------
**/
"use strict";
(function(){

  function init() {
    // Configuration
    Espruino.Core.Config.add("AUTO_SAVE_CODE", {
      section : "Communications",
      name : "Auto Save",
      description : "Save code to Chrome's cloud storage when clicking 'Send to Espruino'?",
      type : "boolean",
      defaultValue : 20,
    });
    // get code from our config area at bootup
    setTimeout(function() {
      var code;
      if (Espruino.Config.CODE) {
        code = Espruino.Config.CODE;
        console.log("Loaded code from storage.");
      } else {
        code = "var  l = false;\nsetInterval(function() {\n  l = !l;\n  LED1.write(l);\n}, 500);";
        console.log("No code in storage.");
      }
      Espruino.Core.EditorJavaScript.setCode(code);
    },1);

    Espruino.addProcessor("sending", function(data, callback) {
      if(Espruino.Config.AUTO_SAVE_CODE)
        Espruino.Config.set("CODE", Espruino.Core.EditorJavaScript.getCode()); // save the code
      callback(data);
    });
  }

  function getEspruinoCode(callback) {
    Espruino.callProcessor("transformForEspruino", getCurrentCode(), callback);
  }

  function getCurrentCode() {
    if (Espruino.Core.Layout.isInBlockly()) {
      return Espruino.Core.EditorBlockly.getCode();
    } else {
      return Espruino.Core.EditorJavaScript.getCode();
    }
  }

  Espruino.Core.Code = {
    init : init,
    getEspruinoCode : getEspruinoCode, // get the currently selected bit of code ready to send to Espruino (including Modules)
    getCurrentCode : getCurrentCode, // get the currently selected bit of code (either blockly or javascript editor)
  };
}());<commit_msg>use initialised signal rather than timeout...<commit_after>/**
 Copyright 2014 Gordon Williams (gw@pur3.co.uk)

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

 ------------------------------------------------------------------
  Handling the getting and setting of code
 ------------------------------------------------------------------
**/
"use strict";
(function(){

  function init() {
    // Configuration
    Espruino.Core.Config.add("AUTO_SAVE_CODE", {
      section : "Communications",
      name : "Auto Save",
      description : "Save code to Chrome's cloud storage when clicking 'Send to Espruino'?",
      type : "boolean",
      defaultValue : 20,
    });
    // get code from our config area at bootup
    Espruino.addProcessor("initialised", function(data,callback) {
      var code;
      if (Espruino.Config.CODE) {
        code = Espruino.Config.CODE;
        console.log("Loaded code from storage.");
      } else {
        code = "var  l = false;\nsetInterval(function() {\n  l = !l;\n  LED1.write(l);\n}, 500);";
        console.log("No code in storage.");
      }
      Espruino.Core.EditorJavaScript.setCode(code);
      callback(data);
    });

    Espruino.addProcessor("sending", function(data, callback) {
      if(Espruino.Config.AUTO_SAVE_CODE)
        Espruino.Config.set("CODE", Espruino.Core.EditorJavaScript.getCode()); // save the code
      callback(data);
    });
  }

  function getEspruinoCode(callback) {
    Espruino.callProcessor("transformForEspruino", getCurrentCode(), callback);
  }

  function getCurrentCode() {
    if (Espruino.Core.Layout.isInBlockly()) {
      return Espruino.Core.EditorBlockly.getCode();
    } else {
      return Espruino.Core.EditorJavaScript.getCode();
    }
  }

  Espruino.Core.Code = {
    init : init,
    getEspruinoCode : getEspruinoCode, // get the currently selected bit of code ready to send to Espruino (including Modules)
    getCurrentCode : getCurrentCode, // get the currently selected bit of code (either blockly or javascript editor)
  };
}());<|endoftext|>


<commit_before>import React from 'react';

// Redux
import withRedux from 'next-redux-wrapper';
import { initStore } from 'store';
import { setUser } from 'redactions/user';
import { setRouter } from 'redactions/routes';
import { fetchDashboard } from 'components/dashboards/detail/dashboard-detail-actions';
import { fetchDashboards, setSelected, setExpanded, setPagination } from 'components/dashboards/thumbnail-list/dashboard-thumbnail-list-actions';

// Components
import Page from 'components/app/layout/Page';
import Layout from 'components/app/layout/Layout';
import Breadcrumbs from 'components/ui/Breadcrumbs';

import DashboardThumbnailList from 'components/dashboards/thumbnail-list/dashboard-thumbnail-list';
import DashboardDetail from 'components/dashboards/detail/dashboard-detail';

class DashboardsDetail extends Page {
  static async getInitialProps({ asPath, pathname, query, req, store, isServer }) {
    const { user } = isServer ? req : store.getState();
    const url = { asPath, pathname, query };
    await store.dispatch(setUser(user));
    store.dispatch(setRouter(url));

    store.dispatch(setPagination(true));
    await store.dispatch(fetchDashboard({ id: url.query.slug }));
    await store.dispatch(setSelected(url.query.slug));
    await store.dispatch(fetchDashboards({
      filters: { 'filter[published]': 'true' }
    }));

    return { isServer, user, url };
  }

  render() {
    const { dashboardDetail } = this.props;

    return (
      <Layout
        title={dashboardDetail.dashboard.name}
        description={dashboardDetail.dashboard.summary}
        url={this.props.url}
        user={this.props.user}
        pageHeader
        className="page-dashboards c-page-dashboards"
      >

                  <Breadcrumbs items={[{ name: 'Data', href: '/data/dashboards' }]} />

{dashboardDetail.dashboard.name}

                <DashboardThumbnailList
                  onSelect={({ slug }) => {
                    // We need to make an amendment to have this working
                    // Router.pushRoute('dashboards_detail', { slug });
                    window.location = `/data/dashboards/${slug}`;
                  }}
                  onExpand={(bool) => {
                    this.props.setExpanded(bool);
                  }}
                />

                <DashboardDetail />

      </Layout>
    );
  }
}

const mapStateToProps = state => ({
  dashboardDetail: state.dashboardDetail
});

const mapDispatchToProps = {
  fetchDashboard,
  fetchDashboards,
  setSelected,
  setExpanded,
  setPagination
};

export default withRedux(initStore, mapStateToProps, mapDispatchToProps)(DashboardsDetail);
<commit_msg>Dashboard detail: remove thumbnail list<commit_after>import React from 'react';

// Redux
import withRedux from 'next-redux-wrapper';
import { initStore } from 'store';
import { setUser } from 'redactions/user';
import { setRouter } from 'redactions/routes';
import { fetchDashboard } from 'components/dashboards/detail/dashboard-detail-actions';

// Components
import Page from 'components/app/layout/Page';
import Layout from 'components/app/layout/Layout';
import Breadcrumbs from 'components/ui/Breadcrumbs';

import DashboardDetail from 'components/dashboards/detail/dashboard-detail';

class DashboardsDetail extends Page {
  static async getInitialProps({ asPath, pathname, query, req, store, isServer }) {
    const { user } = isServer ? req : store.getState();
    const url = { asPath, pathname, query };
    await store.dispatch(setUser(user));
    store.dispatch(setRouter(url));

    await store.dispatch(fetchDashboard({ id: url.query.slug }));

    return { isServer, user, url };
  }

  render() {
    const { dashboardDetail } = this.props;

    return (
      <Layout
        title={dashboardDetail.dashboard.name}
        description={dashboardDetail.dashboard.summary}
        url={this.props.url}
        user={this.props.user}
        pageHeader
        className="page-dashboards c-page-dashboards"
      >

                  <Breadcrumbs items={[{ name: 'Data', href: '/data/dashboards' }]} />

{dashboardDetail.dashboard.name}

                <DashboardDetail />

      </Layout>
    );
  }
}

const mapStateToProps = state => ({
  dashboardDetail: state.dashboardDetail
});

const mapDispatchToProps = {
  fetchDashboard
};

export default withRedux(initStore, mapStateToProps, mapDispatchToProps)(DashboardsDetail);
<|endoftext|>


<commit_before>// Gets data from provided url and updates DOM element.
function generate_os_data(url, element) {
    $.get(url, function (data) {
        $(element).text(data);
    }, "json");
}

// If dataTable with provided ID exists, destroy it.
function destroy_dataTable(table_id) {
    var table = $("#" + table_id);
    var ex = document.getElementById(table_id);
    if ($.fn.DataTable.fnIsDataTable(ex)) {
        table.hide().dataTable().fnClearTable();
        table.dataTable().fnDestroy();
    }
}

//DataTables
//Sort file size data.
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "file-size-units": {
        K: 1024,
        M: Math.pow(1024, 2),
        G: Math.pow(1024, 3),
        T: Math.pow(1024, 4),
        P: Math.pow(1024, 5),
        E: Math.pow(1024, 6)
    },

    "file-size-pre": function (a) {
        var x = a.substring(0, a.length - 1);
        var x_unit = a.substring(a.length - 1, a.length);
        if (jQuery.fn.dataTableExt.oSort['file-size-units'][x_unit]) {
            return parseInt(x * jQuery.fn.dataTableExt.oSort['file-size-units'][x_unit], 10);
        }
        else {
            return parseInt(x + x_unit, 10);
        }
    },

    "file-size-asc": function (a, b) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },

    "file-size-desc": function (a, b) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
});

//DataTables
//Sort numeric data which has a percent sign with it.
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "percent-pre": function (a) {
        var x = (a === "-") ? 0 : a.replace(/%/, "");
        return parseFloat(x);
    },

    "percent-asc": function (a, b) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },

    "percent-desc": function (a, b) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
});

//DataTables
//Sort IP addresses
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "ip-address-pre": function (a) {
        // split the address into octets
        //
        var x = a.split('.');

        // pad each of the octets to three digits in length
        //
        function zeroPad(num, places) {
            var zero = places - num.toString().length + 1;
            return Array(+(zero > 0 && zero)).join("0") + num;
        }

        // build the resulting IP
        var r = '';
        for (var i = 0; i < x.length; i++)
            r = r + zeroPad(x[i], 3);

        // return the formatted IP address
        //
        return r;
    },

    "ip-address-asc": function (a, b) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },

    "ip-address-desc": function (a, b) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
});

/*******************************
 Data Call Functions
 *******************************/

var dashboard = {};

dashboard.getPs = function () {
    $.get("sh/ps.php", function (data) {
        destroy_dataTable("ps_dashboard");
        $("#filter-ps").val("").off("keyup");

        var psTable = $("#ps_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "USER" },
                { sTitle: "PID" },
                { sTitle: "%CPU" },
                { sTitle: "%MEM" },
                { sTitle: "VSZ" },
                { sTitle: "RSS" },
                { sTitle: "TTY" },
                { sTitle: "STAT" },
                { sTitle: "START" },
                { sTitle: "TIME" },
                { sTitle: "COMMAND" }
            ],
            bPaginate: true,
            sPaginationType: "full_numbers",
            bFilter: true,
            sDom: "lrtip",
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();

        $("#filter-ps").on("keyup", function () {
            psTable.fnFilter(this.value);
        });
    }, "json");
}

dashboard.getNetStat = function () {
    $.get("sh/netstat.php", function (data) {
        destroy_dataTable("netstat_dashboard");

        $("#netstat_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Number of Connections" },
                { sTitle: "IP Address" }
            ],
            aaSorting: [
                [0, "desc"]
            ],
            bPaginate: true,
            sPaginationType: "full_numbers",
            bFilter: true,
            sDom: "lrtip",
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();
    }, "json");
}

dashboard.getUsers = function () {
    $.get("sh/users.php", function (data) {
        destroy_dataTable("users_dashboard");

        $("#users_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Type" },
                { sTitle: "User" },
                { sTitle: "Home" }
            ],
            aaSorting: [
                [0, "desc"]
            ],
            iDisplayLength: 5,
            bPaginate: true,
            sPaginationType: "full_numbers",
            bFilter: false,
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();
    }, "json");
    $("select[name='users_dashboard_length']").val("5");
}

dashboard.getOnline = function () {
    $.get("sh/online.php", function (data) {
        destroy_dataTable("online_dashboard");

        $("#online_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Who" },
                { sTitle: "From" },
                { sTitle: "Login At" },
                { sTitle: "Idle" }
            ],
            aaSorting: [
                [0, "desc"]
            ],
            iDisplayLength: 5,
            bPaginate: true,
            sPaginationType: "full_numbers",
            bFilter: false,
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();
    }, "json");
    $("select[name='online_dashboard_length']").val("5");
}

dashboard.getLastLog = function () {
    $.get("sh/lastlog.php", function (data) {
        destroy_dataTable("lastlog_dashboard");

        $("#lastlog_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Who" },
                { sTitle: "From" },
                { sTitle: "When" },
            ],
            aaSorting: [
                [2, "desc"]
            ],
            iDisplayLength: 5,
            bPaginate: true,
            sPaginationType: "full_numbers",
            bFilter: false,
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();
    }, "json");
    $("select[name='lastlog_dashboard_length']").val("5");
}

dashboard.getRam = function () {
    $.get("sh/mem.php", function (data) {
        var ram_total = data[1];
        var ram_used = Math.round((data[2] / ram_total) * 100);
        var ram_free = Math.round((data[3] / ram_total) * 100);

        $("#ram-total").text(ram_total);
        $("#ram-used").text(data[2]);
        $("#ram-free").text(data[3]);

        $("#ram-free-per").text(ram_free);
        $("#ram-used-per").text(ram_used);
    }, "json");
}

dashboard.getDf = function () {
    $.get("sh/df.php", function (data) {
        var table = $("#df_dashboard");
        var ex = document.getElementById("df_dashboard");
        if ($.fn.DataTable.fnIsDataTable(ex)) {
            table.hide().dataTable().fnClearTable();
            table.dataTable().fnDestroy();
        }

        table.dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Filesystem" },
                { sTitle: "Size", sType: "file-size" },
                { sTitle: "Used", sType: "file-size" },
                { sTitle: "Avail", sType: "file-size" },
                { sTitle: "Use%", sType: "percent" },
                { sTitle: "Mounted" }
            ],
            bPaginate: false,
            bFilter: false,
            bAutoWidth: true,
            bInfo: false
        }).fadeIn();
    }, "json");
}

dashboard.getWhereIs = function () {
    $.get("sh/where.php", function (data) {
        var table = $("#whereis_dashboard");
        var ex = document.getElementById("whereis_dashboard");
        if ($.fn.DataTable.fnIsDataTable(ex)) {
            table.hide().dataTable().fnClearTable();
            table.dataTable().fnDestroy();
        }

        table.dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Software" },
                { sTitle: "Installation" }
            ],
            bPaginate: true,
            iDisplayLength: 6,
            bFilter: false,
            aaSorting: [
                [1, "desc"]
            ],
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();
    }, "json");
}

dashboard.getOs = function () {
    generate_os_data("sh/issue.php", "#os-info");
    generate_os_data("sh/hostname.php", "#os-hostname");
    generate_os_data("sh/time.php", "#os-time");
    generate_os_data("sh/uptime.php", "#os-uptime");
}

dashboard.getIp = function () {
    $.get("sh/ip.php", function (data) {
        destroy_dataTable("ip_dashboard");
        $("#ip_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Interface" },
                { sTitle: "IP" }
            ],
            iDisplayLength: 5,
            bPaginate: true,
            sPaginationType: "two_button",
            bFilter: false,
            bAutoWidth: true,
            bInfo: false
        }).fadeIn();
    }, "json");
}

dashboard.getPing = function () {
    var refreshIcon = $('#refresh-ping .icon-refresh');
    refreshIcon.addClass('icon-spin');

    $.ajax({
        url: 'sh/ping.php',
        cache: false,
        success: function (data) {
            destroy_dataTable("ping_dashboard");

            $("#ping_dashboard").dataTable({
                aaData: data,
                aoColumns: [
                    { sTitle: "Host" },
                    { sTitle: "Time (in ms)" }
                ],
                aaSorting: [
                    [0, "desc"]
                ],
                bPaginate: true,
                sPaginationType: "full_numbers",
                bFilter: true,
                sDom: "lrtip",
                bAutoWidth: false,
                bInfo: false
            }).fadeIn();
        },
        complete: function() {
            refreshIcon.removeClass('icon-spin');
        }
    });
}

dashboard.getIspeed = function () {
    var rateUpstream = $("#ispeed-rate-upstream");
    var rateDownstream = $("#ispeed-rate-downstream");
    var refreshIcon = $("#refresh-ispeed .icon-refresh");

    // 0 = KB
    // 1 = MB
    var AS = 0;
    var power = AS + 1;
    var result = { 'upstream' :0, 'downstream':0};

    refreshIcon.addClass('icon-spin');

    $.ajax({
        url: 'sh/speed.php',
        cache: false,
        success: function(data) {
            // round the speed (float to int);
            // dependent on value of AS, calculate speed in MB or KB ps
            result['upstream'] = Math.floor((data['upstream'] / (Math.pow(1024, power))));
            result['downstream'] = Math.floor((data['downstream'] / (Math.pow(1024, power))));
            // update rate of speed on widget
            rateUpstream.text(result['upstream']);
            rateDownstream.text(result['downstream']);
        },
        complete: function() {
            refreshIcon.removeClass('icon-spin');
        }
    });

    // update unit value in widget
    var leadUpstream = rateUpstream.next(".lead");
    var leadDownstream = rateDownstream.next(".lead");
    leadUpstream.text(AS ? "MB/s" : "KB/s");
    leadDownstream.text(AS ? "MB/s" : "KB/s");
}

dashboard.getLoadAverage = function () {
    $.get("sh/loadavg.php", function (data) {
        $("#cpu-1min").text(data[0][0]);
        $("#cpu-5min").text(data[1][0]);
        $("#cpu-15min").text(data[2][0]);
        $("#cpu-1min-per").text(data[0][1]);
        $("#cpu-5min-per").text(data[1][1]);
        $("#cpu-15min-per").text(data[2][1]);
    }, "json");
    generate_os_data("sh/numberofcores.php", "#core-number");
}

dashboard.getDnsmasqLeases = function () {
    $.get("sh/dnsmasq-leases.php", function (data) {
        var table = $("#dnsmasqleases_dashboard");
        var ex = document.getElementById("dnsmasqleases_dashboard");
        if ($.fn.DataTable.fnIsDataTable(ex)) {
            table.hide().dataTable().fnClearTable();
            table.dataTable().fnDestroy();
        }

        table.dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Expires At" },
                { sTitle: "MAC Address" },
                { sTitle: "IP Address", sType: "ip-address" },
                { sTitle: "Hostname" }
            ],
            bPaginate: false,
            bFilter: false,
            bAutoWidth: true,
            bInfo: false
        }).fadeIn();
    }, "json");
}

dashboard.getBandwidth = function () {
    var refreshIcon = $('#refresh-bandwidth .icon-refresh');
    refreshIcon.addClass('icon-spin');

    $.ajax({
        url: 'sh/bandwidth.php',
        cache: false,
        success: function (data) {
            $('#bw-tx').text(data.tx);
            $('#bw-rx').text(data.rx);
        },
        complete: function() {
            refreshIcon.removeClass('icon-spin');
        }
    });

}

/**
 * Refreshes all widgets. Does not call itself recursively.
 */
dashboard.getAll = function () {
    for (var item in dashboard.fnMap) {
        if (dashboard.fnMap.hasOwnProperty(item) && item !== "all") {
            dashboard.fnMap[item]();
        }
    }
}

dashboard.fnMap = {
    all: dashboard.getAll,
    ram: dashboard.getRam,
    ps: dashboard.getPs,
    df: dashboard.getDf,
    os: dashboard.getOs,
    users: dashboard.getUsers,
    online: dashboard.getOnline,
    lastlog: dashboard.getLastLog,
    whereis: dashboard.getWhereIs,
    ip: dashboard.getIp,
    ispeed: dashboard.getIspeed,
    cpu: dashboard.getLoadAverage,
    netstat: dashboard.getNetStat,
    dnsmasqleases: dashboard.getDnsmasqLeases,
    bandwidth: dashboard.getBandwidth,
    ping: dashboard.getPing
};
<commit_msg>limit netstat widget to 5 item a page<commit_after>// Gets data from provided url and updates DOM element.
function generate_os_data(url, element) {
    $.get(url, function (data) {
        $(element).text(data);
    }, "json");
}

// If dataTable with provided ID exists, destroy it.
function destroy_dataTable(table_id) {
    var table = $("#" + table_id);
    var ex = document.getElementById(table_id);
    if ($.fn.DataTable.fnIsDataTable(ex)) {
        table.hide().dataTable().fnClearTable();
        table.dataTable().fnDestroy();
    }
}

//DataTables
//Sort file size data.
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "file-size-units": {
        K: 1024,
        M: Math.pow(1024, 2),
        G: Math.pow(1024, 3),
        T: Math.pow(1024, 4),
        P: Math.pow(1024, 5),
        E: Math.pow(1024, 6)
    },

    "file-size-pre": function (a) {
        var x = a.substring(0, a.length - 1);
        var x_unit = a.substring(a.length - 1, a.length);
        if (jQuery.fn.dataTableExt.oSort['file-size-units'][x_unit]) {
            return parseInt(x * jQuery.fn.dataTableExt.oSort['file-size-units'][x_unit], 10);
        }
        else {
            return parseInt(x + x_unit, 10);
        }
    },

    "file-size-asc": function (a, b) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },

    "file-size-desc": function (a, b) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
});

//DataTables
//Sort numeric data which has a percent sign with it.
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "percent-pre": function (a) {
        var x = (a === "-") ? 0 : a.replace(/%/, "");
        return parseFloat(x);
    },

    "percent-asc": function (a, b) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },

    "percent-desc": function (a, b) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
});

//DataTables
//Sort IP addresses
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "ip-address-pre": function (a) {
        // split the address into octets
        //
        var x = a.split('.');

        // pad each of the octets to three digits in length
        //
        function zeroPad(num, places) {
            var zero = places - num.toString().length + 1;
            return Array(+(zero > 0 && zero)).join("0") + num;
        }

        // build the resulting IP
        var r = '';
        for (var i = 0; i < x.length; i++)
            r = r + zeroPad(x[i], 3);

        // return the formatted IP address
        //
        return r;
    },

    "ip-address-asc": function (a, b) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },

    "ip-address-desc": function (a, b) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
});

/*******************************
 Data Call Functions
 *******************************/

var dashboard = {};

dashboard.getPs = function () {
    $.get("sh/ps.php", function (data) {
        destroy_dataTable("ps_dashboard");
        $("#filter-ps").val("").off("keyup");

        var psTable = $("#ps_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "USER" },
                { sTitle: "PID" },
                { sTitle: "%CPU" },
                { sTitle: "%MEM" },
                { sTitle: "VSZ" },
                { sTitle: "RSS" },
                { sTitle: "TTY" },
                { sTitle: "STAT" },
                { sTitle: "START" },
                { sTitle: "TIME" },
                { sTitle: "COMMAND" }
            ],
            bPaginate: true,
            sPaginationType: "full_numbers",
            bFilter: true,
            sDom: "lrtip",
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();

        $("#filter-ps").on("keyup", function () {
            psTable.fnFilter(this.value);
        });
    }, "json");
}

dashboard.getNetStat = function () {
    $.get("sh/netstat.php", function (data) {
        destroy_dataTable("netstat_dashboard");

        $("#netstat_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Number of Connections" },
                { sTitle: "IP Address" }
            ],
            aaSorting: [
                [0, "desc"]
            ],
            iDisplayLength: 5,
            bPaginate: true,
            sPaginationType: "full_numbers",
            bFilter: true,
            sDom: "lrtip",
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();
    }, "json");
}

dashboard.getUsers = function () {
    $.get("sh/users.php", function (data) {
        destroy_dataTable("users_dashboard");

        $("#users_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Type" },
                { sTitle: "User" },
                { sTitle: "Home" }
            ],
            aaSorting: [
                [0, "desc"]
            ],
            iDisplayLength: 5,
            bPaginate: true,
            sPaginationType: "full_numbers",
            bFilter: false,
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();
    }, "json");
    $("select[name='users_dashboard_length']").val("5");
}

dashboard.getOnline = function () {
    $.get("sh/online.php", function (data) {
        destroy_dataTable("online_dashboard");

        $("#online_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Who" },
                { sTitle: "From" },
                { sTitle: "Login At" },
                { sTitle: "Idle" }
            ],
            aaSorting: [
                [0, "desc"]
            ],
            iDisplayLength: 5,
            bPaginate: true,
            sPaginationType: "full_numbers",
            bFilter: false,
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();
    }, "json");
    $("select[name='online_dashboard_length']").val("5");
}

dashboard.getLastLog = function () {
    $.get("sh/lastlog.php", function (data) {
        destroy_dataTable("lastlog_dashboard");

        $("#lastlog_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Who" },
                { sTitle: "From" },
                { sTitle: "When" },
            ],
            aaSorting: [
                [2, "desc"]
            ],
            iDisplayLength: 5,
            bPaginate: true,
            sPaginationType: "full_numbers",
            bFilter: false,
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();
    }, "json");
    $("select[name='lastlog_dashboard_length']").val("5");
}

dashboard.getRam = function () {
    $.get("sh/mem.php", function (data) {
        var ram_total = data[1];
        var ram_used = Math.round((data[2] / ram_total) * 100);
        var ram_free = Math.round((data[3] / ram_total) * 100);

        $("#ram-total").text(ram_total);
        $("#ram-used").text(data[2]);
        $("#ram-free").text(data[3]);

        $("#ram-free-per").text(ram_free);
        $("#ram-used-per").text(ram_used);
    }, "json");
}

dashboard.getDf = function () {
    $.get("sh/df.php", function (data) {
        var table = $("#df_dashboard");
        var ex = document.getElementById("df_dashboard");
        if ($.fn.DataTable.fnIsDataTable(ex)) {
            table.hide().dataTable().fnClearTable();
            table.dataTable().fnDestroy();
        }

        table.dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Filesystem" },
                { sTitle: "Size", sType: "file-size" },
                { sTitle: "Used", sType: "file-size" },
                { sTitle: "Avail", sType: "file-size" },
                { sTitle: "Use%", sType: "percent" },
                { sTitle: "Mounted" }
            ],
            bPaginate: false,
            bFilter: false,
            bAutoWidth: true,
            bInfo: false
        }).fadeIn();
    }, "json");
}

dashboard.getWhereIs = function () {
    $.get("sh/where.php", function (data) {
        var table = $("#whereis_dashboard");
        var ex = document.getElementById("whereis_dashboard");
        if ($.fn.DataTable.fnIsDataTable(ex)) {
            table.hide().dataTable().fnClearTable();
            table.dataTable().fnDestroy();
        }

        table.dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Software" },
                { sTitle: "Installation" }
            ],
            bPaginate: true,
            iDisplayLength: 6,
            bFilter: false,
            aaSorting: [
                [1, "desc"]
            ],
            bAutoWidth: false,
            bInfo: false
        }).fadeIn();
    }, "json");
}

dashboard.getOs = function () {
    generate_os_data("sh/issue.php", "#os-info");
    generate_os_data("sh/hostname.php", "#os-hostname");
    generate_os_data("sh/time.php", "#os-time");
    generate_os_data("sh/uptime.php", "#os-uptime");
}

dashboard.getIp = function () {
    $.get("sh/ip.php", function (data) {
        destroy_dataTable("ip_dashboard");
        $("#ip_dashboard").dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Interface" },
                { sTitle: "IP" }
            ],
            iDisplayLength: 5,
            bPaginate: true,
            sPaginationType: "two_button",
            bFilter: false,
            bAutoWidth: true,
            bInfo: false
        }).fadeIn();
    }, "json");
}

dashboard.getPing = function () {
    var refreshIcon = $('#refresh-ping .icon-refresh');
    refreshIcon.addClass('icon-spin');

    $.ajax({
        url: 'sh/ping.php',
        cache: false,
        success: function (data) {
            destroy_dataTable("ping_dashboard");

            $("#ping_dashboard").dataTable({
                aaData: data,
                aoColumns: [
                    { sTitle: "Host" },
                    { sTitle: "Time (in ms)" }
                ],
                aaSorting: [
                    [0, "desc"]
                ],
                bPaginate: true,
                sPaginationType: "full_numbers",
                bFilter: true,
                sDom: "lrtip",
                bAutoWidth: false,
                bInfo: false
            }).fadeIn();
        },
        complete: function() {
            refreshIcon.removeClass('icon-spin');
        }
    });
}

dashboard.getIspeed = function () {
    var rateUpstream = $("#ispeed-rate-upstream");
    var rateDownstream = $("#ispeed-rate-downstream");
    var refreshIcon = $("#refresh-ispeed .icon-refresh");

    // 0 = KB
    // 1 = MB
    var AS = 0;
    var power = AS + 1;
    var result = { 'upstream' :0, 'downstream':0};

    refreshIcon.addClass('icon-spin');

    $.ajax({
        url: 'sh/speed.php',
        cache: false,
        success: function(data) {
            // round the speed (float to int);
            // dependent on value of AS, calculate speed in MB or KB ps
            result['upstream'] = Math.floor((data['upstream'] / (Math.pow(1024, power))));
            result['downstream'] = Math.floor((data['downstream'] / (Math.pow(1024, power))));
            // update rate of speed on widget
            rateUpstream.text(result['upstream']);
            rateDownstream.text(result['downstream']);
        },
        complete: function() {
            refreshIcon.removeClass('icon-spin');
        }
    });

    // update unit value in widget
    var leadUpstream = rateUpstream.next(".lead");
    var leadDownstream = rateDownstream.next(".lead");
    leadUpstream.text(AS ? "MB/s" : "KB/s");
    leadDownstream.text(AS ? "MB/s" : "KB/s");
}

dashboard.getLoadAverage = function () {
    $.get("sh/loadavg.php", function (data) {
        $("#cpu-1min").text(data[0][0]);
        $("#cpu-5min").text(data[1][0]);
        $("#cpu-15min").text(data[2][0]);
        $("#cpu-1min-per").text(data[0][1]);
        $("#cpu-5min-per").text(data[1][1]);
        $("#cpu-15min-per").text(data[2][1]);
    }, "json");
    generate_os_data("sh/numberofcores.php", "#core-number");
}

dashboard.getDnsmasqLeases = function () {
    $.get("sh/dnsmasq-leases.php", function (data) {
        var table = $("#dnsmasqleases_dashboard");
        var ex = document.getElementById("dnsmasqleases_dashboard");
        if ($.fn.DataTable.fnIsDataTable(ex)) {
            table.hide().dataTable().fnClearTable();
            table.dataTable().fnDestroy();
        }

        table.dataTable({
            aaData: data,
            aoColumns: [
                { sTitle: "Expires At" },
                { sTitle: "MAC Address" },
                { sTitle: "IP Address", sType: "ip-address" },
                { sTitle: "Hostname" }
            ],
            bPaginate: false,
            bFilter: false,
            bAutoWidth: true,
            bInfo: false
        }).fadeIn();
    }, "json");
}

dashboard.getBandwidth = function () {
    var refreshIcon = $('#refresh-bandwidth .icon-refresh');
    refreshIcon.addClass('icon-spin');

    $.ajax({
        url: 'sh/bandwidth.php',
        cache: false,
        success: function (data) {
            $('#bw-tx').text(data.tx);
            $('#bw-rx').text(data.rx);
        },
        complete: function() {
            refreshIcon.removeClass('icon-spin');
        }
    });

}

/**
 * Refreshes all widgets. Does not call itself recursively.
 */
dashboard.getAll = function () {
    for (var item in dashboard.fnMap) {
        if (dashboard.fnMap.hasOwnProperty(item) && item !== "all") {
            dashboard.fnMap[item]();
        }
    }
}

dashboard.fnMap = {
    all: dashboard.getAll,
    ram: dashboard.getRam,
    ps: dashboard.getPs,
    df: dashboard.getDf,
    os: dashboard.getOs,
    users: dashboard.getUsers,
    online: dashboard.getOnline,
    lastlog: dashboard.getLastLog,
    whereis: dashboard.getWhereIs,
    ip: dashboard.getIp,
    ispeed: dashboard.getIspeed,
    cpu: dashboard.getLoadAverage,
    netstat: dashboard.getNetStat,
    dnsmasqleases: dashboard.getDnsmasqLeases,
    bandwidth: dashboard.getBandwidth,
    ping: dashboard.getPing
};
<|endoftext|>


<commit_before>
/*
On this page JavaScript changes the class on two HTML  (cbp-vm-grid) and (cbp-vm-list) and a

when the icon is clicked.

There are two icons that when clicked change the view of the page. They do this by having JavaScript
add "cbp-vm-selected" to the class of the icon that was clicked.

One icon is a list view and when clicked javascript appends it's class AND the class of the div
to show it is the list icon that is selected.When it does the CSS rules for the list class display.

The other icon is a grid. When it is clicked javascript appends its class to "cbp-vm-selected" and adds
"cbp-vm-view-grid" to the div which then triggers the CSS rule to apply the grid styling to the div.

Like I wrote in the Nested Accordian scripts.js, I don't really understand DOMs however I imagine that a window object would be called for in this case
because the page is open in a tab on my browser which is a window.

Also the document object would be the entry point into the web pages' content i.e. it helps return HTML elements
in the browser.
*/

// 1) capture elements
// 2) add eventListener
// 3) add getEventByClass

// BABY STEPS--ASSIGN SELECTED TO LIST

// document.getElementsByClassName('cbp-vm-list').className+= "cbp-vm-selected";

/*

// BASIC CODE
var list = document.getElementsByClassName("cbp-vm-list");

list.addEventListener('click', function(){
  list.className+= 'cbp-vm-selected';
});

var grid = document.getElementsByClassName("cbp-vm-grid");

grid.addEventListener('click', function(){
  grid.className+= 'cbp-vm-selected';
});

// CODE WITH FUNCTION BEFORE LISTENER
// GRID
// function addSelectorG() {
//   if (grid !== "cbp-vm-icon cbp-vm-grid cbp-vm-selected") {
//     list.className= "cbp-vm-icon cbp-vm-list ' ' ";
//     grid.className+= 'cbp-vm-grid';
//   }
// }
//
// var grid = document.getElementsByClassName("cbp-vm-icon cbp-vm-grid cbp-vm-selected");
//
// grid.addEventListener('click', addSelectorG);

// LIST
// function addSelectorL() {
//   if (list !== "cbp-vm-icon cbp-vm-list cbp-vm-selected") {
//     // grid.className= "cbp-vm-icon cbp-vm-grid ' ' ";
//     list.className+= 'cbp-vm-selected';
//   }
// }
//
// var list = document.getElementsByClassName("cbp-vm-icon cbp-vm-list");
//
// list.addEventListener('click', addSelectorL);

// CODE WITH EXTENDED CLASS NAME AND IF STATEMENTS
//
// var list = document.getElementsByClassName("cbp-vm-icon cbp-vm-list");
//
// list.addEventListener('click', function(){
//   if (list !== "cbp-vm-icon cbp-vm-list cbp-vm-selected") {
//      grid.className= "cbp-vm-icon cbp-vm-grid ' ' ";
//      list.className+= 'cbp-vm-selected';
//   }
// });
//
// var grid = document.getElementsByClassName("cbp-vm-icon cbp-vm-grid cbp-vm-selected");
//
// grid.addEventListener('click', function(){
//   grid.className+= 'cbp-vm-selected';
// });

*/

var buttons = document.querySelector("div #cbp-vm");
var list = document.querySelector("a.cbp-vm-icon.cbp-vm-list");
var grid = document.querySelector("a.cbp-vm-icon.cbp-vm-grid");

list.addEventListener('click', function(listButton){
  var listButton = listButton.currentTarget;
  buttons.className = "cbp-vm-switcher cbp-vm-view-list";
  list.className = 'cbp-vm-icon cbp-vm-list cbp-vm-selected';
  grid.className = 'cbp-vm-icon cbp-vm-grid';
});

grid.addEventListener('click', function(gridButton){
  var currentButton = gridButton.currentTarget;
  buttons.className = "cbp-vm-switcher cbp-vm-view-grid";

  grid.className = 'cbp-vm-icon cbp-vm-grid cbp-vm-selected';
  list.className = "cbp-vm-icon cbp-vm-list";
});
<commit_msg>converted to jquery<commit_after>
/*
On this page JavaScript changes the class on two HTML  (cbp-vm-grid) and (cbp-vm-list) and a

when the icon is clicked.

There are two icons that when clicked change the view of the page. They do this by having JavaScript
add "cbp-vm-selected" to the class of the icon that was clicked.

One icon is a list view and when clicked javascript appends it's class AND the class of the div
to show it is the list icon that is selected.When it does the CSS rules for the list class display.

The other icon is a grid. When it is clicked javascript appends its class to "cbp-vm-selected" and adds
"cbp-vm-view-grid" to the div which then triggers the CSS rule to apply the grid styling to the div.

Like I wrote in the Nested Accordian scripts.js, I don't really understand DOMs however I imagine that a window object would be called for in this case
because the page is open in a tab on my browser which is a window.

Also the document object would be the entry point into the web pages' content i.e. it helps return HTML elements
in the browser.
*/

// 1) capture elements
// 2) add eventListener
// 3) add getEventByClass

// BABY STEPS--ASSIGN SELECTED TO LIST

// document.getElementsByClassName('cbp-vm-list').className+= "cbp-vm-selected";

/*

// BASIC CODE
var list = document.getElementsByClassName("cbp-vm-list");

list.addEventListener('click', function(){
  list.className+= 'cbp-vm-selected';
});

var grid = document.getElementsByClassName("cbp-vm-grid");

grid.addEventListener('click', function(){
  grid.className+= 'cbp-vm-selected';
});

// CODE WITH FUNCTION BEFORE LISTENER
// GRID
// function addSelectorG() {
//   if (grid !== "cbp-vm-icon cbp-vm-grid cbp-vm-selected") {
//     list.className= "cbp-vm-icon cbp-vm-list ' ' ";
//     grid.className+= 'cbp-vm-grid';
//   }
// }
//
// var grid = document.getElementsByClassName("cbp-vm-icon cbp-vm-grid cbp-vm-selected");
//
// grid.addEventListener('click', addSelectorG);

// LIST
// function addSelectorL() {
//   if (list !== "cbp-vm-icon cbp-vm-list cbp-vm-selected") {
//     // grid.className= "cbp-vm-icon cbp-vm-grid ' ' ";
//     list.className+= 'cbp-vm-selected';
//   }
// }
//
// var list = document.getElementsByClassName("cbp-vm-icon cbp-vm-list");
//
// list.addEventListener('click', addSelectorL);

// CODE WITH EXTENDED CLASS NAME AND IF STATEMENTS
//
// var list = document.getElementsByClassName("cbp-vm-icon cbp-vm-list");
//
// list.addEventListener('click', function(){
//   if (list !== "cbp-vm-icon cbp-vm-list cbp-vm-selected") {
//      grid.className= "cbp-vm-icon cbp-vm-grid ' ' ";
//      list.className+= 'cbp-vm-selected';
//   }
// });
//
// var grid = document.getElementsByClassName("cbp-vm-icon cbp-vm-grid cbp-vm-selected");
//
// grid.addEventListener('click', function(){
//   grid.className+= 'cbp-vm-selected';
// });

*/
/*
var buttons = document.querySelector("div #cbp-vm");
var list = document.querySelector("a.cbp-vm-icon.cbp-vm-list");
var grid = document.querySelector("a.cbp-vm-icon.cbp-vm-grid");

list.addEventListener('click', function(listButton){
  var listButton = listButton.currentTarget;
  buttons.className = "cbp-vm-switcher cbp-vm-view-list";
  list.className = 'cbp-vm-icon cbp-vm-list cbp-vm-selected';
  grid.className = 'cbp-vm-icon cbp-vm-grid';
});

grid.addEventListener('click', function(gridButton){
  var currentButton = gridButton.currentTarget;
  buttons.className = "cbp-vm-switcher cbp-vm-view-grid";

  grid.className = 'cbp-vm-icon cbp-vm-grid cbp-vm-selected';
  list.className = "cbp-vm-icon cbp-vm-list";
});
*/
//jQuery Here:
/*
var buttons = $('div #cbp-vm');
var list = $('a.cbp-vm-icon.cbp-vm-list');
var grid = $('cbp-vm-icon cbp-vm-grid');
*/
//When list icon is clicked div gets "cbp-vm-switcher and cbp-vm-view-list" added;
//list gets cbp-vm-selected added;
//grid has nothing added and might? need cbp-vm-selected added
$('a.cbp-vm-icon.cbp-vm-list').on('click', function(){
  $('div #cbp-vm').addClass('cbp-vm-switcher cbp-vm-view-list');
  $('a.cbp-vm-icon.cbp-vm-list').addClass('cbp-vm-selected');

});

$('cbp-vm-icon cbp-vm-grid').on('click', function(){
  $('div #cbp-vm').addClass('cbp-vm-switcher cbp-vm-view-grid');
  $('cbp-vm-icon cbp-vm-grid').addClass('cbp-vm-selected');
})
<|endoftext|>


<commit_before>function render(template, args, msginfo, msgerror) {
    var source;
    var template;
    var path = 'js/templates/' +  template + '.html';
    $.ajax({
        url: path,
        cache: true,
        success: function (data) {
            source = data;
            template = Handlebars.compile(source);
            $('#maincontainer').html(template(args)).trigger('create');
        }
    });
};
function redirect(location){
	window.location = location;
}<commit_msg>Don't redirect but re-render page.<commit_after>function render(template, args, msginfo, msgerror) {
    var source;
    var template;
    var path = 'js/templates/' +  template + '.html';
    $.ajax({
        url: path,
        cache: true,
        success: function (data) {
            source = data;
            template = Handlebars.compile(source);
            $('#maincontainer').html(template(args)).trigger('create');
        }
    });
};
function redirect(location){
	app.route(location);
}<|endoftext|>


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

    var trailer_url;

    // Identify the active tile in the carousel and display it's movie metadata in the preview-container
    $('.carousel').carousel({
        onCycleTo: function (ele, dragged) {

            // Variables definition
            // Get movie metadata for the active tile in the carousel
            var title = $(ele).attr('data-movie-title');
            var storyline = $(ele).attr('data-storyline');
            var wallpaper_url = $(ele).attr('data-wallpaper');
            var trailer_id = $(ele).attr('data-trailer-youtube-id');
            trailer_url = 'http://www.youtube.com/embed/' + trailer_id + '?autoplay=1&html5=1&VQ=HD720&iv_load_policy=3';
            var director = $(ele).attr('data-director');
            var country = $(ele).attr('data-country');
            var rating = $(ele).attr('data-rating');

            // Generate HTML containing the movie metadata
            $('.preview-container').html(
                `<img class ="movie-wallpaper" src=` + wallpaper_url + ` alt="">

` + title + `

` + storyline + `

                                    Directed by
                                    ` + director + `

                                    Country
                                    ` + country + `

                                    IMDB Rating
                                    ` + rating + `

                                Watch Trailer

`
            );
        }
    });

    // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
    $('.modal').modal({
        dismissible: true, // Modal can be dismissed by clicking outside of the modal
        opacity: .5, // Opacity of modal background
        inDuration: 300, // Transition in duration
        outDuration: 200, // Transition out duration
        startingTop: '4%', // Starting top style attribute
        endingTop: '10%', // Ending top style attribute
        ready: function(modal, trigger) { // Callback for Modal open. Modal and trigger parameters available.
            // Start video when modal is opened
            $('.video-container').html(
                ''
            );
        },
        complete: function() {
            // Stop video when modal is closed
            $('.video-container').empty();
        }
    });

});<commit_msg>Changed youtube URL from http to https to fix mixed content error<commit_after>$(document).ready(function(){

    var trailer_url;

    // Identify the active tile in the carousel and display it's movie metadata in the preview-container
    $('.carousel').carousel({
        onCycleTo: function (ele, dragged) {

            // Variables definition
            // Get movie metadata for the active tile in the carousel
            var title = $(ele).attr('data-movie-title');
            var storyline = $(ele).attr('data-storyline');
            var wallpaper_url = $(ele).attr('data-wallpaper');
            var trailer_id = $(ele).attr('data-trailer-youtube-id');
            trailer_url = 'https://www.youtube.com/embed/' + trailer_id + '?autoplay=1&html5=1&VQ=HD720&iv_load_policy=3';
            var director = $(ele).attr('data-director');
            var country = $(ele).attr('data-country');
            var rating = $(ele).attr('data-rating');

            // Generate HTML containing the movie metadata
            $('.preview-container').html(
                `<img class ="movie-wallpaper" src=` + wallpaper_url + ` alt="">

` + title + `

` + storyline + `

                                    Directed by
                                    ` + director + `

                                    Country
                                    ` + country + `

                                    IMDB Rating
                                    ` + rating + `

                                Watch Trailer

`
            );
        }
    });

    // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
    $('.modal').modal({
        dismissible: true, // Modal can be dismissed by clicking outside of the modal
        opacity: .5, // Opacity of modal background
        inDuration: 300, // Transition in duration
        outDuration: 200, // Transition out duration
        startingTop: '4%', // Starting top style attribute
        endingTop: '10%', // Ending top style attribute
        ready: function(modal, trigger) { // Callback for Modal open. Modal and trigger parameters available.
            // Start video when modal is opened
            $('.video-container').html(
                ''
            );
        },
        complete: function() {
            // Stop video when modal is closed
            $('.video-container').empty();
        }
    });

});<|endoftext|>


<commit_before>/**
 * Created by DT314 on 2017/7/4.
 */
import React, {Component} from 'react';
import PropTypes from 'prop-types';

import ListStepItem from '../_ListStepItem';

import './ListStep.css';

export default class ListStep extends Component{

    constructor(props) {

        super(props);

        this.state = {
            activatedStep: props.activatedStep,
            finishedStep: props.finishedStep
        };

        this.tapHandle = this::this.tapHandle;

    }

    tapHandle(activatedStep) {

        const {onChange} = this.props;

        this.setState({
            activatedStep
        }, () => {
            onChange && onChange({
                activatedStep,
                finishedStep: this.state.finishedStep
            });
        });
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.activatedStep !== this.state.activatedStep
            || nextProps.finishedStep !== this.state.finishedStep) {
            this.setState({
                activatedStep: nextProps.activatedStep,
                finishedStep: nextProps.finishedStep
            });
        }
    }

    render() {

        const {className, style, steps} = this.props;
        const {activatedStep, finishedStep} = this.state;

        return (
            <div className={`list-step ${className}`}
                 style={style}>

                {
                    steps.map((item, index) => {
                        return (
                            <ListStepItem  key={index}
                                           index={index}
                                           className={item.className}
                                           style={{
                                               ...item.style,
                                               width: `${100 / steps.length}%`,
                                               zIndex: steps.length - index
                                           }}
                                           activatedStep={activatedStep}
                                           finishedStep={finishedStep}
                                           data={item}
                                           onTouchTap={this.tapHandle}/>
                        );
                    })
                }

        );

    }
}

ListStep.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The render content of step.
     */
    steps: PropTypes.arrayOf(PropTypes.shape({

        /**
         * The CSS class name of step element.
         */
        className: PropTypes.string,

        /**
         * Override the styles of the step element.
         */
        style: PropTypes.object,

        /**
         * The text value of step.
         */
        title: PropTypes.string

    })).isRequired,

    /**
     * Sets the step as active.
     */
    activatedStep: PropTypes.number,

    /**
     * The final step.
     */
    finishedStep: PropTypes.number,

    /**
     * Callback function fired when step change.
     */
    onChange: PropTypes.func

};

ListStep.defaultProps = {

    className: '',
    style: null,

    steps: [],

    activatedStep: 0,
    finishedStep: 0

};<commit_msg>optimize ListStep<commit_after>/**
 * Created by DT314 on 2017/7/4.
 */
import React, {Component} from 'react';
import PropTypes from 'prop-types';

import ListStepItem from '../_ListStepItem';

import './ListStep.css';

export default class ListStep extends Component {

    constructor(props) {

        super(props);

        this.state = {
            activatedStep: props.activatedStep,
            finishedStep: props.finishedStep
        };

        this.touchTapHandler = this::this.touchTapHandler;

    }

    touchTapHandler(activatedStep) {

        const {onChange} = this.props;

        this.setState({
            activatedStep
        }, () => {
            onChange && onChange({
                activatedStep,
                finishedStep: this.state.finishedStep
            });
        });

    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.activatedStep !== this.state.activatedStep
            || nextProps.finishedStep !== this.state.finishedStep) {
            this.setState({
                activatedStep: nextProps.activatedStep,
                finishedStep: nextProps.finishedStep
            });
        }
    }

    render() {

        const {className, style, steps} = this.props;
        const {activatedStep, finishedStep} = this.state;

        return (
            <div className={`list-step ${className}`}
                 style={style}>

                {
                    steps.map((item, index) => {
                        return (
                            <ListStepItem key={index}
                                          index={index}
                                          className={item.className}
                                          style={{
                                              ...item.style,
                                              width: `${100 / steps.length}%`,
                                              zIndex: steps.length - index
                                          }}
                                          activatedStep={activatedStep}
                                          finishedStep={finishedStep}
                                          data={item}
                                          onTouchTap={this.touchTapHandler}/>
                        );
                    })
                }

        );

    }
}

ListStep.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The render content of step.
     */
    steps: PropTypes.arrayOf(PropTypes.shape({

        /**
         * The CSS class name of step element.
         */
        className: PropTypes.string,

        /**
         * Override the styles of the step element.
         */
        style: PropTypes.object,

        /**
         * The text value of step.
         */
        title: PropTypes.string

    })).isRequired,

    /**
     * Sets the step as active.
     */
    activatedStep: PropTypes.number,

    /**
     * The final step.
     */
    finishedStep: PropTypes.number,

    /**
     * Callback function fired when step change.
     */
    onChange: PropTypes.func

};

ListStep.defaultProps = {

    className: '',
    style: null,

    steps: [],

    activatedStep: 0,
    finishedStep: 0

};<|endoftext|>


<commit_before>(function () {

  function loadModule(React, ReactDOM, hljs) {
    return React.createClass({
      propTypes: {
        lang: React.PropTypes.string.isRequired,
        value: React.PropTypes.string.isRequired
      },

      componentDidMount: function () {
        // this will only be called once after first time render
        this.updateCodeBlockDOM();
      },

      componentDidUpdate: function () {
        // whenever component is updated
        this.updateCodeBlockDOM();
      },

      render: function () {
        /*
         *

         *
         *    to_be_rendered_by_highlight.js
         *
         *

         *
         */

        var props = Object.assign({}, this.props);
        delete props.lang;
        delete props.value;

        return (
          React.createElement('pre', props,
            React.createElement('code', {
              ref: 'code',
              className: 'hljs ' + this.props.lang
            })
          )
        );
      },

      updateCodeBlockDOM: function () {
        // update real DOM element after component render
        var ele = ReactDOM.findDOMNode(this.refs.code);

        try {
          ele.innerHTML = hljs.highlight(this.props.lang, this.props.value, true).value;
        } catch (e) {
          console.warn(e);
          ele.innerHTML = this.props.value; // remove syntax highlight
        }
      }
    });
  }

  if (typeof require === 'function' &&
      typeof module  === 'object' &&
      typeof exports === 'object' &&
      module.exports === exports) {

    // Node: export as module
    module.exports = loadModule(
      require('react'),
      require('react-dom'),
      require('highlight.js')
    );
  } else {
    // Browser: export as global variable
    window.HighLight = window.HighLight || loadModule(React, ReactDOM, hljs);
  }

})();
<commit_msg>[refactor] factory design pattern<commit_after>(function (factory) {
  if (typeof require === 'function' &&
      typeof module  === 'object' &&
      typeof exports === 'object' &&
      module.exports === exports) {

    // Node: export as module
    module.exports = factory(
      require('react'),
      require('react-dom'),
      require('highlight.js')
    );
  } else {
    // Browser: export as global variable
    window.HighLight = window.HighLight || factory(React, ReactDOM, hljs);
  }

})(function (React, ReactDOM, hljs) {
  return React.createClass({
    propTypes: {
      lang: React.PropTypes.string.isRequired,
      value: React.PropTypes.string.isRequired
    },

    componentDidMount: function () {
      // this will only be called once after first time render
      this.updateCodeBlockDOM();
    },

    componentDidUpdate: function () {
      // whenever component is updated
      this.updateCodeBlockDOM();
    },

    render: function () {
      /*
       *

       *
       *    to_be_rendered_by_highlight.js
       *
       *

       *
       */

      var props = Object.assign({}, this.props);
      delete props.lang;
      delete props.value;

      return (
        React.createElement('pre', props,
          React.createElement('code', {
            ref: 'code',
            className: 'hljs ' + this.props.lang
          })
        )
      );
    },

    updateCodeBlockDOM: function () {
      // update real DOM element after component render
      var ele = ReactDOM.findDOMNode(this.refs.code);

      try {
        ele.innerHTML = hljs.highlight(this.props.lang, this.props.value, true).value;
      } catch (e) {
        console.warn(e);
        ele.innerHTML = this.props.value; // remove syntax highlight
      }
    }
  });
});
<|endoftext|>


<commit_before>/*!
 * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
    if ($(".navbar").offset().top > 50) {
        $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
});

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

//carousel stop//
$('.carousel').carousel({
    interval: false
}) <commit_msg>remove unnecessary js for carousel<commit_after>/*!
 * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
    if ($(".navbar").offset().top > 50) {
        $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
});

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

<|endoftext|>