<commit_before>/* ----------------------- LOGGING SHORTCUTS -------------------------- */

function debug(msg) {
  if (console && console.debug) {
    console.debug(msg);
  }
}

function log(msg) {
  if (console && console.log) {
    console.log(msg);
  }
}

function error(msg) {
  if (console && console.error) {
    console.error(msg);
  }
}

function warn(msg) {
  if (console && console.warn) {
    console.warn(msg);
  }
}

/* ----------------------- Testing values and types ---------------------- */

function isNumeric(obj) {
  return isFinite(String(obj));
}

function isUndefined(v) {
  return typeof v === "undefined";
}

function isUnset(v) {
  return (typeof v === "undefined") || (v === null);
}

// IE polyfill
if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

/* ----------------------- Html encode/decode ---------------------- */

function htmlEncode(txt) {
    return $('
').text(txt).html();
}
function htmlDecode(html) {
    return $('
').html(html).text();
}

/* ----------------------- Browser utilities ---------------------- */

// is current bowser safari?
function isSafari() {
  return /^((?!chrome|android|ubuntu).)*safari/i.test(navigator.userAgent);
}

// Extract URL parameters from current location
function getParameterByName(name, defaultValue) {
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
  return results === null ? (isUnset(defaultValue) ? defaultValue : "") : decodeURIComponent(results[1].replace(/\+/g, " "));
}

/* ------------------ Drop down menu utils -------------------- */

// add a drop down menu item
function addSelectOption(select, optval) {
  var opt = document.createElement("option");
  opt.innerHTML = optval;
  opt.value = optval;
  opt.setAttribute("name", optval);
  select.appendChild(opt);
}

// select a drop down menu item
function selectOption(select, optval) {
  jqselect = $(select);
  jqselect.children(":selected").prop("selected", false);
  jqselect.children("option[value='" + optval + "']").prop("selected", true);
}
// get selected drop down option
function getSelectedOption(select) {
  return $(select).children(':selected').val();
}

// get checkbox status
function isChecked(selector) {
  return $(selector).is(':checked');
}
// set checkbox status
function setChecked(selector, val) {
  $(selector).prop('checked', val);
}
/* ----------------------- Local storage -------------------------- */

var cookiesBanner;
function consentCookies() {
  $('body').prepend("\

\
    <button id='cookies-eu-accept'>Got it!</button>\

This website uses cookies and browser's local storage to restore your status and settings on your next visits. \
    Read more
\

");

  cookiesBanner = new CookiesEuBanner(function () {}, true);
}

function canValBeSaved() {
  // (cookiesBanner && cookiesBanner.hasConsent())?
  return (window.location.toString().indexOf("file:") === 0);
}

function storeVal(name, val) {
  //log("store " + name + "=" + val);
  if (canValBeSaved()) {
    var store = window.localStorage;
    if (store) {
      if (isUnset(val)) {
        store.removeItem(name);
      } else {
        try {
          store.setItem(name, val);
        } catch (err) {
          var kbsz = val.length ? Math.round(val.length/1024) : 0;
          error("Cannot store value " + name + ": " + kbsz + "KB");
          ga('send', 'event', 'error', 'storeVal failed', name, kbsz);
        }
      }
    }
  }
}

function storeJsonVal(name, val) {
  if (JSON && JSON.stringify) {
    v = JSON.stringify(val);
    storeVal(name, v);
  }
}

function getVal(name, defval) {
  var v = window.localStorage ? window.localStorage.getItem(name) : undefined;
  return isUnset(v) ? defval : v;
}

function getNumVal(name, defval) {
  var v = getVal(name, defval);
  return v && parseFloat(v);
}

function getBoolVal(name, defval) {
  var v = getVal(name, defval);
  return v && v == "true";
}

function getJsonVal(name, defval) {
  var v = getVal(name);
  var val;
  try {
    val = v && JSON && JSON.parse ? JSON.parse(v) : undefined;
  } catch (ex) {
    error("Invalid json preference for " + name);
    v = undefined;
  }
  return isUnset(v) ? defval : val;
}

/* ---------------------- GOOGLE ANALYTICS ------------------------- */

function initGoogleAnalytics(trackingid) {
  var gaScriptUrl = 'https://www.google-analytics.com/analytics.js';
  var gadbg = getVal("wt.ga.dbg", "0");
  if (gadbg != '0') {
    gaScriptUrl = 'https://www.google-analytics.com/analytics_debug.js';
  }
  /**/
  (function(i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function() {
      (i[r].q = i[r].q || []).push(arguments);
    }, i[r].l = 1 * new Date();
    a = s.createElement(o),
      m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    a.onerror = function(err) {
      error("Google Analytics blocked. Ad blocker?");
    };
    try {
      m.parentNode.insertBefore(a, m);
    } catch (err) {
      error("Google Analytics blocked. Ad blocker?");
    }
  })(window, document, 'script', gaScriptUrl, 'ga');
  if (gadbg === "2") {
    window.ga_debug = {trace: true};
  }
  ga('create', trackingid, 'auto');
  if (getBoolVal("wt.ga.off", false)) {
    log('Turning off GA reporting');
    ga('set', 'sendHitTask', null);
  }
  ga('send', 'pageview');
}

/* ---------------------- EMAIL ------------------------- */
/*
 * Open a new mail in default mail client with recipent and subject.
 * It protects the email address from spam robots by splitting the address in several parts,
 * and only assemblying them when needed for the duration of a click.
 *
 * parameters:
 * - selector: the css selector of the link or button which should open the email
 * - name: the name part of the recepient email address
 * - domain: the domain part of the recepient email address
 * - subject: the subject string of the newly created email
 *
 * Attachs a click handler to the html element designated by <selector>
 * that opens the following URL:
 * "mailto:<name>@<domain>?subject=<subject>
 */
function setEmailListener(selector, name, domain, subject) {
  $(selector).click(function() {
    function doEmail(d, i, tail) {
      location.href = "mailto:" + i + "@" + d + tail;
    }
    doEmail(domain, name, "?subject=" + subject);
    return false;
  });
}
if (config.email && config.email.selector) {
  setEmailListener(config.email.selector, config.email.name,
    config.email.domain, config.email.subject);
}

/* ------------------------------ CORS URL  ---------------------------------*/
function corsUrl(url) {
    return "https://cors-anywhere.herokuapp.com/" + url;
    //return config.corsproxy.url() + config.corsproxy.query + encodeURIComponent(url);
}

/* ------------------------------ Encoding ---------------------------------*/
function n10dLocation() {
  var res = window.location.toString();
  res = res.replace(/\?.*$/, "").replace(/\#.*$/, "");
  res = res.replace(/^.*:\/\//, "//");
  res = res.replace(/index.html$/, "");
  res = res.replace(/\/*$/, "/");
  return res;
}

function getLocalCode() {
  var res = getVal("wtracks.code");
  return res;
}

function strxor(s, k) {
  var enc = "";
  // make sure that input is string
  s = s.toString();
  for (var i = 0; i < s.length; i++) {
    // create block
    var a = s.charCodeAt(i);
    // bitwise XOR
    var b = a ^ k.charCodeAt(i % k.length);
    enc = enc + String.fromCharCode(b);
  }
  return enc;
}

function getEncodeParams(s1, s2) {
  var islocal = (window.location.toString().indexOf("file:") === 0) ||
    (window.location.toString().indexOf(".dev.local:") > 0);
  var res = {
    k: islocal ? getLocalCode() : n10dLocation()
  };
  if (s1 || s2) {
    res.s = islocal ? s2 : s1;
  }
  return res;
}

function strencode(s) {
  var param = getEncodeParams();
  return encodeURIComponent(strxor(s, param.k));
}

function strdecode(s1, s2) {
  var param = getEncodeParams(s1, s2);
  return param.s ? strxor(decodeURIComponent(param.s), param.k ? param.k : "") : param.s;
}

// Base 64 encoding / decoding

function supportsBase64() {
  return btoa && atob ? true : false;
}

function b64EncodeUnicode(str) {
  return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
    return String.fromCharCode('0x' + p1);
  }));
}

function b64DecodeUnicode(str) {
  return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));
}

function copyToClipboard(msg, text) {
  window.prompt(msg + "\nCopy to clipboard: Ctrl+C, Enter", text);
}

function arrayMove(arr, old_index, new_index) {
    if (new_index >= arr.length) {
        var k = new_index - arr.length + 1;
        while (k--) {
            arr.push(undefined);
        }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
    return arr;
}

function objectForEach(object, func) {
  if (object) {
    for (var o in object) {
      if (hasOwnProperty.call(object, o)) {
        if (func(o, object[o])) break;
      }
    }
  }
}
function arrayForEach(array, func) {
  if (array) {
    var i = 0;
    var len = array.length;
    while (i < len) {
      if (func(i, array[i])) break;
      if (len > array.length) {
        len = array.length;
      } else {
        i++;
      }
    }
  }
}

/* ---------------------- Start service worker ------------------------*/

if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('./service-worker.js');
  });
}

/* ---------------------- track errors ------------------------*/

window.onerror = function(messageOrEvent, source, line, row, err) {
  error(messageOrEvent.toString() + " [" + source + ": " + line + ", " + row);
  if (ga) {
    ga('send', 'event', 'error', messageOrEvent.toString() +" ["+source+":"+line+","+row, navigator.userAgent);
  }
}
<commit_msg>add page name to error<commit_after>/* ----------------------- LOGGING SHORTCUTS -------------------------- */

function debug(msg) {
  if (console && console.debug) {
    console.debug(msg);
  }
}

function log(msg) {
  if (console && console.log) {
    console.log(msg);
  }
}

function error(msg) {
  if (console && console.error) {
    console.error(msg);
  }
}

function warn(msg) {
  if (console && console.warn) {
    console.warn(msg);
  }
}

/* ----------------------- Testing values and types ---------------------- */

function isNumeric(obj) {
  return isFinite(String(obj));
}

function isUndefined(v) {
  return typeof v === "undefined";
}

function isUnset(v) {
  return (typeof v === "undefined") || (v === null);
}

// IE polyfill
if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

/* ----------------------- Html encode/decode ---------------------- */

function htmlEncode(txt) {
    return $('
').text(txt).html();
}
function htmlDecode(html) {
    return $('
').html(html).text();
}

/* ----------------------- Browser utilities ---------------------- */

// is current bowser safari?
function isSafari() {
  return /^((?!chrome|android|ubuntu).)*safari/i.test(navigator.userAgent);
}

// Extract URL parameters from current location
function getParameterByName(name, defaultValue) {
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
  return results === null ? (isUnset(defaultValue) ? defaultValue : "") : decodeURIComponent(results[1].replace(/\+/g, " "));
}

/* ------------------ Drop down menu utils -------------------- */

// add a drop down menu item
function addSelectOption(select, optval) {
  var opt = document.createElement("option");
  opt.innerHTML = optval;
  opt.value = optval;
  opt.setAttribute("name", optval);
  select.appendChild(opt);
}

// select a drop down menu item
function selectOption(select, optval) {
  jqselect = $(select);
  jqselect.children(":selected").prop("selected", false);
  jqselect.children("option[value='" + optval + "']").prop("selected", true);
}
// get selected drop down option
function getSelectedOption(select) {
  return $(select).children(':selected').val();
}

// get checkbox status
function isChecked(selector) {
  return $(selector).is(':checked');
}
// set checkbox status
function setChecked(selector, val) {
  $(selector).prop('checked', val);
}
/* ----------------------- Local storage -------------------------- */

var cookiesBanner;
function consentCookies() {
  $('body').prepend("\

\
    <button id='cookies-eu-accept'>Got it!</button>\

This website uses cookies and browser's local storage to restore your status and settings on your next visits. \
    Read more
\

");

  cookiesBanner = new CookiesEuBanner(function () {}, true);
}

function canValBeSaved() {
  // (cookiesBanner && cookiesBanner.hasConsent())?
  return (window.location.toString().indexOf("file:") === 0);
}

function storeVal(name, val) {
  //log("store " + name + "=" + val);
  if (canValBeSaved()) {
    var store = window.localStorage;
    if (store) {
      if (isUnset(val)) {
        store.removeItem(name);
      } else {
        try {
          store.setItem(name, val);
        } catch (err) {
          var kbsz = val.length ? Math.round(val.length/1024) : 0;
          error("Cannot store value " + name + ": " + kbsz + "KB");
          ga('send', 'event', 'error', 'storeVal failed', name, kbsz);
        }
      }
    }
  }
}

function storeJsonVal(name, val) {
  if (JSON && JSON.stringify) {
    v = JSON.stringify(val);
    storeVal(name, v);
  }
}

function getVal(name, defval) {
  var v = window.localStorage ? window.localStorage.getItem(name) : undefined;
  return isUnset(v) ? defval : v;
}

function getNumVal(name, defval) {
  var v = getVal(name, defval);
  return v && parseFloat(v);
}

function getBoolVal(name, defval) {
  var v = getVal(name, defval);
  return v && v == "true";
}

function getJsonVal(name, defval) {
  var v = getVal(name);
  var val;
  try {
    val = v && JSON && JSON.parse ? JSON.parse(v) : undefined;
  } catch (ex) {
    error("Invalid json preference for " + name);
    v = undefined;
  }
  return isUnset(v) ? defval : val;
}

/* ---------------------- GOOGLE ANALYTICS ------------------------- */

function initGoogleAnalytics(trackingid) {
  var gaScriptUrl = 'https://www.google-analytics.com/analytics.js';
  var gadbg = getVal("wt.ga.dbg", "0");
  if (gadbg != '0') {
    gaScriptUrl = 'https://www.google-analytics.com/analytics_debug.js';
  }
  /**/
  (function(i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function() {
      (i[r].q = i[r].q || []).push(arguments);
    }, i[r].l = 1 * new Date();
    a = s.createElement(o),
      m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    a.onerror = function(err) {
      error("Google Analytics blocked. Ad blocker?");
    };
    try {
      m.parentNode.insertBefore(a, m);
    } catch (err) {
      error("Google Analytics blocked. Ad blocker?");
    }
  })(window, document, 'script', gaScriptUrl, 'ga');
  if (gadbg === "2") {
    window.ga_debug = {trace: true};
  }
  ga('create', trackingid, 'auto');
  if (getBoolVal("wt.ga.off", false)) {
    log('Turning off GA reporting');
    ga('set', 'sendHitTask', null);
  }
  ga('send', 'pageview');
}

/* ---------------------- EMAIL ------------------------- */
/*
 * Open a new mail in default mail client with recipent and subject.
 * It protects the email address from spam robots by splitting the address in several parts,
 * and only assemblying them when needed for the duration of a click.
 *
 * parameters:
 * - selector: the css selector of the link or button which should open the email
 * - name: the name part of the recepient email address
 * - domain: the domain part of the recepient email address
 * - subject: the subject string of the newly created email
 *
 * Attachs a click handler to the html element designated by <selector>
 * that opens the following URL:
 * "mailto:<name>@<domain>?subject=<subject>
 */
function setEmailListener(selector, name, domain, subject) {
  $(selector).click(function() {
    function doEmail(d, i, tail) {
      location.href = "mailto:" + i + "@" + d + tail;
    }
    doEmail(domain, name, "?subject=" + subject);
    return false;
  });
}
if (config.email && config.email.selector) {
  setEmailListener(config.email.selector, config.email.name,
    config.email.domain, config.email.subject);
}

/* ------------------------------ CORS URL  ---------------------------------*/
function corsUrl(url) {
    return "https://cors-anywhere.herokuapp.com/" + url;
    //return config.corsproxy.url() + config.corsproxy.query + encodeURIComponent(url);
}

/* ------------------------------ Encoding ---------------------------------*/
function n10dLocation() {
  var res = window.location.toString();
  res = res.replace(/\?.*$/, "").replace(/\#.*$/, "");
  res = res.replace(/^.*:\/\//, "//");
  res = res.replace(/index.html$/, "");
  res = res.replace(/\/*$/, "/");
  return res;
}

function getLocalCode() {
  var res = getVal("wtracks.code");
  return res;
}

function strxor(s, k) {
  var enc = "";
  // make sure that input is string
  s = s.toString();
  for (var i = 0; i < s.length; i++) {
    // create block
    var a = s.charCodeAt(i);
    // bitwise XOR
    var b = a ^ k.charCodeAt(i % k.length);
    enc = enc + String.fromCharCode(b);
  }
  return enc;
}

function getEncodeParams(s1, s2) {
  var islocal = (window.location.toString().indexOf("file:") === 0) ||
    (window.location.toString().indexOf(".dev.local:") > 0);
  var res = {
    k: islocal ? getLocalCode() : n10dLocation()
  };
  if (s1 || s2) {
    res.s = islocal ? s2 : s1;
  }
  return res;
}

function strencode(s) {
  var param = getEncodeParams();
  return encodeURIComponent(strxor(s, param.k));
}

function strdecode(s1, s2) {
  var param = getEncodeParams(s1, s2);
  return param.s ? strxor(decodeURIComponent(param.s), param.k ? param.k : "") : param.s;
}

// Base 64 encoding / decoding

function supportsBase64() {
  return btoa && atob ? true : false;
}

function b64EncodeUnicode(str) {
  return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
    return String.fromCharCode('0x' + p1);
  }));
}

function b64DecodeUnicode(str) {
  return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));
}

function copyToClipboard(msg, text) {
  window.prompt(msg + "\nCopy to clipboard: Ctrl+C, Enter", text);
}

function arrayMove(arr, old_index, new_index) {
    if (new_index >= arr.length) {
        var k = new_index - arr.length + 1;
        while (k--) {
            arr.push(undefined);
        }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
    return arr;
}

function objectForEach(object, func) {
  if (object) {
    for (var o in object) {
      if (hasOwnProperty.call(object, o)) {
        if (func(o, object[o])) break;
      }
    }
  }
}
function arrayForEach(array, func) {
  if (array) {
    var i = 0;
    var len = array.length;
    while (i < len) {
      if (func(i, array[i])) break;
      if (len > array.length) {
        len = array.length;
      } else {
        i++;
      }
    }
  }
}

/* ---------------------- Start service worker ------------------------*/

if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('./service-worker.js');
  });
}

/* ---------------------- track errors ------------------------*/

window.onerror = function(messageOrEvent, source, line, row, err) {
  error(messageOrEvent.toString() + " [" + source + ": " + line + ", " + row);
  if (ga) {
    ga('send', 'event', 'error', messageOrEvent.toString() +" ["+source+":"+line+","+row + "]",
   "[" + window.location.pathname + "] " + navigator.userAgent);
  }
}
<|endoftext|>


<commit_before>const Dropdown              = require('@binary-com/binary-style').selectDropdown;
const addComma              = require('./currency').addComma;
const getDecimalPlaces      = require('./currency').getDecimalPlaces;
const Client                = require('../base/client');
const Password              = require('../../_common/check_password');
const localize              = require('../../_common/localize').localize;
const compareBigUnsignedInt = require('../../_common/string_util').compareBigUnsignedInt;
const getHashValue          = require('../../_common/url').getHashValue;
const cloneObject           = require('../../_common/utility').cloneObject;
const isEmptyObject         = require('../../_common/utility').isEmptyObject;

const Validation = (() => {
    const forms        = {};
    const error_class  = 'error-msg';
    const hidden_class = 'invisible';

    const events_map = {
        input   : 'input.validation change.validation',
        select  : 'change.validation',
        checkbox: 'change.validation',
    };

    const getFieldType = ($field) => {
        let type = null;
        if ($field.length) {
            type = $field.attr('type') === 'checkbox' ? 'checkbox' : $field.get(0).localName;
        }
        return type;
    };

    const isChecked = field => field.$.is(':checked') ? '1' : '';

    const getFieldValue = (field, options) => {
        let value;
        if (typeof options.value === 'function') {
            value = options.value();
        } else {
            value = field.type === 'checkbox' ? isChecked(field) : field.$.val();
        }
        return value || '';
    };

    const initForm = (form_selector, fields, needs_token) => {
        const $form = $(`${form_selector}:visible`);

        if (needs_token) {
            const token = getHashValue('token');
            if (!validEmailToken(token)) {
                $form.replaceWith($('<div/>', { class: error_class, text: localize('Verification code is wrong. Please use the link sent to your email.') }));
                return;
            }
        }

        if ($form.length) {
            forms[form_selector] = { $form };
            if (Array.isArray(fields) && fields.length) {
                forms[form_selector].fields = fields;
                fields.forEach((field) => {
                    field.$ = $form.find(field.selector);
                    if (!field.$.length || !field.validations) return;

                    field.type = getFieldType($(field.$[0])); // also handles multiple results
                    field.form = form_selector;
                    if (field.msg_element) {
                        field.$error = $form.find(field.msg_element);
                    } else {
                        const $parent = field.$.parent();
                        // Add indicator to required fields
                        if (field.validations.find(v => /^req$/.test(v) && (isEmptyObject(v[1]) || !v[1].hide_asterisk))) {
                            let $label = $parent.parent().find('label');
                            if (!$label.length) $label = $parent.find('label');
                            if ($label.length && $label.find('span.required_field_asterisk').length === 0) {
                                $($label[0]).append($('<span/>', { class: 'required_field_asterisk', text: '*' }));
                            }
                        }
                        if ($parent.find(`p.${error_class}`).length === 0) {
                            $parent.append($('<p/>', { class: `${error_class} ${hidden_class} no-margin` }));
                        }
                        field.$error = $parent.find(`.${error_class}`);
                    }
                    field.$submit_btn_error = $form.find('#msg_form');

                    const event = events_map[field.type];

                    if (event) {
                        field.$.unbind(event).on(event, () => {
                            checkField(field);
                            if (field.re_check_field) {
                                checkField(forms[form_selector].fields.find(fld => (
                                    fld.selector === field.re_check_field
                                )));
                            }
                        });
                    }
                });
            }
        }

        // need to init Dropdown after we have responses from ws
        const el_all_select = document.querySelectorAll('select:not([multiple]):not([single])');
        el_all_select.forEach((el) => {
            if (el.id) {
                Dropdown(`#${el.id}`);
            }
        });
    };

    // ------------------------------
    // ----- Validation Methods -----
    // ------------------------------
    const validRequired     = (value, options, field) => {
        if (value.length) return true;
        // else
        validators_map.req.message = field.type === 'checkbox' ? 'Please select the checkbox.' : 'This field is required.';
        return false;
    };
    const validEmail        = value => /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/.test(value);
    const validPassword     = (value, options, field) => {
        if (/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]+/.test(value)) {
            Password.checkPassword(field.selector);
            return true;
        }
        // else
        return false;
    };
    const validLetterSymbol = value => !/[`~!@#$%^&*)(_=+[}{\]\\/";:?><,|\d]+/.test(value);
    const validGeneral      = value => !/[`~!@#$%^&*)(_=+[}{\]\\/";:?><|]+/.test(value);
    const validAddress      = value => !/[`~!$%^&*_=+[}{\]\\"?><|]+/.test(value);
    const validPostCode     = value => /^[a-zA-Z\d-\s]*$/.test(value);
    const validPhone        = value => /^\+?[0-9\s]*$/.test(value);
    const validRegular      = (value, options) => options.regex.test(value);
    const validEmailToken   = value => value.trim().length === 8;
    const validTaxID        = value => /^[a-zA-Z0-9]*[\w-]*$/.test(value);

    const validCompare  = (value, options) => value === $(options.to).val();
    const validNotEqual = (value, options) => value !== $(options.to).val();
    const validMin      = (value, options) => (options.min ? value.length >= options.min : true);
    const validLength   = (value, options) => (
        (options.min ? value.length >= options.min : true) &&
        (options.max ? value.length <= options.max : true)
    );

    const validNumber = (value, opts) => {
        const options = cloneObject(opts);
        if (options.allow_empty && value.length === 0) {
            return true;
        }

        let is_ok   = true;
        let message = '';

        if ('min' in options && typeof options.min === 'function') {
            options.min = options.min();
        }
        if ('max' in options && typeof options.max === 'function') {
            options.max = options.max();
        }

        if (!(options.type === 'float' ? /^\d+(\.\d+)?$/ : /^\d+$/).test(value) || !$.isNumeric(value)) {
            is_ok   = false;
            message = localize('Should be a valid number.');
        } else if (options.type === 'float' && options.decimals &&
            !(new RegExp(`^\\d+(\\.\\d{0,${options.decimals}})?$`).test(value))) {
            is_ok   = false;
            message = localize('Up to [_1] decimal places are allowed.', [options.decimals]);
        } else if ('min' in options && 'max' in options && +options.min === +options.max && +value !== +options.min) {
            is_ok   = false;
            message = localize('Should be [_1]', [addComma(options.min, options.format_money ? getDecimalPlaces(Client.get('currency')) : undefined )]);
        } else if ('min' in options && 'max' in options && (+value < +options.min || isMoreThanMax(value, options))) {
            is_ok   = false;
            message = localize('Should be between [_1] and [_2]', [addComma(options.min, options.format_money ? getDecimalPlaces(Client.get('currency')) : undefined ), addComma(options.max, options.format_money ? getDecimalPlaces(Client.get('currency')) : undefined )]);
        } else if ('min' in options && +value < +options.min) {
            is_ok   = false;
            message = localize('Should be more than [_1]', [addComma(options.min, options.format_money ? getDecimalPlaces(Client.get('currency')) : undefined )]);
        } else if ('max' in options && isMoreThanMax(value, options)) {
            is_ok   = false;
            message = localize('Should be less than [_1]', [addComma(options.max, options.format_money ? getDecimalPlaces(Client.get('currency')) : undefined)]);
        }

        validators_map.number.message = message;
        return is_ok;
    };

    const isMoreThanMax = (value, options) =>
        (options.type === 'float' ? +value > +options.max : compareBigUnsignedInt(value, options.max) === 1);

    const validators_map = {
        req          : { func: validRequired,     message: '' },
        email        : { func: validEmail,        message: 'Invalid email address.' },
        password     : { func: validPassword,     message: 'Password should have lower and uppercase letters with numbers.' },
        general      : { func: validGeneral,      message: 'Only letters, numbers, space, hyphen, period, and apostrophe are allowed.' },
        address      : { func: validAddress,      message: 'Only letters, numbers, space, and these special characters are allowed: - . \' # ; : ( ) , @ /' },
        letter_symbol: { func: validLetterSymbol, message: 'Only letters, space, hyphen, period, and apostrophe are allowed.' },
        postcode     : { func: validPostCode,     message: 'Only letters, numbers, space, and hyphen are allowed.' },
        phone        : { func: validPhone,        message: 'Only numbers and spaces are allowed.' },
        compare      : { func: validCompare,      message: 'The two passwords that you entered do not match.' },
        not_equal    : { func: validNotEqual,     message: '[_1] and [_2] cannot be the same.' },
        min          : { func: validMin,          message: 'Minimum of [_1] characters required.' },
        length       : { func: validLength,       message: 'You should enter [_1] characters.' },
        number       : { func: validNumber,       message: '' },
        regular      : { func: validRegular,      message: '' },
        tax_id       : { func: validTaxID,        message: 'Should start with letter or number, and may contain hyphen and underscore.' },
    };

    const pass_length = type => ({ min: (/^mt$/.test(type) ? 8 : 6), max: 25 });

    // --------------------
    // ----- Validate -----
    // --------------------
    const checkField = (field) => {
        if (!field.$.is(':visible') || !field.validations) return true;
        if (field.clear_form_error_on_input) {
            $(`${field.form}_error`).text('');
        }

        let all_is_ok = true;
        let message   = '';
        const field_type = field.$.attr('type');

        field.validations.some((valid) => {
            if (!valid) return false; // check next validation
            let type;
            let options = {};

            if (typeof valid === 'string') {
                type = valid;
            } else {
                type    = valid[0];
                options = valid[1];
            }

            if (type === 'password' && !validLength(getFieldValue(field, options), pass_length(options))) {
                field.is_ok = false;
                type        = 'length';
                options     = pass_length(options);
            } else {
                const validator = (type === 'custom' ? options.func : validators_map[type].func);

                let value = getFieldValue(field, options);
                if (field_type !== 'password' && typeof value === 'string') {
                    value = value.trim();
                }

                field.is_ok = validator(value, options, field);
            }

            if (!field.is_ok) {
                message = options.message || validators_map[type].message;
                if (type === 'length') {
                    message = localize(message, [options.min === options.max ? options.min : `${options.min}-${options.max}`]);
                } else if (type === 'min') {
                    message = localize(message, [options.min]);
                } else if (type === 'not_equal') {
                    message = localize(message, [localize(options.name1), localize(options.name2)]);
                }
                all_is_ok = false;
                return true; // break on the first error found
            }
            return false; // check next validation
        });

        if (!all_is_ok) {
            showError(field, message);
        } else {
            clearError(field);
        }

        return all_is_ok;
    };

    const clearError = (field) => {
        if (field.$error && field.$error.length) {
            field.$error.setVisibility(0);
            if (field.$submit_btn_error && field.$submit_btn_error.length) {
                field.$submit_btn_error.setVisibility(0);
            }
        }
    };

    const showError = (field, message) => {
        clearError(field);
        Password.removeCheck(field.selector);
        field.$error.html(localize(message)).setVisibility(1);
    };

    const validate = (form_selector) => {
        const form = forms[form_selector];
        if (!form.fields) return true;
        form.is_ok = true;
        form.fields.forEach((field) => {
            if (!checkField(field)) {
                if (form.is_ok && !field.no_scroll) { // first error
                    $.scrollTo(field.$, 500, { offset: -10 });
                }
                form.is_ok = false;
            }
        });
        return form.is_ok;
    };

    return {
        validate,
        validEmailToken,

        init: initForm,
    };
})();

module.exports = Validation;
<commit_msg>don't initialize dropdown if empty<commit_after>const Dropdown              = require('@binary-com/binary-style').selectDropdown;
const addComma              = require('./currency').addComma;
const getDecimalPlaces      = require('./currency').getDecimalPlaces;
const Client                = require('../base/client');
const Password              = require('../../_common/check_password');
const localize              = require('../../_common/localize').localize;
const compareBigUnsignedInt = require('../../_common/string_util').compareBigUnsignedInt;
const getHashValue          = require('../../_common/url').getHashValue;
const cloneObject           = require('../../_common/utility').cloneObject;
const isEmptyObject         = require('../../_common/utility').isEmptyObject;

const Validation = (() => {
    const forms        = {};
    const error_class  = 'error-msg';
    const hidden_class = 'invisible';

    const events_map = {
        input   : 'input.validation change.validation',
        select  : 'change.validation',
        checkbox: 'change.validation',
    };

    const getFieldType = ($field) => {
        let type = null;
        if ($field.length) {
            type = $field.attr('type') === 'checkbox' ? 'checkbox' : $field.get(0).localName;
        }
        return type;
    };

    const isChecked = field => field.$.is(':checked') ? '1' : '';

    const getFieldValue = (field, options) => {
        let value;
        if (typeof options.value === 'function') {
            value = options.value();
        } else {
            value = field.type === 'checkbox' ? isChecked(field) : field.$.val();
        }
        return value || '';
    };

    const initForm = (form_selector, fields, needs_token) => {
        const $form = $(`${form_selector}:visible`);

        if (needs_token) {
            const token = getHashValue('token');
            if (!validEmailToken(token)) {
                $form.replaceWith($('<div/>', { class: error_class, text: localize('Verification code is wrong. Please use the link sent to your email.') }));
                return;
            }
        }

        if ($form.length) {
            forms[form_selector] = { $form };
            if (Array.isArray(fields) && fields.length) {
                forms[form_selector].fields = fields;
                fields.forEach((field) => {
                    field.$ = $form.find(field.selector);
                    if (!field.$.length || !field.validations) return;

                    field.type = getFieldType($(field.$[0])); // also handles multiple results
                    field.form = form_selector;
                    if (field.msg_element) {
                        field.$error = $form.find(field.msg_element);
                    } else {
                        const $parent = field.$.parent();
                        // Add indicator to required fields
                        if (field.validations.find(v => /^req$/.test(v) && (isEmptyObject(v[1]) || !v[1].hide_asterisk))) {
                            let $label = $parent.parent().find('label');
                            if (!$label.length) $label = $parent.find('label');
                            if ($label.length && $label.find('span.required_field_asterisk').length === 0) {
                                $($label[0]).append($('<span/>', { class: 'required_field_asterisk', text: '*' }));
                            }
                        }
                        if ($parent.find(`p.${error_class}`).length === 0) {
                            $parent.append($('<p/>', { class: `${error_class} ${hidden_class} no-margin` }));
                        }
                        field.$error = $parent.find(`.${error_class}`);
                    }
                    field.$submit_btn_error = $form.find('#msg_form');

                    const event = events_map[field.type];

                    if (event) {
                        field.$.unbind(event).on(event, () => {
                            checkField(field);
                            if (field.re_check_field) {
                                checkField(forms[form_selector].fields.find(fld => (
                                    fld.selector === field.re_check_field
                                )));
                            }
                        });
                    }
                });
            }
        }

        // need to init Dropdown after we have responses from ws
        const el_all_select = document.querySelectorAll('select:not([multiple]):not([single])');
        el_all_select.forEach((el) => {
            if (el.id && el.length) {
                Dropdown(`#${el.id}`);
            }
        });
    };

    // ------------------------------
    // ----- Validation Methods -----
    // ------------------------------
    const validRequired     = (value, options, field) => {
        if (value.length) return true;
        // else
        validators_map.req.message = field.type === 'checkbox' ? 'Please select the checkbox.' : 'This field is required.';
        return false;
    };
    const validEmail        = value => /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/.test(value);
    const validPassword     = (value, options, field) => {
        if (/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]+/.test(value)) {
            Password.checkPassword(field.selector);
            return true;
        }
        // else
        return false;
    };
    const validLetterSymbol = value => !/[`~!@#$%^&*)(_=+[}{\]\\/";:?><,|\d]+/.test(value);
    const validGeneral      = value => !/[`~!@#$%^&*)(_=+[}{\]\\/";:?><|]+/.test(value);
    const validAddress      = value => !/[`~!$%^&*_=+[}{\]\\"?><|]+/.test(value);
    const validPostCode     = value => /^[a-zA-Z\d-\s]*$/.test(value);
    const validPhone        = value => /^\+?[0-9\s]*$/.test(value);
    const validRegular      = (value, options) => options.regex.test(value);
    const validEmailToken   = value => value.trim().length === 8;
    const validTaxID        = value => /^[a-zA-Z0-9]*[\w-]*$/.test(value);

    const validCompare  = (value, options) => value === $(options.to).val();
    const validNotEqual = (value, options) => value !== $(options.to).val();
    const validMin      = (value, options) => (options.min ? value.length >= options.min : true);
    const validLength   = (value, options) => (
        (options.min ? value.length >= options.min : true) &&
        (options.max ? value.length <= options.max : true)
    );

    const validNumber = (value, opts) => {
        const options = cloneObject(opts);
        if (options.allow_empty && value.length === 0) {
            return true;
        }

        let is_ok   = true;
        let message = '';

        if ('min' in options && typeof options.min === 'function') {
            options.min = options.min();
        }
        if ('max' in options && typeof options.max === 'function') {
            options.max = options.max();
        }

        if (!(options.type === 'float' ? /^\d+(\.\d+)?$/ : /^\d+$/).test(value) || !$.isNumeric(value)) {
            is_ok   = false;
            message = localize('Should be a valid number.');
        } else if (options.type === 'float' && options.decimals &&
            !(new RegExp(`^\\d+(\\.\\d{0,${options.decimals}})?$`).test(value))) {
            is_ok   = false;
            message = localize('Up to [_1] decimal places are allowed.', [options.decimals]);
        } else if ('min' in options && 'max' in options && +options.min === +options.max && +value !== +options.min) {
            is_ok   = false;
            message = localize('Should be [_1]', [addComma(options.min, options.format_money ? getDecimalPlaces(Client.get('currency')) : undefined )]);
        } else if ('min' in options && 'max' in options && (+value < +options.min || isMoreThanMax(value, options))) {
            is_ok   = false;
            message = localize('Should be between [_1] and [_2]', [addComma(options.min, options.format_money ? getDecimalPlaces(Client.get('currency')) : undefined ), addComma(options.max, options.format_money ? getDecimalPlaces(Client.get('currency')) : undefined )]);
        } else if ('min' in options && +value < +options.min) {
            is_ok   = false;
            message = localize('Should be more than [_1]', [addComma(options.min, options.format_money ? getDecimalPlaces(Client.get('currency')) : undefined )]);
        } else if ('max' in options && isMoreThanMax(value, options)) {
            is_ok   = false;
            message = localize('Should be less than [_1]', [addComma(options.max, options.format_money ? getDecimalPlaces(Client.get('currency')) : undefined)]);
        }

        validators_map.number.message = message;
        return is_ok;
    };

    const isMoreThanMax = (value, options) =>
        (options.type === 'float' ? +value > +options.max : compareBigUnsignedInt(value, options.max) === 1);

    const validators_map = {
        req          : { func: validRequired,     message: '' },
        email        : { func: validEmail,        message: 'Invalid email address.' },
        password     : { func: validPassword,     message: 'Password should have lower and uppercase letters with numbers.' },
        general      : { func: validGeneral,      message: 'Only letters, numbers, space, hyphen, period, and apostrophe are allowed.' },
        address      : { func: validAddress,      message: 'Only letters, numbers, space, and these special characters are allowed: - . \' # ; : ( ) , @ /' },
        letter_symbol: { func: validLetterSymbol, message: 'Only letters, space, hyphen, period, and apostrophe are allowed.' },
        postcode     : { func: validPostCode,     message: 'Only letters, numbers, space, and hyphen are allowed.' },
        phone        : { func: validPhone,        message: 'Only numbers and spaces are allowed.' },
        compare      : { func: validCompare,      message: 'The two passwords that you entered do not match.' },
        not_equal    : { func: validNotEqual,     message: '[_1] and [_2] cannot be the same.' },
        min          : { func: validMin,          message: 'Minimum of [_1] characters required.' },
        length       : { func: validLength,       message: 'You should enter [_1] characters.' },
        number       : { func: validNumber,       message: '' },
        regular      : { func: validRegular,      message: '' },
        tax_id       : { func: validTaxID,        message: 'Should start with letter or number, and may contain hyphen and underscore.' },
    };

    const pass_length = type => ({ min: (/^mt$/.test(type) ? 8 : 6), max: 25 });

    // --------------------
    // ----- Validate -----
    // --------------------
    const checkField = (field) => {
        if (!field.$.is(':visible') || !field.validations) return true;
        if (field.clear_form_error_on_input) {
            $(`${field.form}_error`).text('');
        }

        let all_is_ok = true;
        let message   = '';
        const field_type = field.$.attr('type');

        field.validations.some((valid) => {
            if (!valid) return false; // check next validation
            let type;
            let options = {};

            if (typeof valid === 'string') {
                type = valid;
            } else {
                type    = valid[0];
                options = valid[1];
            }

            if (type === 'password' && !validLength(getFieldValue(field, options), pass_length(options))) {
                field.is_ok = false;
                type        = 'length';
                options     = pass_length(options);
            } else {
                const validator = (type === 'custom' ? options.func : validators_map[type].func);

                let value = getFieldValue(field, options);
                if (field_type !== 'password' && typeof value === 'string') {
                    value = value.trim();
                }

                field.is_ok = validator(value, options, field);
            }

            if (!field.is_ok) {
                message = options.message || validators_map[type].message;
                if (type === 'length') {
                    message = localize(message, [options.min === options.max ? options.min : `${options.min}-${options.max}`]);
                } else if (type === 'min') {
                    message = localize(message, [options.min]);
                } else if (type === 'not_equal') {
                    message = localize(message, [localize(options.name1), localize(options.name2)]);
                }
                all_is_ok = false;
                return true; // break on the first error found
            }
            return false; // check next validation
        });

        if (!all_is_ok) {
            showError(field, message);
        } else {
            clearError(field);
        }

        return all_is_ok;
    };

    const clearError = (field) => {
        if (field.$error && field.$error.length) {
            field.$error.setVisibility(0);
            if (field.$submit_btn_error && field.$submit_btn_error.length) {
                field.$submit_btn_error.setVisibility(0);
            }
        }
    };

    const showError = (field, message) => {
        clearError(field);
        Password.removeCheck(field.selector);
        field.$error.html(localize(message)).setVisibility(1);
    };

    const validate = (form_selector) => {
        const form = forms[form_selector];
        if (!form.fields) return true;
        form.is_ok = true;
        form.fields.forEach((field) => {
            if (!checkField(field)) {
                if (form.is_ok && !field.no_scroll) { // first error
                    $.scrollTo(field.$, 500, { offset: -10 });
                }
                form.is_ok = false;
            }
        });
        return form.is_ok;
    };

    return {
        validate,
        validEmailToken,

        init: initForm,
    };
})();

module.exports = Validation;
<|endoftext|>


<commit_before>var _merge = require('lodash.merge'),
    path = require('path'),
    lowdb  = require('lowdb')

module.exports = new function() {

  var db = lowdb(path.resolve(__dirname) + '/data.json')

  var collectionKey = 'data'
  db(collectionKey)

  this.add = function(data) {
    var entry = _merge({}, data, {
        timestamp: new Date().getTime()
      }
    )
    db.object[collectionKey].push(entry)
    db.save()
  }

}<commit_msg>Change saved time format<commit_after>var _merge = require('lodash.merge'),
    path = require('path'),
    lowdb  = require('lowdb')

module.exports = new function() {

  var db = lowdb(path.resolve(__dirname) + '/data.json')

  var collectionKey = 'data'
  db(collectionKey)

  this.add = function(data) {
    var entry = _merge({}, data, {
        timestamp: new Date().toISOString()
      }
    )
    db.object[collectionKey].push(entry)
    db.save()
  }

}<|endoftext|>


<commit_before>module.exports = {
  getRecentBlogs: getRecentBlogs,
  getOldBlogs: getOldBlogs,
  getProjects: getProjects,
  addBlogPost: addBlogPost,
  getBlogPost: getBlogPost,
  editBlogPost: editBlogPost,
  addProjectPost: addProjectPost,
  getProjectPost: getProjectPost,
  editProjectPost: editProjectPost,
  getAuthor: getAuthor
}

// ADMIN SECTION SQL

// Manage Content URL - /admin/contenttype/contenttype

// Manage Taxonomy & Tags - URL - /admin/taxonomies

// Manage Menu Structure - URL - /admin/menus

// Manage Users - URL - /admin/users

// SITE STRUCTURE SQL

// Get recent blog post - URL - frontpage
function getRecentBlogs (connection) {
  return connection('blogs')
  .join('users', 'users.id', 'blogs.author')
  .join('taxonomy_vocabulary', 'taxonomy_vocabulary.id', 'blogs.tags')
  .join('profile', 'profile.id', 'users.profile_id')
  .select('blogs.title', 'blogs.slug', 'blogs.summary', 'blogs.published_date', 'blogs.image', 'profile.first_name', 'profile.last_name', 'profile.id as profile_id', 'taxonomy_vocabulary.title as tags')
  .orderByRaw('blogs.id DESC').limit(5)
}

// Get old blog post - URL - /blog
function getOldBlogs (connection) {
  return connection('blogs')
  .join('users', 'users.id', 'blogs.author')
  .join('taxonomy_vocabulary', 'taxonomy_vocabulary.id', 'blogs.tags')
  .join('profile', 'profile.id', 'users.profile_id')
  .select('blogs.title', 'blogs.slug', 'blogs.summary', 'blogs.published_date', 'blogs.image', 'profile.first_name', 'profile.last_name', 'profile.id as profile_id', 'taxonomy_vocabulary.title as tags')
  .orderByRaw('blogs.id DESC').offset(5)
}

// Get list of project - URL - /projects
function getProjects (connection) {
  return connection('projects')
  .join('taxonomy_vocabulary', 'taxonomy_vocabulary.id', 'projects.tags')
  .select('projects.title as projectTitle', 'projects.description as projectDescription', 'goals', 'requirements', 'outcome', 'status', 'published_date')
  .orderByRaw('projects.id DESC')
}

// BLOG SQL

// Add Blog
function addBlogPost (title, slug, body, author, summary, image, status, date, tags, connection) {
  return connection('users')
  .where('name', '=', author)
  .then((result) => {
    const authorId = result[0].id
    return connection('blogs')
    .insert({'title': title, 'body': body, 'author': authorId, 'summary': summary, 'image': image, 'status': status, 'published_date': date, 'tags': tags, 'type': 'blog', 'slug': slug})
  })
  .then((result) => {
    const id = result
    return connection('blogs')
    .where('id', id)
    .select()
  })
}

// Get Blog
function getBlogPost (blogSlug, connection) {
  return connection('blogs')
  .join('users', 'users.id', 'blogs.author')
  .join('taxonomy_vocabulary', 'taxonomy_vocabulary.id', 'blogs.tags')
  .join('profile', 'profile.id', 'users.profile_id')
  .where('blogs.slug', '=', blogSlug)
  .select('blogs.title', 'blogs.body', 'blogs.summary', 'blogs.published_date', 'blogs.image', 'profile.first_name', 'profile.last_name', 'profile.id as profile_id', 'taxonomy_vocabulary.title as tags', 'blogs.image')
}

// Edit Blog
function editBlogPost (blogSlug, connection) {
  return connection('blogs')
  .where('blogs.slug', '=', blogSlug)
  .update()
  .then((result) => {
    const id = result
    return connection('pages')
    .where('id', id)
    .select()
  })
}

// PROJECTS CONTENT TYPE SQL

// Add Project
function addProjectPost (title, description, goals, requirements, outcome, author, status, date, connection) {
  return connection('users')
  .where('name', '=', author)
  .then((result) => {
    const authorId = result[0].id
    return connection('projects')
    .insert({ 'title': title, 'description': description, 'goals': goals, 'requirements': requirements, 'outcome': outcome, 'status': status, 'published_date': '2017-04-12 08:00:00', 'type': 'projects', 'author': authorId })
    .then((result) => {
      const id = result
      return connection('projects')
      .where('id', id)
      .select()
    })
  })
}
// Get Project
function getProjectPost (id, connection) {
  return connection('projects')
  .join('users', 'users.id', 'projects.author')
  .select()
  .where('id', id)
}

// Edit Project
function editProjectPost (id, connection) {
  return connection('projects')
  .where('id', id)
  .update()
  .then((result) => {
    const id = result
    return connection('pages')
    .where('id', id)
    .select()
  })
}
// PAGE CONTENT TYPE SQL

// Add Page

// Get Page

// Edit Page

// TAXONOMY SQL

// PROFILE SQL

// MENU SQL

// HELPER SQL

// Fetch Profile -> User

// Fetch
function getAuthor (author, connection) {
  return connection('users')
  .where('users.name', 'like', `%${author}%`)
  .select('users.name')
}
<commit_msg>Remove db.js file<commit_after><|endoftext|>


<commit_before>// Require GitHub storage provider to work...
(function (staticWeb) {
    "use strict";
    var MemberTest = function (element) {
        if (!(this instanceof MemberTest)) {
            return new MemberTest(element);
        }

        return this.init(element);
    }
    MemberTest.prototype = {
        init: function (element) {
            var self = this;
            self._element = element;
            self._template = false;
            self._apartmentInfo = false;

            staticWeb.retrieveTemplate("brfskagagard-member-options", function (template) {
                self._template = template;
                staticWeb.insertTemplate(self._template, self._element);
                if (self._apartmentInfo) {
                    self.updateApartmentInfo(self._apartmentInfo);
                }
            });

            if (!staticWeb.config.permissions.check || staticWeb.isUserLevel('member')) {
                self.createInterface(staticWeb.storage);
            }
        },
        getApartmentRepo: function (storage, callback) {
            var apartmentRepo = localStorage.getItem('brfskagagard-member-apartment-repo');
            if (!!apartmentRepo) {
                callback(apartmentRepo);
            } else {
                storage.listStorages(function (repos) {
                    for (var repoIndex = 0; repoIndex < repos.length; repoIndex++) {
                        var currentRepo = repos[repoIndex];
                        // in our test the repo name needs to start with 'brfskagagard-lgh'
                        var isApartmentRepo = currentRepo.name.indexOf('brfskagagard-lgh') === 0;
                        if (isApartmentRepo) {
                            // Storing for faster use next time
                            localStorage.setItem('brfskagagard-member-apartment-repo', currentRepo.path);
                            callback(currentRepo.path);
                            return;
                        }
                    }
                    callback(false);
                });
            }
        },
        updateApartmentInfo: function (apartmentInfo) {
            var options = document.getElementsByClassName('brfskagagard-member-options');
            for (var index = 0; index < options.length; index++) {
                var element = options[index];
                element.style.display = 'block';
            }

            this.setTextOnElements('flowertwig-mypages-options-info-building', apartmentInfo.Building);
            this.setTextOnElements('flowertwig-mypages-options-info-apartment', 'Lgh. ' + apartmentInfo.Number);
            this.setTextOnElements('flowertwig-mypages-options-info-size', 'Storlek: ' + apartmentInfo.Size);

            var delivery = [];
            for (var index = 0; index < apartmentInfo.Owners.length; index++) {
                var owner = apartmentInfo.Owners[index];
                for (var index2 = 0; index2 < owner.WayOfInfo.length; index2++) {
                    var way = owner.WayOfInfo[index2];
                    if (delivery.indexOf(way) === -1) {
                        delivery.push(way);
                    }
                }
            }

            this.setTextOnElements('flowertwig-mypages-options-info-delivery', delivery.join(','));
            this.setTextOnElements('flowertwig-mypages-options-info-tenents', 'Boende: ' + apartmentInfo.Owners.length + ' st');
        },
        setTextOnElements: function (className, text) {
            var elements = document.getElementsByClassName(className);
            for (var index = 0; index < elements.length; index++) {
                var element = elements[index];
                this.setTextForElement(element, text);
            }
        },
        setTextForElement: function (element, text) {
            element.innerText = text;
        },
        createInterface: function (storage) {
            var self = this;

            // This method will be called by swadmin.js when storage is ready to be used.
            this.getApartmentRepo(storage, function (repoPath) {
                // Check if we have a valid repo path
                if (!!repoPath) {
                    storage.get(
                        'apartment.json',
                        function (info, status) {
                            if (status.isOK) {
                                // Get apartment info
                                var apartmentInfo = JSON.parse(info.data);
                                self._apartmentInfo = apartmentInfo;
                                if (self._template) {
                                    self.updateApartmentInfo(apartmentInfo);
                                }
                            }
                        },
                        { 'repo': repoPath }
                    );
                } else {
                    // TODO: update view to user, invalid access...
                }
            });
        }
    }
    staticWeb.registerComponent('brfskagagard-member-options', MemberTest);
})(window.StaticWeb);<commit_msg>change to support html encoded chars<commit_after>// Require GitHub storage provider to work...
(function (staticWeb) {
    "use strict";
    var MemberTest = function (element) {
        if (!(this instanceof MemberTest)) {
            return new MemberTest(element);
        }

        return this.init(element);
    }
    MemberTest.prototype = {
        init: function (element) {
            var self = this;
            self._element = element;
            self._template = false;
            self._apartmentInfo = false;

            staticWeb.retrieveTemplate("brfskagagard-member-options", function (template) {
                self._template = template;
                staticWeb.insertTemplate(self._template, self._element);
                if (self._apartmentInfo) {
                    self.updateApartmentInfo(self._apartmentInfo);
                }
            });

            if (!staticWeb.config.permissions.check || staticWeb.isUserLevel('member')) {
                self.createInterface(staticWeb.storage);
            }
        },
        getApartmentRepo: function (storage, callback) {
            var apartmentRepo = localStorage.getItem('brfskagagard-member-apartment-repo');
            if (!!apartmentRepo) {
                callback(apartmentRepo);
            } else {
                storage.listStorages(function (repos) {
                    for (var repoIndex = 0; repoIndex < repos.length; repoIndex++) {
                        var currentRepo = repos[repoIndex];
                        // in our test the repo name needs to start with 'brfskagagard-lgh'
                        var isApartmentRepo = currentRepo.name.indexOf('brfskagagard-lgh') === 0;
                        if (isApartmentRepo) {
                            // Storing for faster use next time
                            localStorage.setItem('brfskagagard-member-apartment-repo', currentRepo.path);
                            callback(currentRepo.path);
                            return;
                        }
                    }
                    callback(false);
                });
            }
        },
        updateApartmentInfo: function (apartmentInfo) {
            var options = document.getElementsByClassName('brfskagagard-member-options');
            for (var index = 0; index < options.length; index++) {
                var element = options[index];
                element.style.display = 'block';
            }

            this.setTextOnElements('flowertwig-mypages-options-info-building', apartmentInfo.Building);
            this.setTextOnElements('flowertwig-mypages-options-info-apartment', 'Lgh. ' + apartmentInfo.Number);
            this.setTextOnElements('flowertwig-mypages-options-info-size', 'Storlek: ' + apartmentInfo.Size);

            var delivery = [];
            for (var index = 0; index < apartmentInfo.Owners.length; index++) {
                var owner = apartmentInfo.Owners[index];
                for (var index2 = 0; index2 < owner.WayOfInfo.length; index2++) {
                    var way = owner.WayOfInfo[index2];
                    if (delivery.indexOf(way) === -1) {
                        delivery.push(way);
                    }
                }
            }

            this.setTextOnElements('flowertwig-mypages-options-info-delivery', delivery.join(','));
            this.setTextOnElements('flowertwig-mypages-options-info-tenents', 'Boende: ' + apartmentInfo.Owners.length + ' st');
        },
        setTextOnElements: function (className, text) {
            var elements = document.getElementsByClassName(className);
            for (var index = 0; index < elements.length; index++) {
                var element = elements[index];
                this.setTextForElement(element, text);
            }
        },
        setTextForElement: function (element, text) {
            element.innerHTML = text;
        },
        createInterface: function (storage) {
            var self = this;

            // This method will be called by swadmin.js when storage is ready to be used.
            this.getApartmentRepo(storage, function (repoPath) {
                // Check if we have a valid repo path
                if (!!repoPath) {
                    storage.get(
                        'apartment.json',
                        function (info, status) {
                            if (status.isOK) {
                                // Get apartment info
                                var apartmentInfo = JSON.parse(info.data);
                                self._apartmentInfo = apartmentInfo;
                                if (self._template) {
                                    self.updateApartmentInfo(apartmentInfo);
                                }
                            }
                        },
                        { 'repo': repoPath }
                    );
                } else {
                    // TODO: update view to user, invalid access...
                }
            });
        }
    }
    staticWeb.registerComponent('brfskagagard-member-options', MemberTest);
})(window.StaticWeb);<|endoftext|>


<commit_before>var basex = require('basex');
var cheerio = require('cheerio');
var _ = require('underscore');

var session = new basex.Session(process.env.BASEX_HOST || 'localhost',
                                process.env.BASEX_PORT || 1984,
                                process.env.BASEX_USER || 'admin',
                                process.env.BASEX_PASS || 'admin');

basex.Session.prototype.search= function(query, cb) {
  var xquery =
    "for $hit in collection('colenso')\n" +
    "where $hit//*:text[descendant::text() contains text '" + query + "']\n" +
    "return
{ $hit//*:title }
";
  this.execute("XQUERY <result> { " + xquery + " } </result> ",
                function(err, data) {
                  if (err) {
                    cb(err);
                    return;
                  }
                  var $ = cheerio.load(data.result);
                  var list = [];
                  $('li').each(function(i, elem) {
                    list[i] = { title: $(this).text().trim(),
                      path: $(this).attr('path')
                    };
                  });
                  cb(undefined, list);
                });
};

basex.Session.prototype.searchXPath = function(query, cb) {
  var xquery =
    "for $hit in collection('colenso')\n" +
    "where $hit" + query + "\n" +
    "return
{ $hit//*:title }
";
  this.execute("XQUERY <result> { " + xquery + " } </result> ",
                function(err, data) {
                  if (err) {
                    cb(err);
                    return;
                  }
                  var $ = cheerio.load(data.result);
                  var list = [];
                  $('li').each(function(i, elem) {
                    list[i] = { title: $(this).text().trim(),
                      path: $(this).attr('path')
                    };
                  });
                  cb(undefined, list);
                });
};

basex.Session.prototype.searchXQuery = function(query, cb) {
  console.log(query);
  this.execute("XQUERY " + query,
                function(err, data) {
                  if (err) {
                    cb(err);
                    console.log(err);
                    return;
                  }
                  cb(undefined, data);
                });
};

basex.Session.prototype.documentsInFolder = function(path, cb) {
  this.execute("XQUERY <result> { for $c in collection('colenso" + path + "')\n return
{ $c//*:title }
 } </result> ",
                function(err, data) {
                  if (err) {
                    cb(err);
                    return;
                  }
                  var $ = cheerio.load(data.result);
                  var list = [];
                  $('li').each(function(i, elem) {
                    list[i] = {
                      title: $(this).text().trim(),
                      path: $(this).attr('path')
                    };
                  });
                  cb(undefined, list);
                });
};

basex.Session.prototype.foldersInPath = function(path, cb)  {
  this.documentsInFolder(path, function(err, data) {
    path = path.replace('/', '');
    if (err) {
      cb(err);
      return;
    }
    var list = _.map(data, function(line) {
      line.path = line.path.replace(path, '');
      if (line.path.indexOf('/') > -1) {
        line.path = line.path.replace(/^\//, '');
        line.path = line.path.replace(/\/.*$/, '');
        if (line.path.indexOf('.xml') < 0) {
          line.title = line.path.replace(/_/g, ' ');
        }
      }
      return line;
    });
    list = _.uniq(list, function (e) { return e.path; });
    cb(undefined, list);
  });
};

basex.Session.prototype.getDocument = function(path, cb) {
  this.execute("XQUERY doc('colenso" + path + "')",
                function(err, data) {
                  if (err) {
                    cb(err);
                    return;
                  }
                  cb(undefined, data.result);
                });
};

module.exports = session;
<commit_msg>xpath query does not require TEI: or *: prefix for elements<commit_after>var basex = require('basex');
var cheerio = require('cheerio');
var _ = require('underscore');

var session = new basex.Session(process.env.BASEX_HOST || 'localhost',
                                process.env.BASEX_PORT || 1984,
                                process.env.BASEX_USER || 'admin',
                                process.env.BASEX_PASS || 'admin');

basex.Session.prototype.search= function(query, cb) {
  var xquery =
    "for $hit in collection('colenso')\n" +
    "where $hit//*:text[descendant::text() contains text '" + query + "']\n" +
    "return
{ $hit//*:title }
";
  this.execute("XQUERY <result> { " + xquery + " } </result> ",
                function(err, data) {
                  if (err) {
                    cb(err);
                    return;
                  }
                  var $ = cheerio.load(data.result);
                  var list = [];
                  $('li').each(function(i, elem) {
                    list[i] = { title: $(this).text().trim(),
                      path: $(this).attr('path')
                    };
                  });
                  cb(undefined, list);
                });
};

basex.Session.prototype.searchXPath = function(query, cb) {
  var xquery =
    "for $hit in collection('colenso')\n" +
    "where $hit" + query + "\n" +
    "return
{ $hit//*:title }
";
  this.execute("XQUERY declare default element namespace 'http://www.tei-c.org/ns/1.0';\n <result> { " + xquery + " } </result> ",
                function(err, data) {
                  if (err) {
                    cb(err);
                    return;
                  }
                  var $ = cheerio.load(data.result);
                  var list = [];
                  $('li').each(function(i, elem) {
                    list[i] = { title: $(this).text().trim(),
                      path: $(this).attr('path')
                    };
                  });
                  cb(undefined, list);
                });
};

basex.Session.prototype.searchXQuery = function(query, cb) {
  console.log(query);
  this.execute("XQUERY " + query,
                function(err, data) {
                  if (err) {
                    cb(err);
                    console.log(err);
                    return;
                  }
                  cb(undefined, data);
                });
};

basex.Session.prototype.documentsInFolder = function(path, cb) {
  this.execute("XQUERY <result> { for $c in collection('colenso" + path + "')\n return
{ $c//*:title }
 } </result> ",
                function(err, data) {
                  if (err) {
                    cb(err);
                    return;
                  }
                  var $ = cheerio.load(data.result);
                  var list = [];
                  $('li').each(function(i, elem) {
                    list[i] = {
                      title: $(this).text().trim(),
                      path: $(this).attr('path')
                    };
                  });
                  cb(undefined, list);
                });
};

basex.Session.prototype.foldersInPath = function(path, cb)  {
  this.documentsInFolder(path, function(err, data) {
    path = path.replace('/', '');
    if (err) {
      cb(err);
      return;
    }
    var list = _.map(data, function(line) {
      line.path = line.path.replace(path, '');
      if (line.path.indexOf('/') > -1) {
        line.path = line.path.replace(/^\//, '');
        line.path = line.path.replace(/\/.*$/, '');
        if (line.path.indexOf('.xml') < 0) {
          line.title = line.path.replace(/_/g, ' ');
        }
      }
      return line;
    });
    list = _.uniq(list, function (e) { return e.path; });
    cb(undefined, list);
  });
};

basex.Session.prototype.getDocument = function(path, cb) {
  this.execute("XQUERY doc('colenso" + path + "')",
                function(err, data) {
                  if (err) {
                    cb(err);
                    return;
                  }
                  cb(undefined, data.result);
                });
};

module.exports = session;
<|endoftext|>


<commit_before>var players = {};
var turrets = {};

//////////////////////////////// BLUE TEAM BOUUH
players.blue = [{
    name: 'Wickd',
    laning: 80,
    champion: 'Irelia',
    irelia: 99,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 1,
    role: 'top',
    status: 'laning',
	camp: 'none',
    team: 'blue',
	DOMElement: document.getElementById('mapChampionBlueTop')

},{
    name: 'Shook',
    laning: 35,
    champion: 'Riven',
    riven: 90,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 2,
    role: 'jungler',
	status: 'jungling',
	camp: 'BlueSentinelle',
    team: 'blue',
	DOMElement: document.getElementById('mapChampionBlueJungler')
},{
    name: 'Froggen',
    laning: 90,
    champion: 'Anivia',
    anivia: 100,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 3,
    role: 'mid',
    status: 'laning',
	camp: 'none',
    team: 'blue',
	DOMElement: document.getElementById('mapChampionBlueMid')
},{
    name: 'Rekkles',
    laning: 100,
    champion: 'Lucian',
    lucian: 85,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 4,
    role: 'adc',
    status: 'laning',
	camp: 'none',
    team: 'blue',
	DOMElement: document.getElementById('mapChampionBlueAdc')
},{
    name: 'Nyph',
    laning: 75,
    champion: 'Thresh',
	thresh: 80,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 4,
    role: 'support',
    status: 'laning',
	camp: 'none',
    team: 'blue',
	DOMElement: document.getElementById('mapChampionBlueSupport')
}];

//////////////////////////////// RED TEAM YAY
players.red = [{
    name: 'Gollwu',
    laning: 50,
    champion: 'Trundle',
    trundle: 79,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 1,
    role: 'top',
    status: 'laning',
	camp: 'none',
    team: 'red',
	DOMElement: document.getElementById('mapChampionRedTop')
},{
    name: 'Nerevar',
    laning: 25,
    champion: 'Fiddlesticks',
    fiddlesticks: 65,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 2,
    role: 'jungler',
    status: 'jungling',
	camp: 'RedSentinelle',
    team: 'red',
	DOMElement: document.getElementById('mapChampionRedJungler')
},{
    name: 'Overplow',
    laning: 51,
    champion: 'KogMaw',
    kogmaw: 80,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 3,
    role: 'mid',
    status: 'laning',
	camp: 'none',
    team: 'red',
	DOMElement: document.getElementById('mapChampionRedMid')
},{
    name: 'Hycariss',
    laning: 85,
    champion: 'Vayne',
	vayne: 65,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 4,
    role: 'adc',
    status: 'laning',
	camp: 'none',
    team: 'red',
	DOMElement: document.getElementById('mapChampionRedAdc')
},{
    name: 'Sowerdski',
    laning: 10,
    champion: 'Taric',
	taric:0,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 4,
    role: 'support',
    status: 'laning',
	camp: 'none',
    team: 'red',
	DOMElement: document.getElementById('mapChampionRedSupport')
}];

nexus = [{
    name: 'blueNexus',
    hp:100
	DOMElement: document.getElementById('blueNexus')
},{
    name: 'redNexus',
    hp:100
	DOMElement: document.getElementById('redNexus')
}];

inhibs = [{
    name: 'blueInhibTop',
    hp:100
	DOMElement: document.getElementById('blueInhibTop')
},{
    name: 'blueInhibMid',
    hp:100
	DOMElement: document.getElementById('blueInhibMid')
},{
    name: 'blueInhibBot',
    hp:100
	DOMElement: document.getElementById('blueInhibBot')
},{
    name: 'redInhibTop',
    hp:100
	DOMElement: document.getElementById('redInhibTop')
},{
    name: 'redInhibMid',
    hp:100
	DOMElement: document.getElementById('redInhibMid')
},{
    name: 'redInhibBot',
    hp:100
	DOMElement: document.getElementById('redInhibBot')
}];

turrets = [{
    name: 'blueNexusTurret1',
    hp:100
	DOMElement: document.getElementById('blueNexusTurret1')
},{
    name: 'blueNexusTurret2',
    hp:100
	DOMElement: document.getElementById('blueNexusTurret2')
},{
    name: 'blueTopInhibTurret',
    hp:100
	DOMElement: document.getElementById('blueTopInhibTurret')
},{
    name: 'blueMidInhibTurret',
    hp:100
	DOMElement: document.getElementById('blueMidInhibTurret')
},{
    name: 'blueBotInhibturret',
    hp:100
	DOMElement: document.getElementById('blueBotInhibturret')
},{
    name: 'blueTopInnerTurret',
    hp:100
	DOMElement: document.getElementById('blueTopInnerTurret')
},{
    name: 'blueMidInnerTurret',
    hp:100
	DOMElement: document.getElementById('blueMidInnerTurret')
},{
    name: 'blueBotInnerTurret',
    hp:100
	DOMElement: document.getElementById('blueBotInnerTurret')
},{
    name: 'blueTopOuterTurret',
    hp:100
	DOMElement: document.getElementById('blueBotInnerTurret')
},{
    name: 'blueMidOuterTurret',
    hp:100
	DOMElement: document.getElementById('blueBotInnerTurret')
},{
    name: 'blueBotOuterTurret',
    hp:100
	DOMElement: document.getElementById('blueBotInnerTurret')
},{
    name: 'redNexusTurret1',
    hp:100
	DOMElement: document.getElementById('redNexusTurret1')
},{
    name: 'redNexusTurret2',
    hp:100
	DOMElement: document.getElementById('redNexusTurret2')
},{
    name: 'redTopInhibTurret',
    hp:100
	DOMElement: document.getElementById('redTopInhibTurret')
},{
    name: 'redMidInhibTurret',
    hp:100
	DOMElement: document.getElementById('redMidInhibTurret')
},{
    name: 'redBotInhibTurret',
    hp:100
	DOMElement: document.getElementById('redBotInhibTurret')
},{
    name: 'redTopInnerTurret',
    hp:100
	DOMElement: document.getElementById('redTopInnerTurret')
},{
    name: 'redMidInnerTurret',
    hp:100
	DOMElement: document.getElementById('redMidInnerTurret')
},{
    name: 'redBotInnerTurret',
    hp:100
	DOMElement: document.getElementById('redBotInnerTurret')
},{
    name: 'redTopOuterTurret',
    hp:100
	DOMElement: document.getElementById('redTopOuterTurret')
},{
    name: 'redMidOuterTurret',
    hp:100
	DOMElement: document.getElementById('redMidOuterTurret')
},{
    name: 'redBotOuterTurret',
    hp:100
	DOMElement: document.getElementById('redBotOuterTurret')
}];
<commit_msg>turret db fix<commit_after>var players = {};
var turrets = {};
var nexus = {};
var inhibs = {};

//////////////////////////////// BLUE TEAM BOUUH
players.blue = [{
    name: 'Wickd',
    laning: 80,
    champion: 'Irelia',
    irelia: 99,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 1,
    role: 'top',
    status: 'laning',
	camp: 'none',
    team: 'blue',
	DOMElement: document.getElementById('mapChampionBlueTop')

},{
    name: 'Shook',
    laning: 35,
    champion: 'Riven',
    riven: 90,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 2,
    role: 'jungler',
	status: 'jungling',
	camp: 'BlueSentinelle',
    team: 'blue',
	DOMElement: document.getElementById('mapChampionBlueJungler')
},{
    name: 'Froggen',
    laning: 90,
    champion: 'Anivia',
    anivia: 100,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 3,
    role: 'mid',
    status: 'laning',
	camp: 'none',
    team: 'blue',
	DOMElement: document.getElementById('mapChampionBlueMid')
},{
    name: 'Rekkles',
    laning: 100,
    champion: 'Lucian',
    lucian: 85,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 4,
    role: 'adc',
    status: 'laning',
	camp: 'none',
    team: 'blue',
	DOMElement: document.getElementById('mapChampionBlueAdc')
},{
    name: 'Nyph',
    laning: 75,
    champion: 'Thresh',
	thresh: 80,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 4,
    role: 'support',
    status: 'laning',
	camp: 'none',
    team: 'blue',
	DOMElement: document.getElementById('mapChampionBlueSupport')
}];

//////////////////////////////// RED TEAM YAY
players.red = [{
    name: 'Gollwu',
    laning: 50,
    champion: 'Trundle',
    trundle: 79,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 1,
    role: 'top',
    status: 'laning',
	camp: 'none',
    team: 'red',
	DOMElement: document.getElementById('mapChampionRedTop')
},{
    name: 'Nerevar',
    laning: 25,
    champion: 'Fiddlesticks',
    fiddlesticks: 65,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 2,
    role: 'jungler',
    status: 'jungling',
	camp: 'RedSentinelle',
    team: 'red',
	DOMElement: document.getElementById('mapChampionRedJungler')
},{
    name: 'Overplow',
    laning: 51,
    champion: 'KogMaw',
    kogmaw: 80,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 3,
    role: 'mid',
    status: 'laning',
	camp: 'none',
    team: 'red',
	DOMElement: document.getElementById('mapChampionRedMid')
},{
    name: 'Hycariss',
    laning: 85,
    champion: 'Vayne',
	vayne: 65,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 4,
    role: 'adc',
    status: 'laning',
	camp: 'none',
    team: 'red',
	DOMElement: document.getElementById('mapChampionRedAdc')
},{
    name: 'Sowerdski',
    laning: 10,
    champion: 'Taric',
	taric:0,
    gold: 475,
    stuffValue: 475,
    kills:0,
    deaths:0,
    assists:0,
    hp: 100,
    lane: 4,
    role: 'support',
    status: 'laning',
	camp: 'none',
    team: 'red',
	DOMElement: document.getElementById('mapChampionRedSupport')
}];

nexus = [{
    name: 'blueNexus',
    hp:100
	DOMElement: document.getElementById('blueNexus')
},{
    name: 'redNexus',
    hp:100
	DOMElement: document.getElementById('redNexus')
}];

inhibs = [{
    name: 'blueInhibTop',
    hp:100
	DOMElement: document.getElementById('blueInhibTop')
},{
    name: 'blueInhibMid',
    hp:100
	DOMElement: document.getElementById('blueInhibMid')
},{
    name: 'blueInhibBot',
    hp:100
	DOMElement: document.getElementById('blueInhibBot')
},{
    name: 'redInhibTop',
    hp:100
	DOMElement: document.getElementById('redInhibTop')
},{
    name: 'redInhibMid',
    hp:100
	DOMElement: document.getElementById('redInhibMid')
},{
    name: 'redInhibBot',
    hp:100
	DOMElement: document.getElementById('redInhibBot')
}];

turrets = [{
    name: 'blueNexusTurret1',
    hp:100
	DOMElement: document.getElementById('blueNexusTurret1')
},{
    name: 'blueNexusTurret2',
    hp:100
	DOMElement: document.getElementById('blueNexusTurret2')
},{
    name: 'blueTopInhibTurret',
    hp:100
	DOMElement: document.getElementById('blueTopInhibTurret')
},{
    name: 'blueMidInhibTurret',
    hp:100
	DOMElement: document.getElementById('blueMidInhibTurret')
},{
    name: 'blueBotInhibturret',
    hp:100
	DOMElement: document.getElementById('blueBotInhibturret')
},{
    name: 'blueTopInnerTurret',
    hp:100
	DOMElement: document.getElementById('blueTopInnerTurret')
},{
    name: 'blueMidInnerTurret',
    hp:100
	DOMElement: document.getElementById('blueMidInnerTurret')
},{
    name: 'blueBotInnerTurret',
    hp:100
	DOMElement: document.getElementById('blueBotInnerTurret')
},{
    name: 'blueTopOuterTurret',
    hp:100
	DOMElement: document.getElementById('blueBotInnerTurret')
},{
    name: 'blueMidOuterTurret',
    hp:100
	DOMElement: document.getElementById('blueBotInnerTurret')
},{
    name: 'blueBotOuterTurret',
    hp:100
	DOMElement: document.getElementById('blueBotInnerTurret')
},{
    name: 'redNexusTurret1',
    hp:100
	DOMElement: document.getElementById('redNexusTurret1')
},{
    name: 'redNexusTurret2',
    hp:100
	DOMElement: document.getElementById('redNexusTurret2')
},{
    name: 'redTopInhibTurret',
    hp:100
	DOMElement: document.getElementById('redTopInhibTurret')
},{
    name: 'redMidInhibTurret',
    hp:100
	DOMElement: document.getElementById('redMidInhibTurret')
},{
    name: 'redBotInhibTurret',
    hp:100
	DOMElement: document.getElementById('redBotInhibTurret')
},{
    name: 'redTopInnerTurret',
    hp:100
	DOMElement: document.getElementById('redTopInnerTurret')
},{
    name: 'redMidInnerTurret',
    hp:100
	DOMElement: document.getElementById('redMidInnerTurret')
},{
    name: 'redBotInnerTurret',
    hp:100
	DOMElement: document.getElementById('redBotInnerTurret')
},{
    name: 'redTopOuterTurret',
    hp:100
	DOMElement: document.getElementById('redTopOuterTurret')
},{
    name: 'redMidOuterTurret',
    hp:100
	DOMElement: document.getElementById('redMidOuterTurret')
},{
    name: 'redBotOuterTurret',
    hp:100
	DOMElement: document.getElementById('redBotOuterTurret')
}];

<|endoftext|>


<commit_before>// Interface for making db queries reactive.
// TODO: store dep for each query.
var ReactiveDb = function(collection) {
	this.db = collection;
	this.dep = new Dependency();
};

ReactiveDb.prototype.insert = function(doc) {
	db.insert(doc);
};

ReactiveDb.prototype.update = function(query, change) {
	db.update(query, change);
	this.dep.changed();
};

ReactiveDb.prototype.find = function(query) {
	this.dep.depend();
	db.find(query);
};

ReactiveDb.prototype.remove = function(query) {
	db.remove(query);
	this.dep.changed();
};
<commit_msg>Removes db attempt from master.<commit_after><|endoftext|>


<commit_before>
/*
 Copyright 2013 Simon Paulger <spaulger@codezen.co.uk>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

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

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

(function() {
    'use strict';

    Backbone.StorageProxy = function()
    {

    };

    /**
     * Construct a new storage proxy with the storage adapters
     * passed.
     *
     * @param modelOrCollection Model or collection to override sync method
     * @param storageAdapters Array of storage adapters
     * @returns {Backbone.StorageProxy} Constructed storage proxy
     */
    Backbone.StorageProxy.factory = function(modelOrCollection, storageAdapters)
    {
        Backbone.StorageProxy.overrideSync(modelOrCollection);
        return new Backbone.StorageProxy().setStorageAdapters(storageAdapters);
    };

    /**
     * Override the sync method of the model or collection.
     *
     * @param modelOrCollection Model or collection object
     */
    Backbone.StorageProxy.overrideSync = function(modelOrCollection)
    {
        // Override model or collection sync method
        modelOrCollection.backboneSync = modelOrCollection.sync;
        modelOrCollection.sync = function(method, model, options) {
            // Get storage proxy
            var storageProxy;

            if (model.storageProxy && model.storageProxy instanceof Backbone.StorageProxy) {
                storageProxy = model.storageProxy;
            } else if (model.collection && model.collection.storageProxy &&
                model.collection.storageProx instanceof Backbone.StorageProxy) {
                storageProxy = model.collection.storageProxy;
            } else {
                throw new TypeError('Storage proxy not found or removed from model or collection, ' +
                    'or is not of type Backbone.StorageProxy.');
            }

            // Call all storage adapters attached to the storage proxy
            // and notify the callbacks with the appropriate responses
            var storageAdapters = storageProxy.getStorageAdapters();
            for(var i = 0; i < storageAdapters.length; i++) {
                var args = [];
                for (var x = 0; x < arguments.length; x++) {
                    args.push(arguments[x]);
                }
                args.push(storageAdapters[i].adapter.sync.apply(storageAdapters[i].adapter, arguments));

                if (storageAdapters[i].callback.apply(model, args) !== true) {
                    // Short circuit any further storage adapter execution
                    break;
                }
            }
        };
    };

    Backbone.StorageProxy.prototype = {
        /**
         * List of storage adapters to forward sync calls to.
         */
        _storageAdapters: [],

        /**
         * Sets all the list of storage adapters to proxy to
         * to the list provided.
         *
         * @param storageAdapters Array of storage adapters
         * @return {Backbone.StorageProxy} this
         */
        setStorageAdapters: function(storageAdapters) {
            if (storageAdapters == null) {
                this.reset();
            } else {
                // Validate storage adapter array
                for (var i = 0; i < storageAdapters.length; i++) {
                    if (storageAdapters[i].adapter == null) {
                        throw new TypeError('Storage adapter at position ' + i + ' not defined.');
                    } else if (storageAdapters[i].callback == null) {
                        throw new TypeError('Storage adapter callback at position ' + i + ' not defined.');
                    }
                }

                this._storageAdapters = storageAdapters;
            }

            return this;
        },

        /**
         * Add a storage adapter to the proxy.
         *
         * @param storageAdapter Single storage adapter
         * @param callback Callback to execute when storage adapter has completed
         * @return {Backbone.StorageProxy} this
         */
        addStorageAdapter: function(storageAdapter, callback) {
            if (storageAdapter == null) {
                throw new TypeError('Storage adapter not defined.');
            } else if (callback == null) {
                throw new TypeError('Storage adapter callback not defined.');
            }

            this._storageAdapters.push({adapter: storageAdapter, callback: callback});

            return this;
        },

        /**
         * Get array of storage adapters.
         *
         * @returns Array of storage adapters
         */
        getStorageAdapters: function() {
            return this._storageAdapters;
        }
    };
})();
<commit_msg>Rest adapter for original backbone sync method<commit_after>
/*
 Copyright 2013 Simon Paulger <spaulger@codezen.co.uk>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

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

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

(function() {
    'use strict';

    Backbone.StorageProxy = function()
    {

    };

    /**
     * Construct a new storage proxy with the storage adapters
     * passed.
     *
     * @param modelOrCollection Model or collection to override sync method
     * @param storageAdapters Array of storage adapters
     * @returns {Backbone.StorageProxy} Constructed storage proxy
     */
    Backbone.StorageProxy.factory = function(modelOrCollection, storageAdapters)
    {
        Backbone.StorageProxy.overrideSync(modelOrCollection);
        return new Backbone.StorageProxy().setStorageAdapters(storageAdapters);
    };

    /**
     * Override the sync method of the model or collection.
     *
     * @param modelOrCollection Model or collection object
     */
    Backbone.StorageProxy.overrideSync = function(modelOrCollection)
    {
        // Override model or collection sync method
        modelOrCollection.backboneSync = modelOrCollection.sync;
        modelOrCollection.sync = function(method, model, options) {
            // Get storage proxy
            var storageProxy;

            if (model.storageProxy && model.storageProxy instanceof Backbone.StorageProxy) {
                storageProxy = model.storageProxy;
            } else if (model.collection && model.collection.storageProxy &&
                model.collection.storageProx instanceof Backbone.StorageProxy) {
                storageProxy = model.collection.storageProxy;
            } else {
                throw new TypeError('Storage proxy not found or removed from model or collection, ' +
                    'or is not of type Backbone.StorageProxy.');
            }

            // Call all storage adapters attached to the storage proxy
            // and notify the callbacks with the appropriate responses
            var storageAdapters = storageProxy.getStorageAdapters();
            for(var i = 0; i < storageAdapters.length; i++) {
                var args = [];
                for (var x = 0; x < arguments.length; x++) {
                    args.push(arguments[x]);
                }
                args.push(storageAdapters[i].adapter.sync.apply(storageAdapters[i].adapter, arguments));

                if (storageAdapters[i].callback.apply(model, args) !== true) {
                    // Short circuit any further storage adapter execution
                    break;
                }
            }
        };
    };

    Backbone.StorageProxy.prototype = {
        /**
         * List of storage adapters to forward sync calls to.
         */
        _storageAdapters: [],

        /**
         * Sets all the list of storage adapters to proxy to
         * to the list provided.
         *
         * @param storageAdapters Array of storage adapters
         * @return {Backbone.StorageProxy} this
         */
        setStorageAdapters: function(storageAdapters) {
            if (storageAdapters == null) {
                this.reset();
            } else {
                // Validate storage adapter array
                for (var i = 0; i < storageAdapters.length; i++) {
                    if (storageAdapters[i].adapter == null) {
                        throw new TypeError('Storage adapter at position ' + i + ' not defined.');
                    } else if (storageAdapters[i].callback == null) {
                        throw new TypeError('Storage adapter callback at position ' + i + ' not defined.');
                    }
                }

                this._storageAdapters = storageAdapters;
            }

            return this;
        },

        /**
         * Add a storage adapter to the proxy.
         *
         * @param storageAdapter Single storage adapter
         * @param callback Callback to execute when storage adapter has completed
         * @return {Backbone.StorageProxy} this
         */
        addStorageAdapter: function(storageAdapter, callback) {
            if (storageAdapter == null) {
                throw new TypeError('Storage adapter not defined.');
            } else if (callback == null) {
                throw new TypeError('Storage adapter callback not defined.');
            }

            this._storageAdapters.push({adapter: storageAdapter, callback: callback});

            return this;
        },

        /**
         * Get array of storage adapters.
         *
         * @returns Array of storage adapters
         */
        getStorageAdapters: function() {
            return this._storageAdapters;
        }
    };

    /**
     * Storage adapter for the Backbone.sync RESTful API implementation
     *
     * @constructor
     */
    Backbone.RestAdapter = function() {

    };

    Backbone.RestAdapter.prototype = {
        /**
         * Forward sync calls to the model or collections original
         * sync method and return results
         *
         * @param method
         * @param model
         * @param options
         * @returns {*}
         */
        sync: function(method, model, options)
        {
            if (model.backboneSync == null) {
                throw new TypeError('Backbone sync method model.backboneSync not found.');
            }

            return model.backboneSync(method, model, options);
        }
    };
})();
<|endoftext|>


<commit_before>dojo.provide("dojox.gfx");

dojo.require("dojox.gfx.matrix");
dojo.require("dojox.gfx._base");

(function(){
	var renderers = (typeof djConfig["gfxRenderer"] == "string" ?
		djConfig["gfxRenderer"] : "svg,vml,silverlight,canvas").split(",");
	for(var i = 0; i < renderers.length; ++i){
		switch(renderers[i]){
			case "svg":
				//TODO: need more comprehensive test for SVG
				if(dojo.isIE == 0){ dojox.gfx.renderer = "svg"; }
				break;
			case "vml":
				if(dojo.isIE != 0){ dojox.gfx.renderer = "vml"; }
				break;
			case "silverlight":
				//TODO: need more comprehensive test for Silverlight
				if(window.Silverlight){ dojox.gfx.renderer = "silverlight"; }
				break;
			case "canvas":
				//TODO: need more comprehensive test for Canvas
				if(dojo.isIE == 0){ dojox.gfx.renderer = "canvas"; }
				break;
		}
		if(dojox.gfx.renderer){ break; }
	}
})();

// include a renderer conditionally
dojo.requireIf(dojox.gfx.renderer == "svg", "dojox.gfx.svg");
dojo.requireIf(dojox.gfx.renderer == "vml", "dojox.gfx.vml");
dojo.requireIf(dojox.gfx.renderer == "silverlight", "dojox.gfx.silverlight");
dojo.requireIf(dojox.gfx.renderer == "canvas", "dojox.gfx.canvas");
<commit_msg>enable canvas rendering on the iphone. Makes 2D charts work there thanks to Chris Mitchell's awesome work.<commit_after>dojo.provide("dojox.gfx");

dojo.require("dojox.gfx.matrix");
dojo.require("dojox.gfx._base");

(function(){
	var renderers = (typeof djConfig["gfxRenderer"] == "string" ?
		djConfig["gfxRenderer"] : "svg,vml,silverlight,canvas").split(",");
	for(var i = 0; i < renderers.length; ++i){
		switch(renderers[i]){
			case "svg":
				//TODO: need more comprehensive test for SVG
				if(!dojo.isIE && (!navigator.userAgent.indexOf("iPhone") < 0)){ dojox.gfx.renderer = "svg"; }
				break;
			case "vml":
				if(dojo.isIE != 0){ dojox.gfx.renderer = "vml"; }
				break;
			case "silverlight":
				//TODO: need more comprehensive test for Silverlight
				if(window.Silverlight){ dojox.gfx.renderer = "silverlight"; }
				break;
			case "canvas":
				//TODO: need more comprehensive test for Canvas
				if(dojo.isIE == 0){ dojox.gfx.renderer = "canvas"; }
				break;
		}
		if(dojox.gfx.renderer){ break; }
	}
})();

// include a renderer conditionally
dojo.requireIf(dojox.gfx.renderer == "svg", "dojox.gfx.svg");
dojo.requireIf(dojox.gfx.renderer == "vml", "dojox.gfx.vml");
dojo.requireIf(dojox.gfx.renderer == "silverlight", "dojox.gfx.silverlight");
dojo.requireIf(dojox.gfx.renderer == "canvas", "dojox.gfx.canvas");
<|endoftext|>