<commit_before>//After
//Alekseyenko, A., and Lee, C. (2007).
//Nested Containment List (NCList): A new algorithm for accelerating
//   interval query of genome alignment and interval databases.
//Bioinformatics, doi:10.1093/bioinformatics/btl647
//http://bioinformatics.oxfordjournals.org/cgi/content/abstract/btl647v1

function NCList() {
}

NCList.prototype.importExisting = function(nclist, sublistIndex) {
    this.topList = nclist;
    this.sublistIndex = sublistIndex;
}

NCList.prototype.fill = function(intervals, sublistIndex) {
    //intervals: array of arrays of [start, end, ...]
    //sublistIndex: index into a [start, end] array for storing a sublist
    //              array. this is so you can use those arrays for something
    //              else, and keep the NCList bookkeeping from interfering.
    //              That's hacky, but keeping a separate copy of the intervals
    //              in the NCList seems like a waste (TODO: measure that waste).
    //half-open?
    this.sublistIndex = sublistIndex;
    var myIntervals = intervals;//.concat();
    //sort by OL
    myIntervals.sort(function(a, b) {
        if (a[0] != b[0])
            return a[0] - b[0];
        else
            return b[1] - a[1];
    });
    var sublistStack = new Array();
    var curList = new Array();
    this.topList = curList;
    curList.push(myIntervals[0]);
    var curInterval, topSublist;
    for (var i = 1, len = myIntervals.length; i < len; i++) {
        curInterval = myIntervals[i];
        //if this interval is contained in the previous interval,
        if (curInterval[1] < myIntervals[i - 1][1]) {
            //create a new sublist starting with this interval
            sublistStack.push(curList);
            curList = new Array(curInterval);
            myIntervals[i - 1][sublistIndex] = curList;
        } else {
            //find the right sublist for this interval
            while (true) {
                if (0 == sublistStack.length) {
                    curList.push(curInterval);
                    break;
                } else {
                    topSublist = sublistStack[sublistStack.length - 1];
                    if (topSublist[topSublist.length - 1][1] > curInterval[1]) {
                        //curList is the first (deepest) sublist that
                        //curInterval fits into
                        curList.push(curInterval);
                        break;
                    } else {
                        curList = sublistStack.pop();
                    }
                }
            }
        }
    }
}

NCList.prototype.binarySearch = function(arr, item, itemIndex) {
    var low = -1;
    var high = arr.length;
    var mid;

    while (high - low > 1) {
        mid = (low + high) >>> 1;
        if (arr[mid][itemIndex] > item)
            high = mid;
        else
            low = mid;
    }

    if (1 == itemIndex) return high; else return low;
}

//due to javascript function-call overhead, there's some copy/pase code below,
//for performance.  If later profiling shows that we can get away with a cleaner
//version using function pointers then it might be better to re-arrange this.

NCList.prototype.iterHelper = function(arr, from, to, fun, inc, searchIndex, testIndex) {
    var len = arr.length;
    var i = this.binarySearch(arr, from, searchIndex);
    while ((i < len)
           && (i >= 0)
           && ((inc * arr[i][testIndex]) < (inc * to))) {
        fun(arr[i]);
        if (arr[i][this.sublistIndex] !== undefined)
            this.iterHelper(arr[i][this.sublistIndex], from, to,
                            fun, inc, searchIndex, testIndex);
        i += inc;
    }
}

NCList.prototype.iterate = function(from, to, fun) {
    //calls the given function for all of the intervals that overlap
    //the given interval.
    //if from <= to, iterates left-to-right, otherwise iterates right-to-left

    //inc: iterate leftward or rightward
    var inc = (from > to) ? -1 : 1;
    //searchIndex: search on start or end
    var searchIndex = (from > to) ? 0 : 1;
    //testIndex: test on start or end
    var testIndex = (from > to) ? 1 : 0;
    this.iterHelper(this.topList, from, to, fun, inc, searchIndex, testIndex);
}

NCList.prototype.overlaps = function(from, to) {
    //returns an array of all of the intervals that overlap
    //the given interval.
    //if from <= to, result is sorted left-to-right (on start),
    //otherwise right-to-left (on end)

    //inc: iterate leftward or rightward
    var inc = (from > to) ? -1 : 1;
    //searchIndex: search on start or end
    var searchIndex = (from > to) ? 0 : 1;
    //testIndex: test on start or end
    var testIndex = (from > to) ? 1 : 0;
    var result = [];
    this.overlapHelper(this.topList, from, to, result,
		       inc, searchIndex, testIndex);
    return result;
}

NCList.prototype.overlapHelper = function(arr, from, to, result,
					  inc, searchIndex, testIndex) {
    var len = arr.length;
    var i = this.binarySearch(arr, from, searchIndex);
    while ((i < len)
           && (i >= 0)
           && ((inc * arr[i][testIndex]) < (inc * to))) {
	result.push(arr[i]);
        if (arr[i][this.sublistIndex] !== undefined)
            this.overlapHelper(arr[i][this.sublistIndex], from, to,
			       result, inc, searchIndex, testIndex);
        i += inc;
    }
}

NCList.prototype.histogram = function(from, to, numBins) {
    //returns a histogram of the feature density in the given interval

    var result = new Array(numBins);
    for (var i = 0; i < numBins; i++) result[i] = 0;
    this.histHelper(this.topList, from, to, result, numBins, (to - from) / numBins);
    return result;
}

NCList.prototype.histHelper = function(arr, from, to, result, numBins, binWidth) {
    var len = arr.length;
    var i = this.binarySearch(arr, from, 1);
    var firstBin, lastBin;
    while ((i < len)
           && (i >= 0)
           && (arr[i][0] < to)) {
	firstBin = Math.max(0, ((arr[i][0] - from) / binWidth) | 0);
	lastBin = Math.min(numBins, ((arr[i][1] - from) / binWidth) | 0);
	for (var bin = firstBin; bin <= lastBin; bin++) result[bin]++;
        if (arr[i][this.sublistIndex] !== undefined)
            this.histHelper(arr[i][this.sublistIndex], from, to, result, numBins, binWidth);
        i++;
    }
}
<commit_msg>small doc addition/fix<commit_after>//After
//Alekseyenko, A., and Lee, C. (2007).
//Nested Containment List (NCList): A new algorithm for accelerating
//   interval query of genome alignment and interval databases.
//Bioinformatics, doi:10.1093/bioinformatics/btl647
//http://bioinformatics.oxfordjournals.org/cgi/content/abstract/btl647v1

function NCList() {
}

NCList.prototype.importExisting = function(nclist, sublistIndex) {
    this.topList = nclist;
    this.sublistIndex = sublistIndex;
}

NCList.prototype.fill = function(intervals, sublistIndex) {
    //intervals: array of arrays of [start, end, ...]
    //sublistIndex: index into a [start, end] array for storing a sublist
    //              array. this is so you can use those arrays for something
    //              else, and keep the NCList bookkeeping from interfering.
    //              That's hacky, but keeping a separate copy of the intervals
    //              in the NCList seems like a waste (TODO: measure that waste).
    //half-open?
    this.sublistIndex = sublistIndex;
    var myIntervals = intervals;//.concat();
    //sort by OL
    myIntervals.sort(function(a, b) {
        if (a[0] != b[0])
            return a[0] - b[0];
        else
            return b[1] - a[1];
    });
    var sublistStack = new Array();
    var curList = new Array();
    this.topList = curList;
    curList.push(myIntervals[0]);
    var curInterval, topSublist;
    for (var i = 1, len = myIntervals.length; i < len; i++) {
        curInterval = myIntervals[i];
        //if this interval is contained in the previous interval,
        if (curInterval[1] < myIntervals[i - 1][1]) {
            //create a new sublist starting with this interval
            sublistStack.push(curList);
            curList = new Array(curInterval);
            myIntervals[i - 1][sublistIndex] = curList;
        } else {
            //find the right sublist for this interval
            while (true) {
                if (0 == sublistStack.length) {
                    curList.push(curInterval);
                    break;
                } else {
                    topSublist = sublistStack[sublistStack.length - 1];
                    if (topSublist[topSublist.length - 1][1] > curInterval[1]) {
                        //curList is the first (deepest) sublist that
                        //curInterval fits into
                        curList.push(curInterval);
                        break;
                    } else {
                        curList = sublistStack.pop();
                    }
                }
            }
        }
    }
}

NCList.prototype.binarySearch = function(arr, item, itemIndex) {
    var low = -1;
    var high = arr.length;
    var mid;

    while (high - low > 1) {
        mid = (low + high) >>> 1;
        if (arr[mid][itemIndex] > item)
            high = mid;
        else
            low = mid;
    }

    //if we're iterating rightward, return the high index;
    //if leftward, the low index
    if (1 == itemIndex) return high; else return low;
}

//due to javascript function-call overhead, there's some copy/paste code below,
//for performance.  If later profiling shows that we can get away with a cleaner
//version using function pointers then it might be better to re-arrange this.

NCList.prototype.iterHelper = function(arr, from, to, fun, inc, searchIndex, testIndex) {
    var len = arr.length;
    var i = this.binarySearch(arr, from, searchIndex);
    while ((i < len)
           && (i >= 0)
           && ((inc * arr[i][testIndex]) < (inc * to))) {
        fun(arr[i]);
        if (arr[i][this.sublistIndex] !== undefined)
            this.iterHelper(arr[i][this.sublistIndex], from, to,
                            fun, inc, searchIndex, testIndex);
        i += inc;
    }
}

NCList.prototype.iterate = function(from, to, fun) {
    //calls the given function for all of the intervals that overlap
    //the given interval.
    //if from <= to, iterates left-to-right, otherwise iterates right-to-left

    //inc: iterate leftward or rightward
    var inc = (from > to) ? -1 : 1;
    //searchIndex: search on start or end
    var searchIndex = (from > to) ? 0 : 1;
    //testIndex: test on start or end
    var testIndex = (from > to) ? 1 : 0;
    this.iterHelper(this.topList, from, to, fun, inc, searchIndex, testIndex);
}

NCList.prototype.overlaps = function(from, to) {
    //returns an array of all of the intervals that overlap
    //the given interval.
    //if from <= to, result is sorted left-to-right (on start),
    //otherwise right-to-left (on end)

    //inc: iterate leftward or rightward
    var inc = (from > to) ? -1 : 1;
    //searchIndex: search on start or end
    var searchIndex = (from > to) ? 0 : 1;
    //testIndex: test on start or end
    var testIndex = (from > to) ? 1 : 0;
    var result = [];
    this.overlapHelper(this.topList, from, to, result,
		       inc, searchIndex, testIndex);
    return result;
}

NCList.prototype.overlapHelper = function(arr, from, to, result,
					  inc, searchIndex, testIndex) {
    var len = arr.length;
    var i = this.binarySearch(arr, from, searchIndex);
    while ((i < len)
           && (i >= 0)
           && ((inc * arr[i][testIndex]) < (inc * to))) {
	result.push(arr[i]);
        if (arr[i][this.sublistIndex] !== undefined)
            this.overlapHelper(arr[i][this.sublistIndex], from, to,
			       result, inc, searchIndex, testIndex);
        i += inc;
    }
}

NCList.prototype.histogram = function(from, to, numBins) {
    //returns a histogram of the feature density in the given interval

    var result = new Array(numBins);
    for (var i = 0; i < numBins; i++) result[i] = 0;
    this.histHelper(this.topList, from, to, result, numBins, (to - from) / numBins);
    return result;
}

NCList.prototype.histHelper = function(arr, from, to, result, numBins, binWidth) {
    var len = arr.length;
    var i = this.binarySearch(arr, from, 1);
    var firstBin, lastBin;
    while ((i < len)
           && (i >= 0)
           && (arr[i][0] < to)) {
	firstBin = Math.max(0, ((arr[i][0] - from) / binWidth) | 0);
	lastBin = Math.min(numBins, ((arr[i][1] - from) / binWidth) | 0);
	for (var bin = firstBin; bin <= lastBin; bin++) result[bin]++;
        if (arr[i][this.sublistIndex] !== undefined)
            this.histHelper(arr[i][this.sublistIndex], from, to, result, numBins, binWidth);
        i++;
    }
}
<|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-render-limit-increase@jonatkins
// @name           IITC plugin: render limit increase
// @category       Tweaks
// @version        0.3.0.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Increase the render limits, so less likely to be hit in higher density areas
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @grant          none
// ==/UserScript==

@@PLUGINSTART@@

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.renderLimitIncrease = function() {};

window.plugin.renderLimitIncrease.setHigherLimits = function() {

  // this controls how far data is being drawn outside the viewport. Set
  // it 0 to only draw entities that intersect the current view. A value
  // of one will render an area twice the size of the viewport (or some-
  // thing like that, Leaflet doc isn’t too specific). Setting it too low
  // makes the missing data on move/zoom out more obvious. Setting it too
  // high causes too many items to be drawn, making drag&drop sluggish.
  // default for iitc is 0.3. a lower value reduces overdraw
  window.VIEWPORT_PAD_RATIO = 0.1;

  // Leaflet will get very slow for MANY items. It’s better to display
  // only some instead of crashing the browser.
  // defaults are 1000 portals, 400 links and 200 fields
  window.MAX_DRAWN_PORTALS = 5000;
  window.MAX_DRAWN_LINKS = 2000;
  window.MAX_DRAWN_FIELDS = 1000;
  window.USE_INCREASED_RENDER_LIMIT = true; // Used for other plugins
};

var setup =  window.plugin.renderLimitIncrease.setHigherLimits;

// PLUGIN END //////////////////////////////////////////////////////////

@@PLUGINEND@@
<commit_msg>render limits are obsolete with the new code - remove contents of plugin (file remains so users auto-updating get this 'empty' version)<commit_after>// ==UserScript==
// @id             iitc-plugin-render-limit-increase@jonatkins
// @name           IITC plugin: render limit increase
// @category       Obsolete
// @version        0.4.0.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] OBSOLETE PLUGIN
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @grant          none
// ==/UserScript==

@@PLUGINSTART@@

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.renderLimitIncrease = function() {};

window.plugin.renderLimitIncrease.setHigherLimits = function() {
};

var setup =  window.plugin.renderLimitIncrease.setHigherLimits;

// PLUGIN END //////////////////////////////////////////////////////////

@@PLUGINEND@@
<|endoftext|>


<commit_before>'use strict'

let YFFData = {
  organizations: []
}

function init () {
  const lookupOrganizationButton = document.getElementById('lookupOrganisasjonsButton')
  const bedriftsWrapper = document.getElementById('bedriftsinfoWrapper')
  const lookupField = document.getElementById('brregQuery')
  const lookupForm = document.getElementById('lookupOrganisasjonForm')
  const requiredFields = document.getElementById('submitDocumentForm').querySelectorAll('[required]')
  bedriftsWrapper.style.display = 'none'
  hideVelger('bedriftsVelger')
  hideVelger('lookupMessages')
  addListener(lookupForm, 'submit', lookupOrganization)
  addListener(lookupOrganizationButton, 'click', lookupOrganization)
  requiredFields.forEach(function (field) {
    addListener(field, 'keyup', validateDocumentForm)
  })

  setTimeout(function () {
    lookupField.focus()
  }, 500)

  validateDocumentForm()

  initPreview()
}

function validateDocumentForm () {
  const previewButton = document.getElementById('previewDocumentButton')
  const submitButton = document.getElementById('submitFormButton')
  const requiredFields = document.getElementById('submitDocumentForm').querySelectorAll('[required]')
  let requiredValues = []

  // disable buttons
  submitButton.disabled = true
  previewButton.disabled = true

  requiredFields.forEach(function (field) {
    if (field.value !== '') {
      requiredValues.push(true)
    }
  })

  if (requiredValues.length === requiredFields.length) {
    submitButton.disabled = false
    previewButton.disabled = false
  }
}

function hideVelger (velger) {
  const velgers = document.querySelectorAll('.' + velger)
  velgers.forEach(function (item) {
    item.style.display = 'none'
  })
}

function showVelger (velger) {
  const velgers = document.querySelectorAll('.' + velger)
  velgers.forEach(function (item) {
    item.style.display = ''
  })
}

//MDL Text Input Cleanup
function mdlCleanUp () {
  var mdlInputs = document.querySelectorAll('.mdl-js-textfield');
  for (var i = 0, l = mdlInputs.length; i < l; i++) {
    mdlInputs[i].MaterialTextfield.checkDirty();
  }
}

function spinnerOn () {
  const spinner = document.getElementById('searchIcon')
  const resultDiv = document.getElementById('lookupWrapper')
  resultDiv.innerHTML = ''
  spinner.innerText = 'hourglass_empty'
}

function spinnerOff () {
  const spinner = document.getElementById('searchIcon')
  spinner.innerText = 'search'
}

function setupOrganization (data) {
  const bedriftsNavn = document.getElementById('organisasjonsNavn')
  const bedriftsNummer = document.getElementById('organisasjonsNummer')
  const bedriftsAdresse = document.getElementById('organisasjonsAdresse')
  const bedriftsPostnummer = document.getElementById('organisasjonsPostnummer')
  const bedriftsPoststed = document.getElementById('organisasjonsPoststed')
  const bedriftsWrapper = document.getElementById('bedriftsinfoWrapper')
  // Updates fields
  bedriftsNavn.value = data.navn
  bedriftsNummer.value = data.orgnr
  bedriftsAdresse.value = data.forretningsadr
  bedriftsPostnummer.value = data.forradrpostnr
  bedriftsPoststed.value = data.forradrpoststed
  // Reveal info
  mdlCleanUp()
  bedriftsWrapper.style.display = ''
  hideVelger('bedriftsVelger')
  hideVelger('lookupMessages')
  addListener(document.getElementById('addContactPersonButton'), 'click', addContactPerson)
  addListener(document.getElementById('addNextOfKinButton'), 'click', addNextOfKin)
}

function addListener (element, type, func) {
  element.removeEventListener(type, func)
  element.addEventListener(type, func)
}

function createInput (options) {
  const id = uuidv4()
  const div = document.createElement('div')
  const input = document.createElement('input')
  const label = document.createElement('label')
  div.classList.add('mdl-textfield')
  div.classList.add('mdl-js-textfield')
  div.classList.add('mdl-textfield--floating-label')
  div.classList.add('width90')
  input.classList.add('mdl-textfield__input')
  label.classList.add('mdl-textfield__label')
  input.setAttribute('id', id)
  input.setAttribute('name', options.name)
  label.setAttribute('for', id)
  label.innerHTML = options.text
  div.appendChild(input)
  div.appendChild(label)
  return div
}

function addContactPerson (e) {
  e.preventDefault()
  const button = e.target
  const nameField = createInput({name: 'kontaktpersonNavn', text: 'Kontaktperson'})
  const phoneField = createInput({name: 'kontaktpersonTelefon', text: 'Telefon'})
  const departmentField = createInput({name: 'kontaktpersonAvdeling', text: 'Avdeling'})
  button.parentNode.insertBefore(nameField, button)
  button.parentNode.insertBefore(phoneField, button)
  button.parentNode.insertBefore(departmentField, button)
  componentHandler.upgradeElements(button.parentNode)
}

function addNextOfKin (e) {
  e.preventDefault()
  const button = e.target
  const nameField = createInput({name: 'parorendeNavn', text: 'Navn'})
  const phoneField = createInput({name: 'parorendeTelefon', text: 'Telefon'})
  button.parentNode.insertBefore(nameField, button)
  button.parentNode.insertBefore(phoneField, button)
  componentHandler.upgradeElements(button.parentNode)
}

function organizationSelected (e) {
  e.preventDefault()
  const selectedIndex = parseInt(e.target.dataset.myIndex, 10)
  const data = YFFData.organizations[selectedIndex]
  setupOrganization(data)
}

function createRadio (options) {
  const id = new Date().getMilliseconds()
  const label = document.createElement('label')
  const input = document.createElement('input')
  const span = document.createElement('span')
  label.classList.add('mdl-radio')
  label.classList.add('mdl-js-radio')
  label.classList.add('mdl-js-ripple-effect')
  label.classList.add('hoverGrey')
  input.classList.add('mdl-radio__button')
  span.classList.add('mdl-radio__label')
  input.setAttribute('id', id)
  input.setAttribute('data-my-index', options.index)
  input.setAttribute('name', options.name)
  input.setAttribute('type', 'radio')
  label.setAttribute('id', options.index)
  label.setAttribute('for', id)
  span.setAttribute('data-my-index', options.index)
  span.innerHTML = options.navn + ' - ' + options.forradrkommnavn
  label.appendChild(input)
  label.appendChild(span)
  return label
}

function buildOrganizationsSelector () {
  const div = document.getElementById('lookupWrapper')
  div.innerHTML = ''
  YFFData.organizations.forEach(function (item, index) {
    const radio = createRadio(Object.assign(item, {index: index, name: 'selectOrg'}))
    const br = document.createElement('br')
    div.appendChild(radio)
    div.appendChild(br)
    addListener(radio, 'click', organizationSelected)
  })
  showVelger('bedriftsVelger')
}

function lookupOrganization (e) {
  e.preventDefault()
  const queryField = document.getElementById('brregQuery')
  const messages = document.getElementById('lookupMessages')
  const query = queryField.value
  const url = `/yff/brreg`
  spinnerOn()
  messages.innerHTML = ''
  hideVelger('lookupMessages')
  hideVelger('bedriftsWrapper')
  hideVelger('bedriftsinfoWrapper')
  axios.post(url, {query: query})
    .then(function (result) {
      spinnerOff()
      YFFData.organizations = result.data
      if (result.data.length === 1) {
        setupOrganization(result.data[0])
      } else if (result.data.length === 0) {
        messages.innerHTML = 'Ingen bedrifter funnet. Vennligst forsøk med andre søkekriterier'
        showVelger('lookupMessages')
      } else {
        buildOrganizationsSelector()
      }
    }).catch(function (error) {
      console.error(error)
      spinnerOff()
    })
}

function ready (fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

ready(init)
<commit_msg>Hands? I've got'em<commit_after>'use strict'

let YFFData = {
  organizations: []
}

function init () {
  const lookupOrganizationButton = document.getElementById('lookupOrganisasjonsButton')
  const bedriftsWrapper = document.getElementById('bedriftsinfoWrapper')
  const lookupField = document.getElementById('brregQuery')
  const lookupForm = document.getElementById('lookupOrganisasjonForm')
  const requiredFields = document.getElementById('submitDocumentForm').querySelectorAll('[required]')
  bedriftsWrapper.style.display = 'none'
  hideVelger('bedriftsVelger')
  hideVelger('lookupMessages')
  addListener(lookupForm, 'submit', lookupOrganization)
  addListener(lookupOrganizationButton, 'click', lookupOrganization)
  requiredFields.forEach(function (field) {
    addListener(field, 'keyup', validateDocumentForm)
  })

  setTimeout(function () {
    lookupField.focus()
  }, 500)

  validateDocumentForm()

  initPreview()
}

function validateDocumentForm () {
  const previewButton = document.getElementById('previewDocumentButton')
  const submitButton = document.getElementById('submitFormButton')
  const requiredFields = document.getElementById('submitDocumentForm').querySelectorAll('[required]')
  let requiredValues = []

  // disable buttons
  submitButton.disabled = true
  previewButton.disabled = true

  requiredFields.forEach(function (field) {
    if (field.value !== '') {
      requiredValues.push(true)
    }
  })

  if (requiredValues.length === requiredFields.length) {
    submitButton.disabled = false
    previewButton.disabled = false
  }
}

function hideVelger (velger) {
  const velgers = document.querySelectorAll('.' + velger)
  velgers.forEach(function (item) {
    item.style.display = 'none'
  })
}

function showVelger (velger) {
  const velgers = document.querySelectorAll('.' + velger)
  velgers.forEach(function (item) {
    item.style.display = ''
  })
}

//MDL Text Input Cleanup
function mdlCleanUp () {
  var mdlInputs = document.querySelectorAll('.mdl-js-textfield');
  for (var i = 0, l = mdlInputs.length; i < l; i++) {
    mdlInputs[i].MaterialTextfield.checkDirty();
  }
}

function spinnerOn () {
  const spinner = document.getElementById('searchIcon')
  const resultDiv = document.getElementById('lookupWrapper')
  resultDiv.innerHTML = ''
  spinner.innerText = 'hourglass_empty'
}

function spinnerOff () {
  const spinner = document.getElementById('searchIcon')
  spinner.innerText = 'search'
}

function setupOrganization (data) {
  const bedriftsNavn = document.getElementById('organisasjonsNavn')
  const bedriftsNummer = document.getElementById('organisasjonsNummer')
  const bedriftsAdresse = document.getElementById('organisasjonsAdresse')
  const bedriftsPostnummer = document.getElementById('organisasjonsPostnummer')
  const bedriftsPoststed = document.getElementById('organisasjonsPoststed')
  const bedriftsWrapper = document.getElementById('bedriftsinfoWrapper')
  // Updates fields
  bedriftsNavn.value = data.navn
  bedriftsNummer.value = data.orgnr
  bedriftsAdresse.value = data.forretningsadr
  bedriftsPostnummer.value = data.forradrpostnr
  bedriftsPoststed.value = data.forradrpoststed
  // Reveal info
  mdlCleanUp()
  bedriftsWrapper.style.display = ''
  hideVelger('bedriftsVelger')
  hideVelger('lookupMessages')
  addListener(document.getElementById('addContactPersonButton'), 'click', addContactPerson)
  addListener(document.getElementById('addNextOfKinButton'), 'click', addNextOfKin)
}

function addListener (element, type, func) {
  element.removeEventListener(type, func)
  element.addEventListener(type, func)
}

function createInput (options) {
  const id = uuidv4()
  const div = document.createElement('div')
  const input = document.createElement('input')
  const label = document.createElement('label')
  div.classList.add('mdl-textfield')
  div.classList.add('mdl-js-textfield')
  div.classList.add('mdl-textfield--floating-label')
  div.classList.add('width90')
  input.classList.add('mdl-textfield__input')
  label.classList.add('mdl-textfield__label')
  input.setAttribute('id', id)
  input.setAttribute('name', options.name)
  label.setAttribute('for', id)
  label.innerHTML = options.text
  div.appendChild(input)
  div.appendChild(label)
  return div
}

function addContactPerson (e) {
  e.preventDefault()
  const button = e.target
  const nameField = createInput({name: 'kontaktpersonNavn', text: 'Kontaktperson'})
  const phoneField = createInput({name: 'kontaktpersonTelefon', text: 'Telefon'})
  const departmentField = createInput({name: 'kontaktpersonAvdeling', text: 'Avdeling'})
  button.parentNode.insertBefore(nameField, button)
  button.parentNode.insertBefore(phoneField, button)
  button.parentNode.insertBefore(departmentField, button)
  componentHandler.upgradeElements(button.parentNode)
}

function addNextOfKin (e) {
  e.preventDefault()
  const button = e.target
  const nameField = createInput({name: 'parorendeNavn', text: 'Navn'})
  const phoneField = createInput({name: 'parorendeTelefon', text: 'Telefon'})
  button.parentNode.insertBefore(nameField, button)
  button.parentNode.insertBefore(phoneField, button)
  componentHandler.upgradeElements(button.parentNode)
}

function organizationSelected (e) {
  e.preventDefault()
  const selectedIndex = parseInt(e.target.dataset.myIndex, 10)
  const data = YFFData.organizations[selectedIndex]
  setupOrganization(data)
}

function createRadio (options) {
  const id = new Date().getMilliseconds()
  const label = document.createElement('label')
  const input = document.createElement('input')
  const span = document.createElement('span')
  label.classList.add('mdl-radio')
  label.classList.add('mdl-js-radio')
  label.classList.add('mdl-js-ripple-effect')
  label.classList.add('hoverGrey')
  input.classList.add('mdl-radio__button')
  span.classList.add('mdl-radio__label')
  input.setAttribute('id', id)
  input.setAttribute('data-my-index', options.index)
  input.setAttribute('name', options.name)
  input.setAttribute('type', 'radio')
  label.setAttribute('id', options.index)
  label.setAttribute('for', id)
  span.setAttribute('data-my-index', options.index)
  span.innerHTML = options.navn + ' - ' + options.forradrkommnavn
  label.appendChild(input)
  label.appendChild(span)
  return label
}

function buildOrganizationsSelector () {
  const div = document.getElementById('lookupWrapper')
  div.innerHTML = ''
  YFFData.organizations.forEach(function (item, index) {
    const radio = createRadio(Object.assign(item, {index: index, name: 'selectOrg'}))
    const br = document.createElement('br')
    div.appendChild(radio)
    div.appendChild(br)
    addListener(radio, 'click', organizationSelected)
  })
  showVelger('bedriftsVelger')
}

function lookupOrganization (e) {
  e.preventDefault()
  const queryField = document.getElementById('brregQuery')
  const messages = document.getElementById('lookupMessages')
  const query = queryField.value
  const url = '/yff/brreg'
  spinnerOn()
  messages.innerHTML = ''
  hideVelger('lookupMessages')
  hideVelger('bedriftsWrapper')
  hideVelger('bedriftsinfoWrapper')
  axios.post(url, {query: query})
    .then(function (result) {
      spinnerOff()
      YFFData.organizations = result.data
      if (result.data.length === 1) {
        setupOrganization(result.data[0])
      } else if (result.data.length === 0) {
        messages.innerHTML = 'Ingen bedrifter funnet. Vennligst forsøk med andre søkekriterier'
        showVelger('lookupMessages')
      } else {
        buildOrganizationsSelector()
      }
    }).catch(function (error) {
      console.error(error)
      spinnerOff()
    })
}

function ready (fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

ready(init)
<|endoftext|>


<commit_before>const request = require('request');
var _ = require( 'underscore' );
var results = []
var survey_result = {}

if (!process.env.page_token) {
    console.log('Error: Specify page_token in environment');
    process.exit(1);
}

if (!process.env.verify_token) {
    console.log('Error: Specify verify_token in environment');
    process.exit(1);
}

var Botkit = require('./lib/Botkit.js');
var os = require('os');

var controller = Botkit.facebookbot({
    debug: false,
    access_token: process.env.page_token,
    verify_token: process.env.verify_token,
});

var bot = controller.spawn({
});

controller.setupWebserver(process.env.port || 3000, function(err, webserver) {
    controller.createWebhookEndpoints(webserver, bot, function() {
        console.log('ONLINE!');
    });
});

controller.hears(['hi','Hi'], 'message_received', function(bot, message) {
    console.log(message.user)
    bot.reply(message, `Hello`);
    // var found_result = _.findWhere(results, {id: message.user});
    // if (found_result == undefined){

    //         askSurvey(bot, message);
    // } else {
    //     bot.reply(message, `Hello, you have already done the survey`);
    //     redoSurvey(bot, message)
    // }
    // getProfile(message.user, function(err, profile) {
    //     console.log(message.user)
    // });

});

// POSTBACK HANLDER
controller.on('facebook_postback', function(bot, message) {
    if (message.payload == 'yes(start)') {
        bot.reply(message, `Excellent! Lets get started.`);
        survey_result = {}
        survey_result.id = message.user
        // getProfile(message.user, function(err, profile) {
        //     survey_result.user = `${profile.first_name} ${profile.last_name}`
        //     survey_result.gender = `${profile.gender}`
        //     survey_result.locale = `${profile.locale}`
        //     survey_result.timezone = `${profile.timezone}`
        // });
        askRelationship(bot, message)
    } else if (message.payload == 'I love it' || message.payload == 'I hate it' || message.payload == 'Guilty pleasure') {

            if (survey_result.relationship == null) {
                survey_result.relationship = message.payload
                askDetail(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'I make it myself' || message.payload == 'KFC is my go to' || message.payload == 'Any way is good' || message.payload == 'Fried food is gross' || message.payload == `I don't eat animals` || message.payload == `It's a secret` || message.payload == `reward` ||message.payload == `cures hangover`) {

            if (survey_result.detail == null) {
                survey_result.detail = message.payload
                askMood(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == '(•‿•)' || message.payload == '(•︵•)' || message.payload == '(•_•)') {

            if (survey_result.mood == null) {
                survey_result.mood = message.payload
                askPreference(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'Chicken Parmesan' || message.payload == 'Double Down' || message.payload == 'Fried Drumsticks' || message.payload == 'Chicken Nuggets' || message.payload == 'Veggies') {

            if (survey_result.preference == null) {
                survey_result.preference = message.payload
                askHungry(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'yes' || message.payload == 'no' ) {

            if (survey_result.hungry == null) {
                survey_result.hungry = message.payload
                endSurvey(bot, message)
            } else if (survey_result == {}){
            bot.reply(message, `You've already answered that question.`);
            }
    } else if (message.payload == 'no(survey)') {
        sayThanks(bot, message)
    } else if (message.payload == 'View results') {
        saveResults(bot, message)
        viewResults(bot, message)
    } else if (message.payload == 'Re-do survey') {
        bot.reply(message, `Excellent! Lets get started.`);
        deleteEntry(bot, message)
        survey_result = {}
        survey_result.id = message.user
        // getProfile(message.user, function(err, profile) {

        //     survey_result.user = `${profile.first_name} ${profile.last_name}`
        //     survey_result.gender = `${profile.gender}`
        //     survey_result.locale = `${profile.locale}`
        //     survey_result.timezone = `${profile.timezone}`

        // });
        askRelationship(bot, message)
    } else if (message.payload == `I'm done`) {
        saveResults(bot, message)
        sayThanks(bot, message)
    }
});
// check for user
deleteEntry = function(bot, message){
    var found_result = _.findWhere(results, {id: message.user});
    var result = results.filter(function (value) {return (value !== found_result);});
    results = result
}
// View Results
viewResults = function(bot, message) {
    var found_result = _.findWhere(results, {id: message.user});
    var text = JSON.stringify(found_result)
    bot.reply(message, `${text}`);
}
// QUESTIONS
askSurvey = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'Do you have a moment to answer some questions about fried chicken ?',
            'buttons':[
                {
                'type':'postback',
                'title':`Yes`,
                'payload':`yes(start)`
                },
                {
                'type':'postback',
                'title':`No`,
                'payload':`no(survey)`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });
}

askRelationship = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text':  'What would you say your relationship is with fried chicken ?',
            'buttons':[
                {
                'type':'postback',
                'title':'I love it',
                'payload':'I love it'
                },
                {
                'type':'postback',
                'title':'I hate it',
                'payload':'I hate it'
                },
                {
                'type':'postback',
                'title':'Guilty pleasure',
                'payload':'Guilty pleasure'
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });
}

askDetail = function(bot, message) {
    if (message.payload == 'I love it') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text': 'What is your favourite way to eat fried chicken ?',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'I make it myself',
                    'payload':'I make it myself'
                    },
                    {
                    'type':'postback',
                    'title':'KFC is my go to',
                    'payload':'KFC is my go to'
                    },
                    {
                    'type':'postback',
                    'title':'Any way is good',
                    'payload':'Any way is good'
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else if (message.payload == 'I hate it') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text': 'Not a fan ? tell me more.',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'Fried food is gross',
                    'payload':'Fried food is gross'
                    },
                    {
                    'type':'postback',
                    'title':`I don't eat animals`,
                    'payload':`I don't eat animals`
                    },
                    {
                    'type':'postback',
                    'title':`It's a secret`,
                    'payload':`It's a secret`
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else if (message.payload == 'Guilty pleasure') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text':  'Guilty pleasure you say, tell me more.',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'When Hungover',
                    'payload':'cures hangover'
                    },
                    {
                    'type':'postback',
                    'title':'Reward for myself',
                    'payload':'reward'
                    },
                    {
                    'type':'postback',
                    'title':`It's a secret`,
                    'payload':`It's a secret`
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else  {
        bot.reply(message, 'oops')
    }

}

askMood = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'What is your current mood ?',
            'buttons':[
                {
                'type':'postback',
                'title':`(•‿•)`,
                'payload':`(•‿•)`
                },
                {
                'type':'postback',
                'title':`(•︵•)`,
                'payload':`(•︵•)`
                },
                {
                'type':'postback',
                'title':`(•_•)`,
                'payload':`(•_•)`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}

askPreference = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload': {
                'template_type': 'generic',
                'elements': [
                    {
                        'title': 'Chicken Parmesan',
                        'image_url': 'http://fiber-international.com/wp-content/uploads/2015/04/800x600-chicken.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Chicken Parmesan'
                            }
                        ]
                    },
                    {
                        'title': 'Double Down',
                        'image_url': 'http://assets.bwbx.io/images/ieMg5BCeWkWU/v1/-1x-1.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Double Down'
                            }
                        ]
                    },
                    {
                        'title': 'Fried Drumsticks',
                        'image_url': 'https://i.ytimg.com/vi/G8hbFO-r2nQ/maxresdefault.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Fried Drumsticks'
                            }
                        ]
                    },
                    {
                        'title': 'Chicken Nuggets',
                        'image_url': 'http://www.urbanmommies.com/wp-content/uploads/McDonalds-Chicken-Nuggets.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Chicken Nuggets'
                            }
                        ]
                    },
                    {
                        'title': 'Veggies',
                        'image_url': 'http://www.stevensonfitness.com/wp-content/uploads/2014/10/veggies.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Veggies'
                            }
                        ]
                    }
                ]
            }
    };

    bot.reply(message, {
        attachment: attachment,
    });

    bot.reply(message, 'Which of these meals your you like to be eating right now ?');
}

askHungry = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'Have I made you hungry ?',
            'buttons':[
                {
                'type':'postback',
                'title':`yes`,
                'payload':`yes`
                },
                {
                'type':'postback',
                'title':`no`,
                'payload':`no`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}
// OTHER RESPONSES
sayThanks = function(bot, message) {
  bot.reply(message, 'OK! thanks for your time');
}
//saving
saveResults = function(bot, message) {
    results.push(survey_result)
    console.log(results)
}

endSurvey = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'OK! thanks for your time',
            'buttons':[
                {
                'type':'postback',
                'title':`View results`,
                'payload':`View results`
                },
                {
                'type':'postback',
                'title':`Re-do survey`,
                'payload':`Re-do survey`
                },
                {
                'type':'postback',
                'title':`I'm done`,
                'payload':`I'm done`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}

redoSurvey = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'How can I help ?',
            'buttons':[
                {
                'type':'postback',
                'title':`View results`,
                'payload':`View results`
                },
                {
                'type':'postback',
                'title':`Re-do survey`,
                'payload':`Re-do survey`
                },
                {
                'type':'postback',
                'title':`I'm done`,
                'payload':`I'm done`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}
// GET USER INFO !!!
// getProfile = function (id, cb) {

//     if (!cb) cb = Function.prototype

//     request({
//       method: 'GET',
//       uri: `https://graph.facebook.com/v2.6/${id}`,
//       qs: {
//         fields: 'first_name,last_name,profile_pic,gender,locale,timezone',
//         access_token: process.env.page_token
//       },
//       json: true
//     }, function(err, res, body) {
//       if (err) return cb(err)
//       if (body.error) return cb(body.error)

//       cb(null, body)
//     })
// }
<commit_msg>first name undefined for tester<commit_after>const request = require('request');
var _ = require( 'underscore' );
var results = []
var survey_result = {}

if (!process.env.page_token) {
    console.log('Error: Specify page_token in environment');
    process.exit(1);
}

if (!process.env.verify_token) {
    console.log('Error: Specify verify_token in environment');
    process.exit(1);
}

var Botkit = require('./lib/Botkit.js');
var os = require('os');

var controller = Botkit.facebookbot({
    debug: false,
    access_token: process.env.page_token,
    verify_token: process.env.verify_token,
});

var bot = controller.spawn({
});

controller.setupWebserver(process.env.port || 3000, function(err, webserver) {
    controller.createWebhookEndpoints(webserver, bot, function() {
        console.log('ONLINE!');
    });
});

controller.hears(['hi','Hi'], 'message_received', function(bot, message) {
    console.log(message.user)
    bot.reply(message, `Hello`);
    askSurvey(bot, message);
    // var found_result = _.findWhere(results, {id: message.user});
    // if (found_result == undefined){

    //
    // } else {
    //     bot.reply(message, `Hello, you have already done the survey`);
    //     redoSurvey(bot, message)
    // }
    // getProfile(message.user, function(err, profile) {
    //     console.log(message.user)
    // });

});

// POSTBACK HANLDER
controller.on('facebook_postback', function(bot, message) {
    if (message.payload == 'yes(start)') {
        bot.reply(message, `Excellent! Lets get started.`);
        survey_result = {}
        survey_result.id = message.user
        // getProfile(message.user, function(err, profile) {
        //     survey_result.user = `${profile.first_name} ${profile.last_name}`
        //     survey_result.gender = `${profile.gender}`
        //     survey_result.locale = `${profile.locale}`
        //     survey_result.timezone = `${profile.timezone}`
        // });
        askRelationship(bot, message)
    } else if (message.payload == 'I love it' || message.payload == 'I hate it' || message.payload == 'Guilty pleasure') {

            if (survey_result.relationship == null) {
                survey_result.relationship = message.payload
                askDetail(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'I make it myself' || message.payload == 'KFC is my go to' || message.payload == 'Any way is good' || message.payload == 'Fried food is gross' || message.payload == `I don't eat animals` || message.payload == `It's a secret` || message.payload == `reward` ||message.payload == `cures hangover`) {

            if (survey_result.detail == null) {
                survey_result.detail = message.payload
                askMood(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == '(•‿•)' || message.payload == '(•︵•)' || message.payload == '(•_•)') {

            if (survey_result.mood == null) {
                survey_result.mood = message.payload
                askPreference(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'Chicken Parmesan' || message.payload == 'Double Down' || message.payload == 'Fried Drumsticks' || message.payload == 'Chicken Nuggets' || message.payload == 'Veggies') {

            if (survey_result.preference == null) {
                survey_result.preference = message.payload
                askHungry(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'yes' || message.payload == 'no' ) {

            if (survey_result.hungry == null) {
                survey_result.hungry = message.payload
                endSurvey(bot, message)
            } else if (survey_result == {}){
            bot.reply(message, `You've already answered that question.`);
            }
    } else if (message.payload == 'no(survey)') {
        sayThanks(bot, message)
    } else if (message.payload == 'View results') {
        saveResults(bot, message)
        viewResults(bot, message)
    } else if (message.payload == 'Re-do survey') {
        bot.reply(message, `Excellent! Lets get started.`);
        deleteEntry(bot, message)
        survey_result = {}
        survey_result.id = message.user
        // getProfile(message.user, function(err, profile) {

        //     survey_result.user = `${profile.first_name} ${profile.last_name}`
        //     survey_result.gender = `${profile.gender}`
        //     survey_result.locale = `${profile.locale}`
        //     survey_result.timezone = `${profile.timezone}`

        // });
        askRelationship(bot, message)
    } else if (message.payload == `I'm done`) {
        saveResults(bot, message)
        sayThanks(bot, message)
    }
});
// check for user
deleteEntry = function(bot, message){
    var found_result = _.findWhere(results, {id: message.user});
    var result = results.filter(function (value) {return (value !== found_result);});
    results = result
}
// View Results
viewResults = function(bot, message) {
    var found_result = _.findWhere(results, {id: message.user});
    var text = JSON.stringify(found_result)
    bot.reply(message, `${text}`);
}
// QUESTIONS
askSurvey = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'Do you have a moment to answer some questions about fried chicken ?',
            'buttons':[
                {
                'type':'postback',
                'title':`Yes`,
                'payload':`yes(start)`
                },
                {
                'type':'postback',
                'title':`No`,
                'payload':`no(survey)`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });
}

askRelationship = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text':  'What would you say your relationship is with fried chicken ?',
            'buttons':[
                {
                'type':'postback',
                'title':'I love it',
                'payload':'I love it'
                },
                {
                'type':'postback',
                'title':'I hate it',
                'payload':'I hate it'
                },
                {
                'type':'postback',
                'title':'Guilty pleasure',
                'payload':'Guilty pleasure'
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });
}

askDetail = function(bot, message) {
    if (message.payload == 'I love it') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text': 'What is your favourite way to eat fried chicken ?',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'I make it myself',
                    'payload':'I make it myself'
                    },
                    {
                    'type':'postback',
                    'title':'KFC is my go to',
                    'payload':'KFC is my go to'
                    },
                    {
                    'type':'postback',
                    'title':'Any way is good',
                    'payload':'Any way is good'
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else if (message.payload == 'I hate it') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text': 'Not a fan ? tell me more.',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'Fried food is gross',
                    'payload':'Fried food is gross'
                    },
                    {
                    'type':'postback',
                    'title':`I don't eat animals`,
                    'payload':`I don't eat animals`
                    },
                    {
                    'type':'postback',
                    'title':`It's a secret`,
                    'payload':`It's a secret`
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else if (message.payload == 'Guilty pleasure') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text':  'Guilty pleasure you say, tell me more.',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'When Hungover',
                    'payload':'cures hangover'
                    },
                    {
                    'type':'postback',
                    'title':'Reward for myself',
                    'payload':'reward'
                    },
                    {
                    'type':'postback',
                    'title':`It's a secret`,
                    'payload':`It's a secret`
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else  {
        bot.reply(message, 'oops')
    }

}

askMood = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'What is your current mood ?',
            'buttons':[
                {
                'type':'postback',
                'title':`(•‿•)`,
                'payload':`(•‿•)`
                },
                {
                'type':'postback',
                'title':`(•︵•)`,
                'payload':`(•︵•)`
                },
                {
                'type':'postback',
                'title':`(•_•)`,
                'payload':`(•_•)`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}

askPreference = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload': {
                'template_type': 'generic',
                'elements': [
                    {
                        'title': 'Chicken Parmesan',
                        'image_url': 'http://fiber-international.com/wp-content/uploads/2015/04/800x600-chicken.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Chicken Parmesan'
                            }
                        ]
                    },
                    {
                        'title': 'Double Down',
                        'image_url': 'http://assets.bwbx.io/images/ieMg5BCeWkWU/v1/-1x-1.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Double Down'
                            }
                        ]
                    },
                    {
                        'title': 'Fried Drumsticks',
                        'image_url': 'https://i.ytimg.com/vi/G8hbFO-r2nQ/maxresdefault.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Fried Drumsticks'
                            }
                        ]
                    },
                    {
                        'title': 'Chicken Nuggets',
                        'image_url': 'http://www.urbanmommies.com/wp-content/uploads/McDonalds-Chicken-Nuggets.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Chicken Nuggets'
                            }
                        ]
                    },
                    {
                        'title': 'Veggies',
                        'image_url': 'http://www.stevensonfitness.com/wp-content/uploads/2014/10/veggies.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Veggies'
                            }
                        ]
                    }
                ]
            }
    };

    bot.reply(message, {
        attachment: attachment,
    });

    bot.reply(message, 'Which of these meals your you like to be eating right now ?');
}

askHungry = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'Have I made you hungry ?',
            'buttons':[
                {
                'type':'postback',
                'title':`yes`,
                'payload':`yes`
                },
                {
                'type':'postback',
                'title':`no`,
                'payload':`no`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}
// OTHER RESPONSES
sayThanks = function(bot, message) {
  bot.reply(message, 'OK! thanks for your time');
}
//saving
saveResults = function(bot, message) {
    results.push(survey_result)
    console.log(results)
}

endSurvey = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'OK! thanks for your time',
            'buttons':[
                {
                'type':'postback',
                'title':`View results`,
                'payload':`View results`
                },
                {
                'type':'postback',
                'title':`Re-do survey`,
                'payload':`Re-do survey`
                },
                {
                'type':'postback',
                'title':`I'm done`,
                'payload':`I'm done`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}

redoSurvey = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'How can I help ?',
            'buttons':[
                {
                'type':'postback',
                'title':`View results`,
                'payload':`View results`
                },
                {
                'type':'postback',
                'title':`Re-do survey`,
                'payload':`Re-do survey`
                },
                {
                'type':'postback',
                'title':`I'm done`,
                'payload':`I'm done`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}
// GET USER INFO !!!
// getProfile = function (id, cb) {

//     if (!cb) cb = Function.prototype

//     request({
//       method: 'GET',
//       uri: `https://graph.facebook.com/v2.6/${id}`,
//       qs: {
//         fields: 'first_name,last_name,profile_pic,gender,locale,timezone',
//         access_token: process.env.page_token
//       },
//       json: true
//     }, function(err, res, body) {
//       if (err) return cb(err)
//       if (body.error) return cb(body.error)

//       cb(null, body)
//     })
// }
<|endoftext|>


<commit_before>/*
 * Tangram
 * Copyright 2009 Baidu Inc. All rights reserved.
 *
 * path: baidu/dom/_styleFixer/textOverflow.js
 * author: allstar
 * version: 1.1.0
 * date: 2009/11/17
 */

///import baidu.dom._styleFixer;
///import baidu.browser.firefox;
///import baidu.browser.opera;

/**
 * 提供给setStyle与getStyle使用，在做textOverflow时会向element对象中添加,_baiduOverflow, _baiduHTML两个属性保存原始的innerHTML信息
 */
baidu.dom._styleFixer.textOverflow = (function () {
    var fontSizeCache = {};

    function pop(list) {
        var o = list.length;
        if (o > 0) {
            o = list[o - 1];
            list.length--;
        } else {
            o = null;
        }
        return o;
    }

    function setText(element, text) {
        element[baidu.browser.firefox ? "textContent" : "innerText"] = text;
    }

    function count(element, width, ellipsis) {
        /* 计算cache的名称 */
        var o = baidu.browser.ie ? element.currentStyle || element.style : getComputedStyle(element, null),
            fontWeight = o.fontWeight,
            cacheName =
                "font-family:" + o.fontFamily + ";font-size:" + o.fontSize
                + ";word-spacing:" + o.wordSpacing + ";font-weight:" + ((parseInt(fontWeight) || 0) == 401 ? 700 : fontWeight)
                + ";font-style:" + o.fontStyle + ";font-variant:" + o.fontVariant,
            cache = fontSizeCache[cacheName];

        if (!cache) {
            o = element.appendChild(document.createElement("div"));

            o.style.cssText = "float:left;" + cacheName;
            cache = fontSizeCache[cacheName] = [];

            /* 计算ASCII字符的宽度cache */
            for (var i=0; i < 256; i++) {
                i == 32 ? (o.innerHTML = " ") : setText(o, String.fromCharCode(i));
                cache[i] = o.offsetWidth;
            }

            /* 计算非ASCII字符的宽度、字符间距、省略号的宽度 */
            setText(o, "一");
            cache[256] = o.offsetWidth;
            setText(o, "一一");
            cache[257] = o.offsetWidth - cache[256] * 2;
            cache[258] = cache[".".charCodeAt(0)] * 3 + cache[257] * 3;

            element.removeChild(o);
        }

        for (
            /* wordWidth是每个字符或子节点计算之前的宽度序列 */
            var node = element.firstChild, charWidth = cache[256], wordSpacing = cache[257], ellipsisWidth = cache[258],
                wordWidth = [], ellipsis = ellipsis ? ellipsisWidth : 0;
            node;
            node = node.nextSibling
        ) {
            if (width < ellipsis) {
                element.removeChild(node);
            }
            else if (node.nodeType == 3) {
                for (var i = 0, text = node.nodeValue, length = text.length; i < length; i++) {
                    o = text.charCodeAt(i);
                    /* 计算增加字符后剩余的长度 */
                    wordWidth[wordWidth.length] = [width, node, i];
                    width -= (i ? wordSpacing : 0) + (o < 256 ? cache[o] : charWidth);
                    if (width < ellipsis) {
                        break;
                    }
                }
            }
            else {
                o = node.tagName;
                if (o == "IMG" || o == "TABLE") {
                    /* 特殊元素直接删除 */
                    o = node;
                    node = node.previousSibling;
                    element.removeChild(o);
                }
                else {
                    wordWidth[wordWidth.length] = [width, node];
                    width -= node.offsetWidth;
                }
            }
        }

        if (width < ellipsis) {
            /* 过滤直到能得到大于省略号宽度的位置 */
            while (o = pop(wordWidth)) {
                width = o[0];
                node = o[1];
                o = o[2];
                if (node.nodeType == 3) {
                    if (width >= ellipsisWidth) {
                        node.nodeValue = node.nodeValue.substring(0, o) + "...";
                        return true;
                    }
                    else if (!o) {
                        element.removeChild(node);
                    }
                }
                else if (count(node, width, true)) {
                    return true;
                }
                else {
                    element.removeChild(node);
                }
            }

            /* 能显示的宽度小于省略号的宽度，直接不显示 */
            element.innerHTML = "";
        }
    }

    return {
		get: function (element, style) {
            var browser = baidu.browser;
			return (browser.opera ? style.OTextOverflow : browser.firefox ? element._baiduOverflow: style.textOverflow) || "clip";
		},

		set: function (element, value) {
            var browser = baidu.browser;
			if (element.tagName == "TD" || element.tagName == "TH" || browser.firefox) {
				element._baiduHTML && (element.innerHTML = element._baiduHTML);

				if (value == "ellipsis") {
					element._baiduHTML = element.innerHTML;
					var o = document.createElement("div"), width = element.appendChild(o).offsetWidth;
					element.removeChild(o);
					count(element, width);
				}
				else {
					element._baiduHTML = "";
				}
			}

			o = element.style;
			browser.opera ? (o.OTextOverflow = value) : browser.firefox ? (element._baiduOverflow = value) : (o.textOverflow = value);
		}
    };
})();<commit_msg>将代码中的汉字还成utf8编码<commit_after>/*
 * Tangram
 * Copyright 2009 Baidu Inc. All rights reserved.
 *
 * path: baidu/dom/_styleFixer/textOverflow.js
 * author: allstar
 * version: 1.1.0
 * date: 2009/11/17
 */

///import baidu.dom._styleFixer;
///import baidu.browser.firefox;
///import baidu.browser.opera;

/**
 * 提供给setStyle与getStyle使用，在做textOverflow时会向element对象中添加,_baiduOverflow, _baiduHTML两个属性保存原始的innerHTML信息
 */
baidu.dom._styleFixer.textOverflow = (function () {
    var fontSizeCache = {};

    function pop(list) {
        var o = list.length;
        if (o > 0) {
            o = list[o - 1];
            list.length--;
        } else {
            o = null;
        }
        return o;
    }

    function setText(element, text) {
        element[baidu.browser.firefox ? "textContent" : "innerText"] = text;
    }

    function count(element, width, ellipsis) {
        /* 计算cache的名称 */
        var o = baidu.browser.ie ? element.currentStyle || element.style : getComputedStyle(element, null),
            fontWeight = o.fontWeight,
            cacheName =
                "font-family:" + o.fontFamily + ";font-size:" + o.fontSize
                + ";word-spacing:" + o.wordSpacing + ";font-weight:" + ((parseInt(fontWeight) || 0) == 401 ? 700 : fontWeight)
                + ";font-style:" + o.fontStyle + ";font-variant:" + o.fontVariant,
            cache = fontSizeCache[cacheName];

        if (!cache) {
            o = element.appendChild(document.createElement("div"));

            o.style.cssText = "float:left;" + cacheName;
            cache = fontSizeCache[cacheName] = [];

            /* 计算ASCII字符的宽度cache */
            for (var i=0; i < 256; i++) {
                i == 32 ? (o.innerHTML = " ") : setText(o, String.fromCharCode(i));
                cache[i] = o.offsetWidth;
            }

            /* 计算非ASCII字符的宽度、字符间距、省略号的宽度,\u4e00是汉字一的编码*/
            setText(o, "\u4e00");
            cache[256] = o.offsetWidth;
            setText(o, "\u4e00\u4e00");
            cache[257] = o.offsetWidth - cache[256] * 2;
            cache[258] = cache[".".charCodeAt(0)] * 3 + cache[257] * 3;

            element.removeChild(o);
        }

        for (
            /* wordWidth是每个字符或子节点计算之前的宽度序列 */
            var node = element.firstChild, charWidth = cache[256], wordSpacing = cache[257], ellipsisWidth = cache[258],
                wordWidth = [], ellipsis = ellipsis ? ellipsisWidth : 0;
            node;
            node = node.nextSibling
        ) {
            if (width < ellipsis) {
                element.removeChild(node);
            }
            else if (node.nodeType == 3) {
                for (var i = 0, text = node.nodeValue, length = text.length; i < length; i++) {
                    o = text.charCodeAt(i);
                    /* 计算增加字符后剩余的长度 */
                    wordWidth[wordWidth.length] = [width, node, i];
                    width -= (i ? wordSpacing : 0) + (o < 256 ? cache[o] : charWidth);
                    if (width < ellipsis) {
                        break;
                    }
                }
            }
            else {
                o = node.tagName;
                if (o == "IMG" || o == "TABLE") {
                    /* 特殊元素直接删除 */
                    o = node;
                    node = node.previousSibling;
                    element.removeChild(o);
                }
                else {
                    wordWidth[wordWidth.length] = [width, node];
                    width -= node.offsetWidth;
                }
            }
        }

        if (width < ellipsis) {
            /* 过滤直到能得到大于省略号宽度的位置 */
            while (o = pop(wordWidth)) {
                width = o[0];
                node = o[1];
                o = o[2];
                if (node.nodeType == 3) {
                    if (width >= ellipsisWidth) {
                        node.nodeValue = node.nodeValue.substring(0, o) + "...";
                        return true;
                    }
                    else if (!o) {
                        element.removeChild(node);
                    }
                }
                else if (count(node, width, true)) {
                    return true;
                }
                else {
                    element.removeChild(node);
                }
            }

            /* 能显示的宽度小于省略号的宽度，直接不显示 */
            element.innerHTML = "";
        }
    }

    return {
		get: function (element, style) {
            var browser = baidu.browser;
			return (browser.opera ? style.OTextOverflow : browser.firefox ? element._baiduOverflow: style.textOverflow) || "clip";
		},

		set: function (element, value) {
            var browser = baidu.browser;
			if (element.tagName == "TD" || element.tagName == "TH" || browser.firefox) {
				element._baiduHTML && (element.innerHTML = element._baiduHTML);

				if (value == "ellipsis") {
					element._baiduHTML = element.innerHTML;
					var o = document.createElement("div"), width = element.appendChild(o).offsetWidth;
					element.removeChild(o);
					count(element, width);
				}
				else {
					element._baiduHTML = "";
				}
			}

			o = element.style;
			browser.opera ? (o.OTextOverflow = value) : browser.firefox ? (element._baiduOverflow = value) : (o.textOverflow = value);
		}
    };
})();<|endoftext|>


<commit_before>module.exports.usage = function(req, res, next) {
  res.send(util.usage())
  next()
}

module.exports.findById = function(req, res, next) {
  req.collection.findById(req.params.id, function(e, result){
    res.send(result)

    req.db.close()
    next()
  })
}

module.exports.getCollections = function(req, res, next) {
  req.db.collectionNames(function(err, items) {
    res.send(util.pageResult(items, req.query.page, req.query.per_page))
    req.db.close()
    next()
  })
}

module.exports.getDocs = function(req, res, next) {
  var start = util.getStart(req.query.page, req.query.per_page)
  var max =  parseInt(req.query.per_page)
  var sort = (req.query.orderby) ? req.query.orderby : '_id'
  var order = (req.query.desc) ? -1 : 1
  var options = {
    skip: start,
    limit: max,
    sort: [[sort, order]]
  }

  req.collection.find(req.body, options).toArray(function(e, results){
    res.send(results)
    req.db.close()
    next()
  })
}

module.exports.getPlaces = function(req, res, next) {
  var start = util.getStart(req.query.page, req.query.per_page)
  var max =  parseInt(req.query.per_page)
  var sort = (req.query.orderby) ? req.query.orderby : '_id'
  var order = (req.query.desc) ? -1 : 1
  var options = {
    skip: start,
    limit: max,
    sort: [[sort, order]]
  }

  req.collection.find({$and:[req.body, {"loc": {"$exists": true}}]}, options).toArray(function(e, results){
    res.send(results)
    req.db.close()
    next()
  })
}

module.exports.getNext = function(req, res, next) {
  var size = 1
  if (req.query.per_page) {
    size = parseInt(req.query.per_page)
  }

  var sess = req.session
  if (!sess.previousQuery ||
    JSON.stringify(sess.previousQuery) != JSON.stringify(req.body)) {
    sess.previousQuery = req.body
    sess.skipToken = 0
  }

  var sort = (req.query.orderby) ? req.query.orderby : '_id'
  var order = (req.query.desc) ? -1 : 1
  var options = {
    skip: sess.skipToken,
    limit: size,
    sort: [[sort, order]]
  }

  req.collection.find(req.body, options).toArray(function(e, results) {
    res.send(results)
    req.db.close()
    next()
  })

  sess.skipToken += size
}

module.exports.reset = function(req, res, next) {
  var sess = req.session
  sess.skipToken = 0
  res.send((sess.skipToken === 0)?{msg:'success'}:{msg:'error'})
  next()
}

module.exports.groupcount = function(req, res, next) {
  var map = function() {
    emit(this[group], 1)
  }

  var reduce = function(key, values){
    return Array.sum(values)
  }

  util.aggInternal(req, res, next, map, reduce, req.query.prop, req.query.groupby)
}

module.exports.count = function(req, res, next) {
  var count = req.collection.count(req)
  res.send(count)
  req.db.close()
  next()
}

module.exports.sum = function(req, res, next) {
  var map = function() {
    emit(this[group], this[property])
  }

  var reduce = function(key, values) {
    return Array.sum(values)
  }

  util.aggInternal(req, res, next, map, reduce, req.query.prop, req.query.groupby)
}

module.exports.avg = function(req, res, next) {
  var map = function() {
    emit(this[group], this[property])
  }

  var reduce = function(key, values) {
    return values.length != 0 ? Array.sum(values) / values.length : 0
  }

  util.aggInternal(req, res, next, map, reduce, req.query.prop, req.query.groupby)
}

module.exports.max = function(req, res, next) {
  var map = function(){
    var content = {value: this[property], _id: this._id}
    emit(this[group], content)
  }

  var reduce = function(key, values){
    var result = values[0]
    for (var i = 1; i < values.length; i++) {
      if (values[i].value > result.value) {
        result = values[i];
      }
    }
    return result
  }

  util.aggInternal(req, res, next, map, reduce, req.query.prop, req.query.groupby)
}

module.exports.min = function(req, res, next) {
  var map = function(){
    var content = {value: this[property], _id: this._id}
    emit(this[group], content)
  }

  var reduce = function(key, values){
    var result = values[0]
    for (var i = 1; i < values.length; i++) {
      if (values[i].value < result.value) {
        result = values[i];
      }
    }
    return result
  }

  util.aggInternal(req, res, next, map, reduce, req.query.prop, req.query.groupby)
}
<commit_msg>update count logic<commit_after>module.exports.usage = function(req, res, next) {
  res.send(util.usage())
  next()
}

module.exports.findById = function(req, res, next) {
  req.collection.findById(req.params.id, function(e, result){
    res.send(result)

    req.db.close()
    next()
  })
}

module.exports.getCollections = function(req, res, next) {
  req.db.collectionNames(function(err, items) {
    res.send(util.pageResult(items, req.query.page, req.query.per_page))
    req.db.close()
    next()
  })
}

module.exports.getDocs = function(req, res, next) {
  var start = util.getStart(req.query.page, req.query.per_page)
  var max =  parseInt(req.query.per_page)
  var sort = (req.query.orderby) ? req.query.orderby : '_id'
  var order = (req.query.desc) ? -1 : 1
  var options = {
    skip: start,
    limit: max,
    sort: [[sort, order]]
  }

  req.collection.find(req.body, options).toArray(function(e, results){
    res.send(results)
    req.db.close()
    next()
  })
}

module.exports.getPlaces = function(req, res, next) {
  var start = util.getStart(req.query.page, req.query.per_page)
  var max =  parseInt(req.query.per_page)
  var sort = (req.query.orderby) ? req.query.orderby : '_id'
  var order = (req.query.desc) ? -1 : 1
  var options = {
    skip: start,
    limit: max,
    sort: [[sort, order]]
  }

  req.collection.find({$and:[req.body, {"loc": {"$exists": true}}]}, options).toArray(function(e, results){
    res.send(results)
    req.db.close()
    next()
  })
}

module.exports.getNext = function(req, res, next) {
  var size = 1
  if (req.query.per_page) {
    size = parseInt(req.query.per_page)
  }

  var sess = req.session
  if (!sess.previousQuery ||
    JSON.stringify(sess.previousQuery) != JSON.stringify(req.body)) {
    sess.previousQuery = req.body
    sess.skipToken = 0
  }

  var sort = (req.query.orderby) ? req.query.orderby : '_id'
  var order = (req.query.desc) ? -1 : 1
  var options = {
    skip: sess.skipToken,
    limit: size,
    sort: [[sort, order]]
  }

  req.collection.find(req.body, options).toArray(function(e, results) {
    res.send(results)
    req.db.close()
    next()
  })

  sess.skipToken += size
}

module.exports.reset = function(req, res, next) {
  var sess = req.session
  sess.skipToken = 0
  res.send((sess.skipToken === 0)?{msg:'success'}:{msg:'error'})
  next()
}

module.exports.groupcount = function(req, res, next) {
  var map = function() {
    emit(this[group], 1)
  }

  var reduce = function(key, values){
    return Array.sum(values)
  }

  util.aggInternal(req, res, next, map, reduce, req.query.prop, req.query.groupby)
}

module.exports.count = function(req, res, next) {
  req.collection.count(req.body, function(e, count) {
    if (!!e) {
      console.error(e)
      res.send({msg:'error', details: e})
      req.db.close()
    }
    else {
      res.send(count)
      req.db.close()
      next()
    }
  })
}

module.exports.sum = function(req, res, next) {
  var map = function() {
    emit(this[group], this[property])
  }

  var reduce = function(key, values) {
    return Array.sum(values)
  }

  util.aggInternal(req, res, next, map, reduce, req.query.prop, req.query.groupby)
}

module.exports.avg = function(req, res, next) {
  var map = function() {
    emit(this[group], this[property])
  }

  var reduce = function(key, values) {
    return values.length != 0 ? Array.sum(values) / values.length : 0
  }

  util.aggInternal(req, res, next, map, reduce, req.query.prop, req.query.groupby)
}

module.exports.max = function(req, res, next) {
  var map = function(){
    var content = {value: this[property], _id: this._id}
    emit(this[group], content)
  }

  var reduce = function(key, values){
    var result = values[0]
    for (var i = 1; i < values.length; i++) {
      if (values[i].value > result.value) {
        result = values[i];
      }
    }
    return result
  }

  util.aggInternal(req, res, next, map, reduce, req.query.prop, req.query.groupby)
}

module.exports.min = function(req, res, next) {
  var map = function(){
    var content = {value: this[property], _id: this._id}
    emit(this[group], content)
  }

  var reduce = function(key, values){
    var result = values[0]
    for (var i = 1; i < values.length; i++) {
      if (values[i].value < result.value) {
        result = values[i];
      }
    }
    return result
  }

  util.aggInternal(req, res, next, map, reduce, req.query.prop, req.query.groupby)
}
<|endoftext|>


<commit_before>goog.provide('jchemhub.controller.plugins.SymbolSelect');
goog.require('goog.debug.Logger');

/**
 * @constructor
 * @extends{jchemhubn.controller.Plugin}s
 */
jchemhub.controller.plugins.SymbolSelect = function() {
	jchemhub.controller.Plugin.call(this);

}
goog.inherits(jchemhub.controller.plugins.SymbolSelect,
		jchemhub.controller.Plugin);

/**
 * Command implemented by this plugin.
 */
jchemhub.controller.plugins.SymbolSelect.COMMAND = 'selectSymbol';

/** @inheritDoc */
jchemhub.controller.plugins.SymbolSelect.prototype.isSupportedCommand = function(
		command) {
	return command == jchemhub.controller.plugins.SymbolSelect.COMMAND;
};

/** @inheritDoc */
jchemhub.controller.plugins.SymbolSelect.prototype.getTrogClassId = goog.functions
		.constant(jchemhub.controller.plugins.SymbolSelect.COMMAND);

/**
 * sets atom symbol.
 *
 * @param {string}
 *            command Command to execute.
 * @return {Object|undefined} The result of the command.
 */
jchemhub.controller.plugins.SymbolSelect.prototype.execCommandInternal = function(
		command, var_args) {
	this.symbol = arguments[1];
};

/**
 * The logger for this class.
 *
 * @type {goog.debug.Logger}
 * @protected
 */
jchemhub.controller.plugins.SymbolSelect.prototype.logger = goog.debug.Logger
		.getLogger('jchemhub.controller.plugins.SymbolSelect');

jchemhub.controller.plugins.SymbolSelect.prototype.handleAtomMouseDown = function(
		e) {
	if (this.symbol) {
		var new_atom = new jchemhub.model.Atom(this.symbol, e.atom.x, e.atom.y)
		goog.array.forEach(e.atom.bonds.getValues(), function(bond){
			var new_bond = jchemhub.model.Bond.clone(bond);
			new_bond.molecule = undefined;
			e.atom==new_bond.source ? new_bond.source = new_atom : new_bond.target = new_atom;
			e.atom.molecule.addBond(new_bond);
		});
		var molecule = e.atom.molecule
		molecule.removeAtom(e.atom);
		molecule.addAtom(new_atom);
		this.editorObject.setModel(this.editorObject.getModel());
	}
};<commit_msg>fix atom coord reference<commit_after>goog.provide('jchemhub.controller.plugins.SymbolSelect');
goog.require('goog.debug.Logger');

/**
 * @constructor
 * @extends{jchemhubn.controller.Plugin}s
 */
jchemhub.controller.plugins.SymbolSelect = function() {
	jchemhub.controller.Plugin.call(this);

}
goog.inherits(jchemhub.controller.plugins.SymbolSelect,
		jchemhub.controller.Plugin);

/**
 * Command implemented by this plugin.
 */
jchemhub.controller.plugins.SymbolSelect.COMMAND = 'selectSymbol';

/** @inheritDoc */
jchemhub.controller.plugins.SymbolSelect.prototype.isSupportedCommand = function(
		command) {
	return command == jchemhub.controller.plugins.SymbolSelect.COMMAND;
};

/** @inheritDoc */
jchemhub.controller.plugins.SymbolSelect.prototype.getTrogClassId = goog.functions
		.constant(jchemhub.controller.plugins.SymbolSelect.COMMAND);

/**
 * sets atom symbol.
 *
 * @param {string}
 *            command Command to execute.
 * @return {Object|undefined} The result of the command.
 */
jchemhub.controller.plugins.SymbolSelect.prototype.execCommandInternal = function(
		command, var_args) {
	this.symbol = arguments[1];
};

/**
 * The logger for this class.
 *
 * @type {goog.debug.Logger}
 * @protected
 */
jchemhub.controller.plugins.SymbolSelect.prototype.logger = goog.debug.Logger
		.getLogger('jchemhub.controller.plugins.SymbolSelect');

jchemhub.controller.plugins.SymbolSelect.prototype.handleAtomMouseDown = function(
		e) {
	if (this.symbol!=e.atom.symbol) {
		var new_atom = new jchemhub.model.Atom(this.symbol, e.atom.coord.x, e.atom.coord.y)
		goog.array.forEach(e.atom.bonds.getValues(), function(bond){
			var new_bond = bond.clone();
			new_bond.molecule = undefined;
			e.atom==new_bond.source ? new_bond.source = new_atom : new_bond.target = new_atom;
			e.atom.molecule.addBond(new_bond);
		});
		var molecule = e.atom.molecule
		molecule.removeAtom(e.atom);
		molecule.addAtom(new_atom);
		this.editorObject.setModel(this.editorObject.getModel());
	}
};<|endoftext|>


<commit_before>define([
  'views/editor_collection_base',
  'underscore',
  'jquidrag',
  'text!templates/groups.tpl',
  'views/group_row',
  'views/group_editor',
  'models/group',
  'models/game',
  'vent',
],
function(
  EditorCollectionView,
  _,
  jQueryUiDraggable,
  Template,
  GroupRowView,
  GroupEditorView,
  Group,
  Game,
  vent
)
{
  return EditorCollectionView.extend(
  {
    template: _.template(Template),

    itemView: GroupRowView,
    itemViewContainer: '.groups',

    className: 'groups-editor',

    events:
    {
      "click .new": "onClickNew"
    },

    onClickNew: function()
    {
      var self = this;

      var game = self.model;
      var group  = new Group({game_id:game.id});
      var group_editor = new GroupEditorView({model:group});

      group_editor.on("group:add", function(group)
      {
        self.collection.add(group);
      });

      vent.trigger("application:popup:show", group_editor, "Create Group");
    },

    onRender: function()
    {
      var sort_options = {
        items: '.draggable-game-group',
        handle: '.tab-drag-handle',
        stop: function( event, ui ) { vent.trigger("grouprow:released", ui.item, ui.item.index()); }
      };

      this.$el.find('.list-group.groups').sortable(sort_options);
    }
  });
});

<commit_msg>Revert "maintain group draggability (why?)"<commit_after>define([
  'views/editor_collection_base',
  'underscore',
  'jquidrag',
  'text!templates/groups.tpl',
  'views/group_row',
  'views/group_editor',
  'models/group',
  'models/game',
  'vent',
],
function(
  EditorCollectionView,
  _,
  jQueryUiDraggable,
  Template,
  GroupRowView,
  GroupEditorView,
  Group,
  Game,
  vent
)
{
  return EditorCollectionView.extend(
  {
    template: _.template(Template),

    itemView: GroupRowView,
    itemViewContainer: '.groups',

    className: 'groups-editor',

    events:
    {
      "click .new": "onClickNew"
    },

    onClickNew: function()
    {
      var self = this;

      var game = self.model;
      var group  = new Group({game_id:game.id});
      var group_editor = new GroupEditorView({model:group});

      group_editor.on("group:add", function(group)
      {
        self.collection.add(group);
      });

      vent.trigger("application:popup:show", group_editor, "Create Group");
    },

    onRender: function()
    {
      var sort_options = {
        items: '.draggable-game-group',
        handle: '.group-drag-handle',
        stop: function( event, ui ) { vent.trigger("grouprow:released", ui.item, ui.item.index()); }
      };

      this.$el.find('.list-group.groups').sortable(sort_options);
    }
  });
});

<|endoftext|>


<commit_before>module.exports = ('./RinnaBridge');<commit_msg>Fix exports<commit_after>module.exports = require('./RinnaBridge');<|endoftext|>


<commit_before>(function() {
  var module = angular.module('loom_layer_info_directive', []);

  module.directive('loomLayerInfo',
      function($translate, serverService) {
        return {
          templateUrl: 'layers/partials/layerinfo.tpl.html',
          link: function(scope) {
            var resetVariables = function() {
              scope.layer = null;
              scope.name = null;
              scope.title = null;
              scope.workspace = null;
              scope.featureType = null;
              scope.abstract = null;
              scope.srs = null;
              scope.serverName = null;
              scope.datastoreType = null;
              scope.keywords = null;
              scope.repoName = null;
              scope.branchName = null;
            };
            resetVariables();
            scope.$on('getLayerInfo', function(evt, layer) {
              resetVariables();
              scope.layer = layer;
              var metadata = scope.layer.get('metadata');
              if (goog.isDefAndNotNull(metadata.name)) {
                var split = metadata.name.split(':');
                scope.name = split[split.length - 1];
              }
              if (goog.isDefAndNotNull(metadata.title)) {
                scope.title = metadata.title;
              }
              if (goog.isDefAndNotNull(metadata.workspace)) {
                scope.workspace = metadata.workspace;
              }
              if (goog.isDefAndNotNull(metadata.nativeName)) {
                scope.featureType = metadata.nativeName;
              }
              if (goog.isDefAndNotNull(metadata.abstract)) {
                scope.abstract = metadata.abstract;
              }
              if (goog.isDefAndNotNull(metadata.projection)) {
                scope.srs = metadata.projection;
              }
              if (goog.isDefAndNotNull(metadata.dataStoreType)) {
                scope.datastoreType = metadata.dataStoreType;
              }
              if (goog.isDefAndNotNull(metadata.keywords)) {
                scope.keywords = metadata.keywords.string.toString();
              }
              if (metadata.isGeoGit) {
                scope.branchName = metadata.branchName;
                scope.repoName = metadata.repoName;
              }
              var server = serverService.getServerById(scope.layer.get('metadata').serverId);
              scope.serverName = server.name;
              element.closest('.modal').modal('toggle');
            });

          }
        };
      });
}());
<commit_msg>Fixed a bug that prevented the layer info dialog from opening.<commit_after>(function() {
  var module = angular.module('loom_layer_info_directive', []);

  module.directive('loomLayerInfo',
      function($translate, serverService) {
        return {
          templateUrl: 'layers/partials/layerinfo.tpl.html',
          link: function(scope, element) {
            var resetVariables = function() {
              scope.layer = null;
              scope.name = null;
              scope.title = null;
              scope.workspace = null;
              scope.featureType = null;
              scope.abstract = null;
              scope.srs = null;
              scope.serverName = null;
              scope.datastoreType = null;
              scope.keywords = null;
              scope.repoName = null;
              scope.branchName = null;
            };
            resetVariables();
            scope.$on('getLayerInfo', function(evt, layer) {
              resetVariables();
              scope.layer = layer;
              var metadata = scope.layer.get('metadata');
              if (goog.isDefAndNotNull(metadata.name)) {
                var split = metadata.name.split(':');
                scope.name = split[split.length - 1];
              }
              if (goog.isDefAndNotNull(metadata.title)) {
                scope.title = metadata.title;
              }
              if (goog.isDefAndNotNull(metadata.workspace)) {
                scope.workspace = metadata.workspace;
              }
              if (goog.isDefAndNotNull(metadata.nativeName)) {
                scope.featureType = metadata.nativeName;
              }
              if (goog.isDefAndNotNull(metadata.abstract)) {
                scope.abstract = metadata.abstract;
              }
              if (goog.isDefAndNotNull(metadata.projection)) {
                scope.srs = metadata.projection;
              }
              if (goog.isDefAndNotNull(metadata.dataStoreType)) {
                scope.datastoreType = metadata.dataStoreType;
              }
              if (goog.isDefAndNotNull(metadata.keywords)) {
                scope.keywords = metadata.keywords.string.toString();
              }
              if (metadata.isGeoGit) {
                scope.branchName = metadata.branchName;
                scope.repoName = metadata.repoName;
              }
              var server = serverService.getServerById(scope.layer.get('metadata').serverId);
              scope.serverName = server.name;
              element.closest('.modal').modal('toggle');
            });

          }
        };
      });
}());
<|endoftext|>