<commit_before>/*
//1 get user profile
//2 get rit of beebop error
//3 click more buttons
//4 write json for hypo
*/

'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >8 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

speak: {
          receive: (bot, message) => {

              const upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  /*  CREATE EXTRA JSON FILE FOR HYPO AND INCLUDE IT */
                  if (!_.has(scriptRules, upperText)) {
                      return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)').then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters Hypotheek':
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'woningType')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja, dat wil ik wel':
            return bot.say(`👍 Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, dat hoeft niet':
              receive: () => 'bye'
              break;
          default:
            receive => 'processing'
            break;
      }
    }
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const emailer=message.text;
          return bot.setProp('emailer', emailer)
              .then(()  => bot.say(`Ok - ✉  dan hou ik je via ${emailer} op de hoogte.`))
              .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekStarter: {
    receive: () => 'askName'
},
hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

woningType: {
  receive: (bot, message) => {
    switch(message.text) {
        case '🏬 Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case '🏠 Huis':
          return bot.say(`Leuk`)
          .then(() => 'vervolgVragen')
          break;
    case '📭 Vakantiewoning':
          return bot.say(`Gezellig`)
          .then(() => 'vervolgVragen')
          break;
      default:
        receive => 'processing'
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say('Hoe heet je eigelijk? 😋'),
          receive: (bot, message) => {
              const Name = message.text.trim().toUpperCase();
              return bot.setProp('Name', Name)
                  .then(() => bot.say('Hoi ${Name}. 📋 Ik heb nog wat vragen voor je om verder te kunnen.'))
                  .then(() => 'processing')
            }
},

lastCheck: {
    prompt: (bot) => bot.say(' Is er nog iets waar ik  je bij kan helpen?  🔶  %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ik zoek meer informatie':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

meerInfo: {
  prompt: (bot) => bot.say('bestand'),
   receive: () => 'processing'
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
    receive: ()  => 'finish'
},

error: {
    prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
    receive: () => 'processing'
},

finish: {
receive: () => 'finish'
}
});
<commit_msg>ofd<commit_after>/*
//1 get user profile
//2 get rit of beebop error
//3 click more buttons
//4 write json for hypo
*/

'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');

var myDay = new Date();
var groet = '';

/* hour is before noon */
if ( myDay.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDay.getHours() >=8 && myDay.gethours()<=12 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

speak: {
          receive: (bot, message) => {

              const upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  /*  CREATE EXTRA JSON FILE FOR HYPO AND INCLUDE IT */
                  if (!_.has(scriptRules, upperText)) {
                      return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)').then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters Hypotheek':
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'woningType')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja, dat wil ik wel':
            return bot.say(`👍 Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, dat hoeft niet':
              receive: () => 'bye'
              break;
          default:
            receive => 'processing'
            break;
      }
    }
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const emailer=message.text;
          return bot.setProp('emailer', emailer)
              .then(()  => bot.say(`Ok - ✉  dan hou ik je via ${emailer} op de hoogte.`))
              .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekStarter: {
    receive: () => 'askName'
},
hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

woningType: {
  receive: (bot, message) => {
    switch(message.text) {
        case '🏬 Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case '🏠 Huis':
          return bot.say(`Leuk`)
          .then(() => 'vervolgVragen')
          break;
    case '📭 Vakantiewoning':
          return bot.say(`Gezellig`)
          .then(() => 'vervolgVragen')
          break;
      default:
        receive => 'processing'
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say('Hoe heet je eigelijk? 😋'),
          receive: (bot, message) => {
              const Name = message.text.trim().toUpperCase();
              return bot.setProp('Name', Name)
                  .then(() => bot.say('Hoi ${Name}. 📋 Ik heb nog wat vragen voor je om verder te kunnen.'))
                  .then(() => 'processing')
            }
},

lastCheck: {
    prompt: (bot) => bot.say(' Is er nog iets waar ik  je bij kan helpen?  🔶  %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ik zoek meer informatie':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

meerInfo: {
  prompt: (bot) => bot.say('bestand'),
   receive: () => 'processing'
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
    receive: ()  => 'finish'
},

error: {
    prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
    receive: () => 'processing'
},

finish: {
receive: () => 'finish'
}
});
<|endoftext|>


<commit_before>
$(function() {
    var MAX_PAGES = 10; // 10 is the max

    var $user = $('[data-js-hook="user"]');
    var $commits = $('[data-js-hook="commits"]');
    var $userInput = $('[name="user"]');
    var $updateButton = $('[data-js-hook="update"]');
    var $output = $('[data-js-hook="output"]');

    var commitCount = 0;

    $updateButton.click(function() {
        initialize();
        var defferedObjects = sendAjaxRequestsForGithubUserEvents(getUserName());
        $.when.apply($, defferedObjects).done(updateCommitCount);
    });

    function initialize() {
        commitCount = 0;
        $output.show();
    }

    function sendAjaxRequestsForGithubUserEvents() {
        var deferredObjects = [];
        for (var pageNumber = 1; pageNumber <= MAX_PAGES; pageNumber++) {
            deferredObjects.push(eventAPICallForUserNameAndPageNumber(pageNumber));
        }
        return deferredObjects
    }

    function eventAPICallForUserNameAndPageNumber(pageNumber) {
        return $.ajax(buildGithubApiCallUrl(pageNumber)).success(function(response){
            var pushEvents = filterEventsByType(response, 'PushEvent')
            getNumberOfCommitsFor(pushEvents);
        });
    }

    function buildGithubApiCallUrl(pageNumber) {
        return 'https://api.github.com/users/' + getUserName() + '/events/public?page=' + pageNumber;
    }

    function getUserName() {
        var userName = $userInput.val()
        $user.html(userName);
        return userName;
    }

    function filterEventsByType(events, eventType) {
        var filterEvents = []
        $.grep(events, function(n) {
            if (n['type'] === eventType){
                filterEvents.push(n)
            };
        });
        return filterEvents
    }

    function getNumberOfCommitsFor(githubEvents) {
        githubEvents.forEach(function(githubEvent) {
            var commits = githubEvent.payload.commits.length;
            commitCount += commits;
            console.log(githubEvent, commits);
        });
    }

    function updateCommitCount() {
        $commits.html(commitCount);
    }

});
<commit_msg>make vars local to methods using them, change bad var name<commit_after>
$(function() {
    var MAX_PAGES = 10; // 10 is the max
    var commitCount = 0;

    var $updateButton = $('[data-js-hook="update"]');

    $updateButton.click(function() {
        initialize();
        var defferedObjects = sendAjaxRequestsForGithubUserEvents(getUserName());
        $.when.apply($, defferedObjects).done(updateCommitCount);
    });

    function initialize() {
        var $output = $('[data-js-hook="output"]');
        commitCount = 0;
        $output.show();
    }

    function sendAjaxRequestsForGithubUserEvents() {
        var deferredObjects = [];
        for (var pageNumber = 1; pageNumber <= MAX_PAGES; pageNumber++) {
            deferredObjects.push(eventAPICallForUserNameAndPageNumber(pageNumber));
        }
        return deferredObjects
    }

    function eventAPICallForUserNameAndPageNumber(pageNumber) {
        return $.ajax(buildGithubApiCallUrl(pageNumber)).success(function(response){
            var pushEvents = filterEventsByType(response, 'PushEvent')
            getNumberOfCommitsFor(pushEvents);
        });
    }

    function buildGithubApiCallUrl(pageNumber) {
        return 'https://api.github.com/users/' + getUserName() + '/events/public?page=' + pageNumber;
    }

    function getUserName() {
        var $user = $('[data-js-hook="user"]');
        var $userInput = $('[name="user"]');

        var userName = $userInput.val()
        $user.html(userName);
        return userName;
    }

    function filterEventsByType(events, eventType) {
        var filterEvents = []
        $.grep(events, function(event) {
            if (event['type'] === eventType){
                filterEvents.push(event)
            };
        });
        return filterEvents
    }

    function getNumberOfCommitsFor(githubEvents) {
        githubEvents.forEach(function(githubEvent) {
            var commits = githubEvent.payload.commits.length;
            commitCount += commits;
            console.log(githubEvent, commits);
        });
    }

    function updateCommitCount() {
        var $commits = $('[data-js-hook="commits"]');
        $commits.html(commitCount);
    }

});
<|endoftext|>


<commit_before>/*\
|*|
|*|    JXON framework - Copyleft 2011 by Mozilla Developer Network
|*|
|*|    Revision #2 - August 27th, 2015
|*|
|*|    https://developer.mozilla.org/en-US/docs/JXON
|*|    https://developer.mozilla.org/User:fusionchess
|*|
|*|    This framework is released under the GNU Public License, version 3 or later.
|*|    http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
\*/

const JXON = new (function () {

  const
    sValProp = "keyValue", sAttrProp = "keyAttributes", sAttrsPref = "@", /* you can customize these values */
    aCache = [], rIsNull = /^\s*$/, rIsBool = /^(?:true|false)$/i;

  function parseText (sValue) {
    if (rIsNull.test(sValue)) { return null; }
    if (rIsBool.test(sValue)) { return sValue.toLowerCase() === "true"; }
    if (isFinite(sValue)) { return parseFloat(sValue); }
    if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
    return sValue;
  }

  function EmptyTree () {}

  EmptyTree.prototype.toString = function () { return "null"; };

  EmptyTree.prototype.valueOf = function () { return null; };

  function objectify (vVal) {
    return vVal === null ? new EmptyTree() : vVal instanceof Object ? vVal : new vVal.constructor(vVal);
  }

  function createObjTree (oParentNode, nVerb, bFreeze, bNesteAttr) {

    const
      nLevelStart = aCache.length, bChildren = oParentNode.hasChildNodes(),
      bAttributes = oParentNode.hasAttributes && oParentNode.hasAttributes(), bHighVerb = Boolean(nVerb & 2);

    var
      sProp, vContent, nLength = 0, sCollectedTxt = "",
      vResult = bHighVerb ? {} : /* put here the default value for empty nodes: */ true;

    if (bChildren) {
      for (var oNode, nItem = 0; nItem < oParentNode.childNodes.length; nItem++) {
        oNode = oParentNode.childNodes.item(nItem);
        if (oNode.nodeType === 4) { sCollectedTxt += oNode.nodeValue; } /* nodeType is "CDATASection" (4) */
        else if (oNode.nodeType === 3) { sCollectedTxt += oNode.nodeValue.trim(); } /* nodeType is "Text" (3) */
        else if (oNode.nodeType === 1 && !oNode.prefix) { aCache.push(oNode); } /* nodeType is "Element" (1) */
      }
    }

    const nLevelEnd = aCache.length, vBuiltVal = parseText(sCollectedTxt);

    if (!bHighVerb && (bChildren || bAttributes)) { vResult = nVerb === 0 ? objectify(vBuiltVal) : {}; }

    for (var nElId = nLevelStart; nElId < nLevelEnd; nElId++) {
      sProp = aCache[nElId].nodeName.toLowerCase();
      vContent = createObjTree(aCache[nElId], nVerb, bFreeze, bNesteAttr);
      if (vResult.hasOwnProperty(sProp)) {
        if (vResult[sProp].constructor !== Array) { vResult[sProp] = [vResult[sProp]]; }
        vResult[sProp].push(vContent);
      } else {
        vResult[sProp] = vContent;
        nLength++;
      }
    }

    if (bAttributes) {

      const
        nAttrLen = oParentNode.attributes.length,
        sAPrefix = bNesteAttr ? "" : sAttrsPref, oAttrParent = bNesteAttr ? {} : vResult;

      for (var oAttrib, nAttrib = 0; nAttrib < nAttrLen; nLength++, nAttrib++) {
        oAttrib = oParentNode.attributes.item(nAttrib);
        oAttrParent[sAPrefix + oAttrib.name.toLowerCase()] = parseText(oAttrib.value.trim());
      }

      if (bNesteAttr) {
        if (bFreeze) { Object.freeze(oAttrParent); }
        vResult[sAttrProp] = oAttrParent;
        nLength -= nAttrLen - 1;
      }

    }

    if (nVerb === 3 || (nVerb === 2 || nVerb === 1 && nLength > 0) && sCollectedTxt) {
      vResult[sValProp] = vBuiltVal;
    } else if (!bHighVerb && nLength === 0 && sCollectedTxt) {
      vResult = vBuiltVal;
    }

    if (bFreeze && (bHighVerb || nLength > 0)) { Object.freeze(vResult); }

    aCache.length = nLevelStart;

    return vResult;

  }

  function loadObjTree (oXMLDoc, oParentEl, oParentObj) {

    var vValue, oChild;

    if (oParentObj.constructor === String || oParentObj.constructor === Number || oParentObj.constructor === Boolean) {
      oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 or 1 */
      if (oParentObj === oParentObj.valueOf()) { return; }
    } else if (oParentObj.constructor === Date) {
      oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString()));
    }

    for (var sName in oParentObj) {
      vValue = oParentObj[sName];
      if (isFinite(sName) || vValue instanceof Function) { continue; } /* verbosity level is 0 */
      if (sName === sValProp) {
        if (vValue !== null && vValue !== true) { oParentEl.appendChild(oXMLDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); }
      } else if (sName === sAttrProp) { /* verbosity level is 3 */
        for (var sAttrib in vValue) { oParentEl.setAttribute(sAttrib, vValue[sAttrib]); }
      } else if (sName.charAt(0) === sAttrsPref) {
        oParentEl.setAttribute(sName.slice(1), vValue);
      } else if (vValue.constructor === Array) {
        for (var nItem = 0; nItem < vValue.length; nItem++) {
          oChild = oXMLDoc.createElement(sName);
          loadObjTree(oXMLDoc, oChild, vValue[nItem]);
          oParentEl.appendChild(oChild);
        }
      } else {
        oChild = oXMLDoc.createElement(sName);
        if (vValue instanceof Object) {
          loadObjTree(oXMLDoc, oChild, vValue);
        } else if (vValue !== null && vValue !== true) {
          oChild.appendChild(oXMLDoc.createTextNode(vValue.toString()));
        }
        oParentEl.appendChild(oChild);
      }
    }

  }

  /* Uncomment the following code if you want to enable the .appendJXON() method for *all* the "element" objects! */

  /*

  Element.prototype.appendJXON = function (oObjTree) {
    loadObjTree(document, this, oObjTree);
    return this;
  };

  */

  this.build = function (oXMLParent, nVerbosity /* optional */, bFreeze /* optional */, bNesteAttributes /* optional */) {
    const nVerbMask = arguments.length > 1 && typeof nVerbosity === "number" ? nVerbosity & 3 : /* put here the default verbosity level: */ 1;
    return createObjTree(oXMLParent, nVerbMask, bFreeze || false, arguments.length > 3 ? bNesteAttributes : nVerbMask === 3);
  };

  this.unbuild = function (oObjTree, sNamespaceURI /* optional */, sQualifiedName /* optional */, oDocumentType /* optional */) {
    const oNewDoc = document.implementation.createDocument(sNamespaceURI || null, sQualifiedName || "", oDocumentType || null);
    loadObjTree(oNewDoc, oNewDoc, oObjTree);
    return oNewDoc;
  };

})();
/**
 * @author gggordon <https://github.com/gggordon>
 * @overview Crabber
 * @description Grabs Content of External Links Posted
 * @license MIT
 * @created 2.11.2015
 * @dependencies
 *     - jquery 2.1.*
 *     - JXON
 */

 (function($,w){
 	if($==undefined || $ == null){
 		throw new Exception("jQuery required for Crabber");
 	}
 	/**
     * @param props Object Configuration Object
     * @param props.title String Title
     * @param props.description String Page Description
     * @param props.videoUrl String Url of Video
     * @param props.url String Link Url
     * @param props.videoType String ** Not Used
     * @param props.imageUrl String ** Not Used
 	 */
 	function ExternalContent(props){
        props = props || {};
        var _self = this;
        _self.title = props.title || "";
        _self.url = props.url || "";
        _self.description = props.description || "";
        _self.type = props.type || "website";
        _self.imageUrl = props.imageUrl || "";

        /**
         * Display HTML
         * @param options Object
         * @overide
         */
        _self.display=function(options){
            return '

';
        }
 	}

 	/**
 	 * @param divNode HTMLInputElement
 	 * @param options Object
 	 * @param options.
 	 */
 	function Crabber(divNode, options){
        if(divNode == null || divNode == undefined)
        	return;

        options = options || {};
        var _self = this;

        _self._$tbox=$(divNode);
        _self._$viewNode = $(options.viewNode || (function($tbox){
            var uuid= "crab-view-"+Math.random()*50;
            $tbox.after('

');
            return $('#'+uuid).get(0);
        })(_self._$tbox));
        _self.links = [];
        _self._display = options.display || null;
        _self._getLinksFromStr=function(str){
        	return (str || "").match(/(http:|https:)?\/\/\S+/ig) || [];
        };
        /**
         * @param links Array|string
         * @param callback function(Array|ExternalContent) Callback function accepting array of ExternalContent
         */
        _self._getContentFromLinks=function(links,callback){
        	var contents = [];
        	for(var i=0;i<links.length;i++){

        	}
        	if(callback && typeof callback == 'function')
        		callback(contents);

        	return contents;
        };
        _self.__getContentUsingYQL=function(link,callback){
        	var yqlQuery = "select * from html where url=\""+link+"\" and xpath='/html'";
        	var yqlUrl = "https://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent(yqlQuery)+"&format=json&diagnostics=true&callback=";
        	$.ajax({
                 url:yqlUrl,
                 success:function(data){
                 	console.log('success');
                    console.log(data);
                    var head = data.query.results.html.head;
                    var title = head.title;
                    var desc = (function(meta){
                         for(var i=0;i< meta.length;i++){
                           if(meta[i].name=="description")
                             return meta[i].content;
                         }
                         return '';
                     })(head.meta);
                 },
                 error:function(err){
                 	console.log('error');
                    console.log(err);
                 }
             });
        }
        /**
         * Append contents to node
         * @param contents Array|ExternalContent
         */
        _self._appendContentToNode=function(contents){
             (contents || []).map(function(cn){
                 _self._$viewNode.append(
                     cn.display()
                 );
             });
        }

        /*Event Listeners*/
        /**
         * @param evt Event
         */
        _self._appendOutputOnTextChange=function(evt){
            var newLinks = _self._getLinksFromStr(_self._$tbox.html())
                                .filter(function(link){
                                            var isNew = _self.links.indexOf(link) > -1;
                                            if(isNew)
                                                _self.links.push(link);
                                            return isNew;
                                }) || [];
            _self._getContentFromLinks(newLinks,_self._appendContentToNode)
        };
 	}

    if(w instanceof Object){
        w.Crabber = Crabber;
    }
    $.fn.crabber = function(opts){
        return this.each(function(i,el){
        	new Crabber(el,opts);
        });
    };

 })(jQuery,window);
<commit_msg>Removed JXON support<commit_after>/**
 * @author gggordon <https://github.com/gggordon>
 * @overview Crabber
 * @description Grabs Content of External Links Posted
 * @license MIT
 * @created 2.11.2015
 * @dependencies
 *     - jquery 2.1.*
 */

 (function($,w){
 	if($==undefined || $ == null){
 		throw new Exception("jQuery required for Crabber");
 	}
 	/**
     * @param props Object Configuration Object
     * @param props.title String Title
     * @param props.description String Page Description
     * @param props.videoUrl String Url of Video
     * @param props.url String Link Url
     * @param props.videoType String ** Not Used
     * @param props.imageUrl String ** Not Used
 	 */
 	function ExternalContent(props){
        props = props || {};
        var _self = this;
        _self.title = props.title || "";
        _self.url = props.url || "";
        _self.description = props.description || "";
        _self.type = props.type || "website";
        _self.imageUrl = props.imageUrl || "";

        /**
         * Display HTML
         * @param options Object
         * @overide
         */
        _self.display=function(options){
            return '

';
        }
 	}

 	/**
 	 * @param divNode HTMLInputElement
 	 * @param options Object
 	 * @param options.
 	 */
 	function Crabber(divNode, options){
        if(divNode == null || divNode == undefined)
        	return;

        options = options || {};
        var _self = this;

        _self._$tbox=$(divNode);
        _self._$viewNode = $(options.viewNode || (function($tbox){
            var uuid= "crab-view-"+Math.random()*50;
            $tbox.after('

');
            return $('#'+uuid).get(0);
        })(_self._$tbox));
        _self.links = [];
        _self._display = options.display || null;
        _self._getLinksFromStr=function(str){
        	return (str || "").match(/(http:|https:)?\/\/\S+/ig) || [];
        };
        /**
         * @param links Array|string
         * @param callback function(Array|ExternalContent) Callback function accepting array of ExternalContent
         */
        _self._getContentFromLinks=function(links,callback){
        	var contents = [];
        	for(var i=0;i<links.length;i++){

        	}
        	if(callback && typeof callback == 'function')
        		callback(contents);

        	return contents;
        };
        _self.__getContentUsingYQL=function(link,callback){
        	var yqlQuery = "select * from html where url=\""+link+"\" and xpath='/html'";
        	var yqlUrl = "https://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent(yqlQuery)+"&format=json&diagnostics=true&callback=";
        	$.ajax({
                 url:yqlUrl,
                 success:function(data){
                 	console.log('success');
                    console.log(data);
                    var head = data.query.results.html.head;
                    var title = head.title;
                    var desc = (function(meta){
                         for(var i=0;i< meta.length;i++){
                           if(meta[i].name=="description")
                             return meta[i].content;
                         }
                         return '';
                     })(head.meta);
                 },
                 error:function(err){
                 	console.log('error');
                    console.log(err);
                 }
             });
        }
        /**
         * Append contents to node
         * @param contents Array|ExternalContent
         */
        _self._appendContentToNode=function(contents){
             (contents || []).map(function(cn){
                 _self._$viewNode.append(
                     cn.display()
                 );
             });
        }

        /*Event Listeners*/
        /**
         * @param evt Event
         */
        _self._appendOutputOnTextChange=function(evt){
            var newLinks = _self._getLinksFromStr(_self._$tbox.html())
                                .filter(function(link){
                                            var isNew = _self.links.indexOf(link) > -1;
                                            if(isNew)
                                                _self.links.push(link);
                                            return isNew;
                                }) || [];
            _self._getContentFromLinks(newLinks,_self._appendContentToNode)
        };
 	}

    if(w instanceof Object){
        w.Crabber = Crabber;
    }
    $.fn.crabber = function(opts){
        return this.each(function(i,el){
        	new Crabber(el,opts);
        });
    };

 })(jQuery,window);
<|endoftext|>


<commit_before>var iconStar = "img/star.svg";
var iconNostar = "img/nostar.svg";
var iconSearch = "img/search.svg";
var lang = 0; // 0 for italian and 1 for german
var sug = new Array();
var board = new Object();

loadBusstopsList();

$(document).ready(function() {

	// Initialize

	$(":input").val("");
	$(".bus-list").hide();
	$(".station").removeClass("expanded");
  var favo = loadFavo();
  for (id in favo) {
    favo[id].busstops.forEach( function (el, index) {
      downloadBoard(el.ORT_NR);
    });
  }
	drawContent();

});

//bindEvents();
// User Events
function bindToggle(el, stop) {
	el.find(".station").click(function() {
		//console.log("Toggle");
		if ($(this).hasClass("expanded")) {
			$(this).children(".bus-list").slideUp(200);
			$(this).removeClass("expanded");
		} else {
			$(this).children(".bus-list").slideDown(200);
			$(this).addClass("expanded");
		}
	});

}

function bindStar(el, con) {
	//console.log("Bind Star", el);
	$(el).click(function() {
		if ($(this).hasClass("js-starred")) {
			// Remove Favorite
			$(this).attr("src", iconNostar);
			$(this).removeClass("star").addClass("nostar");
			$(this).removeClass("js-starred");
			removeFavorite(con);
			//$(this).parents(".station").remove();
			return false;
		} else {
			// Add new Favorite
			$(this).attr("src", iconStar);
			$(this).removeClass("nostar").addClass("star");
			$(this).addClass("js-starred");
			addFavorite(con);
			//    $(".favorites").append($(this).parents(".station").clone());
			return false;
		}
	});

}

function addFavorite(content) {
	var favo = loadFavo();
	favo[content.busstops[0].ORT_NR] = content;
	saveFavo(favo);
	drawContent();
}

function removeFavorite(content) {
	var favo = loadFavo();
	delete(favo[content.busstops[0].ORT_NR]);
	saveFavo(favo);
	drawContent();
}

function printFavorite(favo) {
  var idList = [];
	//console.log(favo);
	if (JSON.stringify(favo) == "{}")
		$(".favorites-title").hide();
	else
		$(".favorites-title").show();
	$(".favorites").empty();
	//console.log(favo);
	for (var el in favo) {
    idList = [];
    for (var j = 0; j < favo[el].busstops.length; j++) {
      idList[j] = favo[el].busstops[j].ORT_NR;
    }
    console.log("Favo", idList);
		var div = '
' +
			'' +
			'
' +
			favo[el].stop[lang] + " - " +
			favo[el].city[lang] +
			'
' +
			'<button class="station-star star js-starred"></button>' +
			'' +
      '
' +
      addBoard(idList) +
      '
' +
      'No Connections' +
      '
' +
      '
' +
			'
';
		$(".favorites").append(div);
		bindStar($(".favorites").find(".station-star:last"), favo[el]);
	}
}

$(".js-search").bind("input", function() {
	sug = matchInput(getBusstopList(), $(".js-search").val());
	for (var j = 0; j < sug.length; j++) {
		for (var i = 0; i < sug[j].busstops.length; i++) {
			downloadBoard(sug[j].busstops[i].ORT_NR);
		}
	}
  drawContent();
});

//match input with busstops name and citys
function matchInput(list, input) {
	var suggests = [];
	var found;
	var j;
	if (input !== "") {
		input = input.split(" ");
		for (var i = 0; i < list.length && suggests.length < 4; i++) {
			j = 0;
			do {
				if (input[j] !== "") {
					found = list[i].ORT_GEMEINDE.match(new RegExp(input[j], "i"));
					if (found === null)
						found = list[i].ORT_NAME.match(new RegExp(input[j], "i"));
				}
				j++;
			} while (j < input.length && found !== null);
			if (found !== null)
				suggests[suggests.length] = list[i];
		}
	}
	return suggests;
}

//output suggests
function printSuggests(suggests, dest) {
	var favo = loadFavo();
  var idList = [];

	dest.empty();
	for (var i = 0; i < suggests.length; i++) {
    idList = [];
    for (var j = 0; j < suggests[i].busstops.length; j++) {
      idList[j] = suggests[i].busstops[j].ORT_NR;
    }

		var div = '
' +
			'' +
			'
' +
			suggests[i].stop[lang] + " - " +
			suggests[i].city[lang] +
			'
' +
			'<button class="station-star nostar"></button>' +
			'' +
      '
' +
      addBoard(idList) +
      '
' +
      'No Connections' +
      '
' +
      '
' +
			'
';

			//'

' +
    dest.append(div);

		//favo must be set before bindStar
		if (favo[suggests[i].busstops[0].ORT_NR])
			dest.find(".station-star:last").removeClass("nostar").addClass("star js-starred");
		bindStar(dest.find(".station-star:last"), suggests[i]);
	}
}

function downloadBoard(id) {
	if (board[id] === undefined) {
		var apiUrl = "http://stationboard.opensasa.info/?type=jsonp&ORT_NR=" + id;
		request(apiUrl, stationSuccess, "JSONP", id);
		board[id] = {};
		board[id].runing = true;
	}
}

function stationSuccess(data, id) {
	board[id].runing = false;
	board[id].rides = data.rides;
	//drawContent();
  insertRides();
}

function insertRides() {
  for (var id in board) {
    var data = board[id].rides;
    $("." + id).empty();
    if (board[id].runing !== undefined && board[id].runing === false) {
      for (var i = 0; i < 4 && i < data.length; i++) {
        var div = '
' +
          '' +
          (data[i].lidname).substring(0,3) +
          '' +
          '' +
          formatTime(data[i].departure) +
          '' +
          '' +
          data[i].last_station.split(" - ")[lang] +
          '' +
          '
';
        $("." + id).append(div).show();
      }

      if (data.length === 0) {
        if (!($("." + id).siblings().is(":visible")))
          $("." + id).siblings(".js-no-connections").show();
      }
      else
        $("." + id).siblings(".js-no-connections").hide();
    }
  }
}

function addBoard(idList) {
  var div = "";
  for (var i = 0; i < idList.length; i++) {
    div += '
' +
      '
';
  }
  return div;
}

// cache busstops
function loadBusstopsList() {
  //console.log("Start Request");
  var apiUrl =
    "http://opensasa.info/SASAplandata/?type=BASIS_VER_GUELTIGKEIT";
  request(apiUrl, validitySuccess, "jsonp");
}

function formatTime(time) {
  return time;
}

function validitySuccess(data) {
  if (!localStorage.version || localStorage.version != data[0].VER_GUELTIGKEIT) {
    localStorage.clear();
    localStorage.version = data[0].VER_GUELTIGKEIT;
    if (!localStorage.busstops) {
      //console.log("New Data");
      var apiUrl = "http://opensasa.info/SASAplandata/?type=REC_ORT";
      request(apiUrl, busstopsSuccess, "jsonp");
    }
  }

}

function busstopsSuccess(data) {
  for (var i = 0; i < data.length; i++) {
    // [0] is italian [1] is german
    data[i].stop = data[i].ORT_NAME.split(" - ");
    data[i].city = data[i].ORT_GEMEINDE.split(" - ");
  }
  localStorage.setItem('busstops', JSON.stringify(data));
}

// Return the busstop list as json which is stored in the localStorage
function getBusstopList() {
  return JSON.parse(localStorage.busstops);
}

function loadFavo() {
  if (localStorage.fav)
    return JSON.parse(localStorage.fav);
  else
    return new Object();
}

function saveFavo(data) {
  localStorage.fav = JSON.stringify(data);
}

// callback is the name of the callback arg
function request(urlAPI, success, callback, index) {
  $.ajax({
    url: urlAPI,
    dataType: 'jsonp',
    jsonp: callback,
    success: function(data) {
      //console.log("success: " + urlAPI);
      success(data, index);
    },
    error: function(data) {
      console.log("Error: " + urlAPI);
    }
  });
}

function drawContent() {
  var favo = loadFavo();
  printSuggests(sug, $(".search-results"));
  printFavorite(favo, $(".favorites"));

  insertRides();

  bindToggle($(".search-results"));
  bindToggle($(".favorites"));
}
<commit_msg>[ui] add loading spinner<commit_after>var iconStar = "img/star.svg";
var iconNostar = "img/nostar.svg";
var iconSearch = "img/search.svg";
var lang = 0; // 0 for italian and 1 for german
var sug = new Array();
var board = new Object();

loadBusstopsList();

$(document).ready(function() {

	// Initialize

	$(":input").val("");
	$(".bus-list").hide();
	$(".station").removeClass("expanded");
  var favo = loadFavo();
  for (id in favo) {
    favo[id].busstops.forEach( function (el, index) {
      downloadBoard(el.ORT_NR);
    });
  }
	drawContent();

});

//bindEvents();
// User Events
function bindToggle(el, stop) {
	el.find(".station").click(function() {
		//console.log("Toggle");
		if ($(this).hasClass("expanded")) {
			$(this).children(".bus-list").slideUp(200);
			$(this).removeClass("expanded");
		} else {
			$(this).children(".bus-list").slideDown(200);
			$(this).addClass("expanded");
		}
	});

}

function bindStar(el, con) {
	//console.log("Bind Star", el);
	$(el).click(function() {
		if ($(this).hasClass("js-starred")) {
			// Remove Favorite
			$(this).attr("src", iconNostar);
			$(this).removeClass("star").addClass("nostar");
			$(this).removeClass("js-starred");
			removeFavorite(con);
			//$(this).parents(".station").remove();
			return false;
		} else {
			// Add new Favorite
			$(this).attr("src", iconStar);
			$(this).removeClass("nostar").addClass("star");
			$(this).addClass("js-starred");
			addFavorite(con);
			//    $(".favorites").append($(this).parents(".station").clone());
			return false;
		}
	});

}

function addFavorite(content) {
	var favo = loadFavo();
	favo[content.busstops[0].ORT_NR] = content;
	saveFavo(favo);
	drawContent();
}

function removeFavorite(content) {
	var favo = loadFavo();
	delete(favo[content.busstops[0].ORT_NR]);
	saveFavo(favo);
	drawContent();
}

function printFavorite(favo) {
  var idList = [];
	//console.log(favo);
	if (JSON.stringify(favo) == "{}")
		$(".favorites-title").hide();
	else
		$(".favorites-title").show();
	$(".favorites").empty();
	//console.log(favo);
	for (var el in favo) {
    idList = [];
    for (var j = 0; j < favo[el].busstops.length; j++) {
      idList[j] = favo[el].busstops[j].ORT_NR;
    }
    console.log("Favo", idList);
		var div = '
' +
			'' +
			'
' +
			favo[el].stop[lang] + " - " +
			favo[el].city[lang] +
			'
' +
			'<button class="station-star star js-starred"></button>' +
			'' +
      '
' +
      addBoard(idList) +
      '
' +
      'No Connections' +
      '
' +
      '' +
      '
' +
			'
';
		$(".favorites").append(div);
		bindStar($(".favorites").find(".station-star:last"), favo[el]);
	}
}

$(".js-search").bind("input", function() {
	sug = matchInput(getBusstopList(), $(".js-search").val());
	for (var j = 0; j < sug.length; j++) {
		for (var i = 0; i < sug[j].busstops.length; i++) {
			downloadBoard(sug[j].busstops[i].ORT_NR);
		}
	}
  drawContent();
});

//match input with busstops name and citys
function matchInput(list, input) {
	var suggests = [];
	var found;
	var j;
	if (input !== "") {
		input = input.split(" ");
		for (var i = 0; i < list.length && suggests.length < 4; i++) {
			j = 0;
			do {
				if (input[j] !== "") {
					found = list[i].ORT_GEMEINDE.match(new RegExp(input[j], "i"));
					if (found === null)
						found = list[i].ORT_NAME.match(new RegExp(input[j], "i"));
				}
				j++;
			} while (j < input.length && found !== null);
			if (found !== null)
				suggests[suggests.length] = list[i];
		}
	}
	return suggests;
}

//output suggests
function printSuggests(suggests, dest) {
	var favo = loadFavo();
  var idList = [];

	dest.empty();
	for (var i = 0; i < suggests.length; i++) {
    idList = [];
    for (var j = 0; j < suggests[i].busstops.length; j++) {
      idList[j] = suggests[i].busstops[j].ORT_NR;
    }

		var div = '
' +
			'' +
			'
' +
			suggests[i].stop[lang] + " - " +
			suggests[i].city[lang] +
			'
' +
			'<button class="station-star nostar"></button>' +
			'' +
      '
' +
      addBoard(idList) +
      '
' +
      'No Connections' +
      '
' +
      '' +
      '
' +
			'
';

			//'

' +
    dest.append(div);

		//favo must be set before bindStar
		if (favo[suggests[i].busstops[0].ORT_NR])
			dest.find(".station-star:last").removeClass("nostar").addClass("star js-starred");
		bindStar(dest.find(".station-star:last"), suggests[i]);
	}
}

function downloadBoard(id) {
	if (board[id] === undefined) {
		var apiUrl = "http://stationb2oard.opensasa.info/?type=jsonp&ORT_NR=" + id;
		request(apiUrl, stationSuccess, "JSONP", id);
		board[id] = {};
		board[id].runing = true;
	}
}

function stationSuccess(data, id) {
	board[id].runing = false;
	board[id].rides = data.rides;
	//drawContent();
  insertRides();
}

function insertRides() {
  for (var id in board) {
    var data = board[id].rides;
    $("." + id).empty();
    if (board[id].runing !== undefined && board[id].runing === false) {
      $("." + id).siblings(".spinner").hide();
      for (var i = 0; i < 4 && i < data.length; i++) {
        var div = '
' +
          '' +
          (data[i].lidname).substring(0,3) +
          '' +
          '' +
          formatTime(data[i].departure) +
          '' +
          '' +
          data[i].last_station.split(" - ")[lang] +
          '' +
          '
';
        $("." + id).append(div).show();
      }

      if (data.length === 0) {
        if (!($("." + id).siblings().is(":visible")))
          $("." + id).siblings(".js-no-connections").show();
      }
      else
        $("." + id).siblings(".js-no-connections").hide();
    }
    else {
        $("." + id).siblings(".spinner").show();

    }
  }
}

function addBoard(idList) {
  var div = "";
  for (var i = 0; i < idList.length; i++) {
    div += '
' +
      '
';
  }
  return div;
}

// cache busstops
function loadBusstopsList() {
  //console.log("Start Request");
  var apiUrl =
    "http://opensasa.info/SASAplandata/?type=BASIS_VER_GUELTIGKEIT";
  request(apiUrl, validitySuccess, "jsonp");
}

function formatTime(time) {
  return time;
}

function validitySuccess(data) {
  if (!localStorage.version || localStorage.version != data[0].VER_GUELTIGKEIT) {
    localStorage.clear();
    localStorage.version = data[0].VER_GUELTIGKEIT;
    if (!localStorage.busstops) {
      //console.log("New Data");
      var apiUrl = "http://opensasa.info/SASAplandata/?type=REC_ORT";
      request(apiUrl, busstopsSuccess, "jsonp");
    }
  }

}

function busstopsSuccess(data) {
  for (var i = 0; i < data.length; i++) {
    // [0] is italian [1] is german
    data[i].stop = data[i].ORT_NAME.split(" - ");
    data[i].city = data[i].ORT_GEMEINDE.split(" - ");
  }
  localStorage.setItem('busstops', JSON.stringify(data));
}

// Return the busstop list as json which is stored in the localStorage
function getBusstopList() {
  return JSON.parse(localStorage.busstops);
}

function loadFavo() {
  if (localStorage.fav)
    return JSON.parse(localStorage.fav);
  else
    return new Object();
}

function saveFavo(data) {
  localStorage.fav = JSON.stringify(data);
}

// callback is the name of the callback arg
function request(urlAPI, success, callback, index) {
  $.ajax({
    url: urlAPI,
    dataType: 'jsonp',
    jsonp: callback,
    success: function(data) {
      //console.log("success: " + urlAPI);
      success(data, index);
    },
    error: function(data) {
      console.log("Error: " + urlAPI);
    }
  });
}

function drawContent() {
  var favo = loadFavo();
  printSuggests(sug, $(".search-results"));
  printFavorite(favo, $(".favorites"));

  insertRides();

  bindToggle($(".search-results"));
  bindToggle($(".favorites"));
}
<|endoftext|>


<commit_before>/* jshint -W117 */
function TraceablePeerConnection(ice_config, constraints) {
    var self = this;
    var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
    this.peerconnection = new RTCPeerconnection(ice_config, constraints);
    this.updateLog = [];
    this.stats = {};
    this.statsinterval = null;
    this.maxstats = 300; // limit to 300 values, i.e. 5 minutes; set to 0 to disable

    // override as desired
    this.trace = function(what, info) {
        //console.warn('WTRACE', what, info);
        self.updateLog.push({
            time: new Date(),
            type: what,
            value: info || ""
        });
    };
    this.onicecandidate = null;
    this.peerconnection.onicecandidate = function (event) {
        self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
        if (self.onicecandidate !== null) {
            self.onicecandidate(event);
        }
    };
    this.onaddstream = null;
    this.peerconnection.onaddstream = function (event) {
        self.trace('onaddstream', event.stream.id);
        if (self.onaddstream !== null) {
            self.onaddstream(event);
        }
    };
    this.onremovestream = null;
    this.peerconnection.onremovestream = function (event) {
        self.trace('onremovestream', event.stream.id);
        if (self.onremovestream !== null) {
            self.onremovestream(event);
        }
    };
    this.onsignalingstatechange = null;
    this.peerconnection.onsignalingstatechange = function (event) {
        self.trace('onsignalingstatechange', event.srcElement.signalingState);
        if (self.onsignalingstatechange !== null) {
            self.onsignalingstatechange(event);
        }
    };
    this.oniceconnectionstatechange = null;
    this.peerconnection.oniceconnectionstatechange = function (event) {
        self.trace('oniceconnectionstatechange', event.srcElement.iceConnectionState);
        if (self.oniceconnectionstatechange !== null) {
            self.oniceconnectionstatechange(event);
        }
    };
    this.onnegotiationneeded = null;
    this.peerconnection.onnegotiationneeded = function (event) {
        self.trace('onnegotiationneeded');
        if (self.onnegotiationneeded !== null) {
            self.onnegotiationneeded(event);
        }
    };
    self.ondatachannel = null;
    this.peerconnection.ondatachannel = function (event) {
        self.trace('ondatachannel', event);
        if (self.ondatachannel !== null) {
            self.ondatachannel(event);
        }
    }
    this.statsinterval = window.setInterval(function() {
        self.peerconnection.getStats(function(stats) {
            var results = stats.result();
            for (var i = 0; i < results.length; ++i) {
                //console.log(results[i].type, results[i].id, results[i].names())
                var now = new Date();
                results[i].names().forEach(function (name) {
                    var id = results[i].id + '-' + name;
                    if (!self.stats[id]) {
                        self.stats[id] = {
                            startTime: now,
                            endTime: now,
                            values: []
                        };
                    }
                    self.stats[id].values.push(results[i].stat(name));
                    if (self.stats[id].values.length > self.maxstats) {
                        self.stats[id].values.shift();
                    }
                    self.stats[id].endTime = now;
                });
            }
        });

    }, 1000);
};

dumpSDP = function(description) {
    return 'type: ' + description.type + '\r\n' + description.sdp;
}

TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() { return this.peerconnection.localDescription; });
TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() { return this.peerconnection.remoteDescription; });

TraceablePeerConnection.prototype.addStream = function (stream) {
    this.trace('addStream', stream.id);
    this.peerconnection.addStream(stream);
};

TraceablePeerConnection.prototype.removeStream = function (stream) {
    this.trace('removeStream', stream.id);
    this.peerconnection.removeStream(stream);
};

TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
    this.trace('createDataChannel', label, opts);
    this.peerconnection.createDataChannel(label, opts);
}

TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
    var self = this;
    this.trace('setLocalDescription', dumpSDP(description));
    this.peerconnection.setLocalDescription(description,
        function () {
            self.trace('setLocalDescriptionOnSuccess');
            successCallback();
        },
        function (err) {
            self.trace('setLocalDescriptionOnFailure', err);
            failureCallback(err);
        }
    );
    if (this.statsinterval === null && this.maxstats > 0) {
        // start gathering stats
        this.statsinterval = window.setInterval(this.dumpStats, 1000);
    }
};

TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
    var self = this;
    this.trace('setRemoteDescription', dumpSDP(description));
    this.peerconnection.setRemoteDescription(description,
        function () {
            self.trace('setRemoteDescriptionOnSuccess');
            successCallback();
        },
        function (err) {
            self.trace('setRemoteDescriptionOnFailure', err);
            failureCallback(err);
        }
    );
    if (this.statsinterval === null && this.maxstats > 0) {
        // start gathering stats
        this.statsinterval = window.setInterval(this.dumpStats, 1000);
    }
};

TraceablePeerConnection.prototype.close = function () {
    this.trace('stop');
    if (this.statsinterval !== null) {
        window.clearInterval(this.statsinterval);
        this.statsinterval = null;
    }
    this.peerconnection.close();
};

TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
    var self = this;
    this.trace('createOffer', JSON.stringify(constraints, null, ' '));
    this.peerconnection.createOffer(
        function (offer) {
            self.trace('createOfferOnSuccess', dumpSDP(offer));
            successCallback(offer);
        },
        function(err) {
            self.trace('createOfferOnFailure', err);
            failureCallback(err);
        },
        constraints
    );
};

TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
    var self = this;
    this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
    this.peerconnection.createAnswer(
        function (answer) {
            self.trace('createAnswerOnSuccess', dumpSDP(answer));
            successCallback(answer);
        },
        function(err) {
            self.trace('createAnswerOnFailure', err);
            failureCallback(err);
        },
        constraints
    );
};

TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
    var self = this;
    this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
    this.peerconnection.addIceCandidate(candidate);
    /* maybe later
    this.peerconnection.addIceCandidate(candidate,
        function () {
            self.trace('addIceCandidateOnSuccess');
            successCallback();
        },
        function (err) {
            self.trace('addIceCandidateOnFailure', err);
            failureCallback(err);
        }
    );
    */
};

TraceablePeerConnection.prototype.getStats = function(callback) {
    this.peerconnection.getStats(callback);
};

TraceablePeerConnection.prototype.dumpStats = function(stats) {
    var self = this;
    var results = stats.result();
    for (var i = 0; i < results.length; ++i) {
        //console.log(results[i].type, results[i].id, results[i].names())
        var now = new Date();
        results[i].names().forEach(function (name) {
            var id = results[i].id + '-' + name;
            if (!self.stats[id]) {
                self.stats[id] = {
                    startTime: now,
                    endTime: now,
                    values: []
                };
            }
            self.stats[id].values.push(results[i].stat(name));
            if (self.stats[id].values.length > self.maxstats) {
                self.stats[id].values.shift();
            }
            self.stats[id].endTime = now;
        });
    }
};

// mozilla chrome compat layer -- very similar to adapter.js
function setupRTC() {
    var RTC = null;
    if (navigator.mozGetUserMedia) {
        console.log('This appears to be Firefox');
        var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
        if (version >= 22) {
            RTC = {
                peerconnection: mozRTCPeerConnection,
                browser: 'firefox',
                getUserMedia: navigator.mozGetUserMedia.bind(navigator),
                attachMediaStream: function (element, stream) {
                    element[0].mozSrcObject = stream;
                    element[0].play();
                },
                pc_constraints: {}
            };
            if (!MediaStream.prototype.getVideoTracks)
                MediaStream.prototype.getVideoTracks = function () { return []; };
            if (!MediaStream.prototype.getAudioTracks)
                MediaStream.prototype.getAudioTracks = function () { return []; };
            RTCSessionDescription = mozRTCSessionDescription;
            RTCIceCandidate = mozRTCIceCandidate;
        }
    } else if (navigator.webkitGetUserMedia) {
        console.log('This appears to be Chrome');
        RTC = {
            peerconnection: webkitRTCPeerConnection,
            browser: 'chrome',
            getUserMedia: navigator.webkitGetUserMedia.bind(navigator),
            attachMediaStream: function (element, stream) {
                element.attr('src', webkitURL.createObjectURL(stream));
            },
            // DTLS should now be enabled by default but..
            pc_constraints: {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]}
        };
        if (navigator.userAgent.indexOf('Android') != -1) {
            RTC.pc_constraints = {}; // disable DTLS on Android
        }
        if (!webkitMediaStream.prototype.getVideoTracks) {
            webkitMediaStream.prototype.getVideoTracks = function () {
                return this.videoTracks;
            };
        }
        if (!webkitMediaStream.prototype.getAudioTracks) {
            webkitMediaStream.prototype.getAudioTracks = function () {
                return this.audioTracks;
            };
        }
    }
    if (RTC === null) {
        try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
    }
    return RTC;
}

function getUserMediaWithConstraints(um, resolution, bandwidth, fps) {
    var constraints = {audio: false, video: false};

    if (um.indexOf('video') >= 0) {
        constraints.video = {mandatory: {}};// same behaviour as true
    }
    if (um.indexOf('audio') >= 0) {
        constraints.audio = {};// same behaviour as true
    }
    if (um.indexOf('screen') >= 0) {
        constraints.video = {
            "mandatory": {
                "chromeMediaSource": "screen"
            }
        };
    }

    if (resolution && !constraints.video) {
        constraints.video = {mandatory: {}};// same behaviour as true
    }
    // see https://code.google.com/p/chromium/issues/detail?id=143631#c9 for list of supported resolutions
    switch (resolution) {
    // 16:9 first
    case '1080':
    case 'fullhd':
        constraints.video.mandatory.minWidth = 1920;
        constraints.video.mandatory.minHeight = 1080;
        constraints.video.mandatory.minAspectRatio = 1.77;
        break;
    case '720':
    case 'hd':
        constraints.video.mandatory.minWidth = 1280;
        constraints.video.mandatory.minHeight = 720;
        constraints.video.mandatory.minAspectRatio = 1.77;
        break;
    case '360':
        constraints.video.mandatory.minWidth = 640;
        constraints.video.mandatory.minHeight = 360;
        constraints.video.mandatory.minAspectRatio = 1.77;
        break;
    case '180':
        constraints.video.mandatory.minWidth = 320;
        constraints.video.mandatory.minHeight = 180;
        constraints.video.mandatory.minAspectRatio = 1.77;
        break;
        // 4:3
    case '960':
        constraints.video.mandatory.minWidth = 960;
        constraints.video.mandatory.minHeight = 720;
        break;
    case '640':
    case 'vga':
        constraints.video.mandatory.minWidth = 640;
        constraints.video.mandatory.minHeight = 480;
        break;
    case '320':
        constraints.video.mandatory.minWidth = 320;
        constraints.video.mandatory.minHeight = 240;
        break;
    default:
        if (navigator.userAgent.indexOf('Android') != -1) {
            constraints.video.mandatory.minWidth = 320;
            constraints.video.mandatory.minHeight = 240;
            constraints.video.mandatory.maxFrameRate = 15;
        }
        break;
    }

    if (bandwidth) { // doesn't work currently, see webrtc issue 1846
        if (!constraints.video) constraints.video = {mandatory: {}};//same behaviour as true
        constraints.video.optional = [{bandwidth: bandwidth}];
    }
    if (fps) { // for some cameras it might be necessary to request 30fps
        // so they choose 30fps mjpg over 10fps yuy2
        if (!constraints.video) constraints.video = {mandatory: {}};// same behaviour as tru;
        constraints.video.mandatory.minFrameRate = fps;
    }

    try {
        RTC.getUserMedia(constraints,
                function (stream) {
                    console.log('onUserMediaSuccess');
                    $(document).trigger('mediaready.jingle', [stream]);
                },
                function (error) {
                    console.warn('Failed to get access to local media. Error ', error);
                    $(document).trigger('mediafailure.jingle');
                });
    } catch (e) {
        console.error('GUM failed: ', e);
        $(document).trigger('mediafailure.jingle');
    }
}
<commit_msg>update format per discussion on https://codereview.chromium.org/23431018/<commit_after>/* jshint -W117 */
function TraceablePeerConnection(ice_config, constraints) {
    var self = this;
    var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
    this.peerconnection = new RTCPeerconnection(ice_config, constraints);
    this.updateLog = [];
    this.stats = {};
    this.statsinterval = null;
    this.maxstats = 300; // limit to 300 values, i.e. 5 minutes; set to 0 to disable

    // override as desired
    this.trace = function(what, info) {
        //console.warn('WTRACE', what, info);
        self.updateLog.push({
            time: new Date(),
            type: what,
            value: info || ""
        });
    };
    this.onicecandidate = null;
    this.peerconnection.onicecandidate = function (event) {
        self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
        if (self.onicecandidate !== null) {
            self.onicecandidate(event);
        }
    };
    this.onaddstream = null;
    this.peerconnection.onaddstream = function (event) {
        self.trace('onaddstream', event.stream.id);
        if (self.onaddstream !== null) {
            self.onaddstream(event);
        }
    };
    this.onremovestream = null;
    this.peerconnection.onremovestream = function (event) {
        self.trace('onremovestream', event.stream.id);
        if (self.onremovestream !== null) {
            self.onremovestream(event);
        }
    };
    this.onsignalingstatechange = null;
    this.peerconnection.onsignalingstatechange = function (event) {
        self.trace('onsignalingstatechange', event.srcElement.signalingState);
        if (self.onsignalingstatechange !== null) {
            self.onsignalingstatechange(event);
        }
    };
    this.oniceconnectionstatechange = null;
    this.peerconnection.oniceconnectionstatechange = function (event) {
        self.trace('oniceconnectionstatechange', event.srcElement.iceConnectionState);
        if (self.oniceconnectionstatechange !== null) {
            self.oniceconnectionstatechange(event);
        }
    };
    this.onnegotiationneeded = null;
    this.peerconnection.onnegotiationneeded = function (event) {
        self.trace('onnegotiationneeded');
        if (self.onnegotiationneeded !== null) {
            self.onnegotiationneeded(event);
        }
    };
    self.ondatachannel = null;
    this.peerconnection.ondatachannel = function (event) {
        self.trace('ondatachannel', event);
        if (self.ondatachannel !== null) {
            self.ondatachannel(event);
        }
    }
    this.statsinterval = window.setInterval(function() {
        self.peerconnection.getStats(function(stats) {
            var results = stats.result();
            for (var i = 0; i < results.length; ++i) {
                //console.log(results[i].type, results[i].id, results[i].names())
                var now = new Date();
                results[i].names().forEach(function (name) {
                    var id = results[i].id + '-' + name;
                    if (!self.stats[id]) {
                        self.stats[id] = {
                            startTime: now,
                            endTime: now,
                            values: [],
                            times: []
                        };
                    }
                    self.stats[id].values.push(results[i].stat(name));
                    self.stats[id].times.push(now.getTime());
                    if (self.stats[id].values.length > self.maxstats) {
                        self.stats[id].values.shift();
                        self.stats[id].times.shift();
                    }
                    self.stats[id].endTime = now;
                });
            }
        });

    }, 1000);
};

dumpSDP = function(description) {
    return 'type: ' + description.type + '\r\n' + description.sdp;
}

TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() { return this.peerconnection.localDescription; });
TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() { return this.peerconnection.remoteDescription; });

TraceablePeerConnection.prototype.addStream = function (stream) {
    this.trace('addStream', stream.id);
    this.peerconnection.addStream(stream);
};

TraceablePeerConnection.prototype.removeStream = function (stream) {
    this.trace('removeStream', stream.id);
    this.peerconnection.removeStream(stream);
};

TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
    this.trace('createDataChannel', label, opts);
    this.peerconnection.createDataChannel(label, opts);
}

TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
    var self = this;
    this.trace('setLocalDescription', dumpSDP(description));
    this.peerconnection.setLocalDescription(description,
        function () {
            self.trace('setLocalDescriptionOnSuccess');
            successCallback();
        },
        function (err) {
            self.trace('setLocalDescriptionOnFailure', err);
            failureCallback(err);
        }
    );
    if (this.statsinterval === null && this.maxstats > 0) {
        // start gathering stats
        this.statsinterval = window.setInterval(this.dumpStats, 1000);
    }
};

TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
    var self = this;
    this.trace('setRemoteDescription', dumpSDP(description));
    this.peerconnection.setRemoteDescription(description,
        function () {
            self.trace('setRemoteDescriptionOnSuccess');
            successCallback();
        },
        function (err) {
            self.trace('setRemoteDescriptionOnFailure', err);
            failureCallback(err);
        }
    );
    if (this.statsinterval === null && this.maxstats > 0) {
        // start gathering stats
        this.statsinterval = window.setInterval(this.dumpStats, 1000);
    }
};

TraceablePeerConnection.prototype.close = function () {
    this.trace('stop');
    if (this.statsinterval !== null) {
        window.clearInterval(this.statsinterval);
        this.statsinterval = null;
    }
    this.peerconnection.close();
};

TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
    var self = this;
    this.trace('createOffer', JSON.stringify(constraints, null, ' '));
    this.peerconnection.createOffer(
        function (offer) {
            self.trace('createOfferOnSuccess', dumpSDP(offer));
            successCallback(offer);
        },
        function(err) {
            self.trace('createOfferOnFailure', err);
            failureCallback(err);
        },
        constraints
    );
};

TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
    var self = this;
    this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
    this.peerconnection.createAnswer(
        function (answer) {
            self.trace('createAnswerOnSuccess', dumpSDP(answer));
            successCallback(answer);
        },
        function(err) {
            self.trace('createAnswerOnFailure', err);
            failureCallback(err);
        },
        constraints
    );
};

TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
    var self = this;
    this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
    this.peerconnection.addIceCandidate(candidate);
    /* maybe later
    this.peerconnection.addIceCandidate(candidate,
        function () {
            self.trace('addIceCandidateOnSuccess');
            successCallback();
        },
        function (err) {
            self.trace('addIceCandidateOnFailure', err);
            failureCallback(err);
        }
    );
    */
};

TraceablePeerConnection.prototype.getStats = function(callback) {
    this.peerconnection.getStats(callback);
};

TraceablePeerConnection.prototype.dumpStats = function(stats) {
    var self = this;
    var results = stats.result();
    for (var i = 0; i < results.length; ++i) {
        //console.log(results[i].type, results[i].id, results[i].names())
        var now = new Date();
        results[i].names().forEach(function (name) {
            var id = results[i].id + '-' + name;
            if (!self.stats[id]) {
                self.stats[id] = {
                    startTime: now,
                    endTime: now,
                    values: []
                };
            }
            self.stats[id].values.push(results[i].stat(name));
            if (self.stats[id].values.length > self.maxstats) {
                self.stats[id].values.shift();
            }
            self.stats[id].endTime = now;
        });
    }
};

// mozilla chrome compat layer -- very similar to adapter.js
function setupRTC() {
    var RTC = null;
    if (navigator.mozGetUserMedia) {
        console.log('This appears to be Firefox');
        var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
        if (version >= 22) {
            RTC = {
                peerconnection: mozRTCPeerConnection,
                browser: 'firefox',
                getUserMedia: navigator.mozGetUserMedia.bind(navigator),
                attachMediaStream: function (element, stream) {
                    element[0].mozSrcObject = stream;
                    element[0].play();
                },
                pc_constraints: {}
            };
            if (!MediaStream.prototype.getVideoTracks)
                MediaStream.prototype.getVideoTracks = function () { return []; };
            if (!MediaStream.prototype.getAudioTracks)
                MediaStream.prototype.getAudioTracks = function () { return []; };
            RTCSessionDescription = mozRTCSessionDescription;
            RTCIceCandidate = mozRTCIceCandidate;
        }
    } else if (navigator.webkitGetUserMedia) {
        console.log('This appears to be Chrome');
        RTC = {
            peerconnection: webkitRTCPeerConnection,
            browser: 'chrome',
            getUserMedia: navigator.webkitGetUserMedia.bind(navigator),
            attachMediaStream: function (element, stream) {
                element.attr('src', webkitURL.createObjectURL(stream));
            },
            // DTLS should now be enabled by default but..
            pc_constraints: {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]}
        };
        if (navigator.userAgent.indexOf('Android') != -1) {
            RTC.pc_constraints = {}; // disable DTLS on Android
        }
        if (!webkitMediaStream.prototype.getVideoTracks) {
            webkitMediaStream.prototype.getVideoTracks = function () {
                return this.videoTracks;
            };
        }
        if (!webkitMediaStream.prototype.getAudioTracks) {
            webkitMediaStream.prototype.getAudioTracks = function () {
                return this.audioTracks;
            };
        }
    }
    if (RTC === null) {
        try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
    }
    return RTC;
}

function getUserMediaWithConstraints(um, resolution, bandwidth, fps) {
    var constraints = {audio: false, video: false};

    if (um.indexOf('video') >= 0) {
        constraints.video = {mandatory: {}};// same behaviour as true
    }
    if (um.indexOf('audio') >= 0) {
        constraints.audio = {};// same behaviour as true
    }
    if (um.indexOf('screen') >= 0) {
        constraints.video = {
            "mandatory": {
                "chromeMediaSource": "screen"
            }
        };
    }

    if (resolution && !constraints.video) {
        constraints.video = {mandatory: {}};// same behaviour as true
    }
    // see https://code.google.com/p/chromium/issues/detail?id=143631#c9 for list of supported resolutions
    switch (resolution) {
    // 16:9 first
    case '1080':
    case 'fullhd':
        constraints.video.mandatory.minWidth = 1920;
        constraints.video.mandatory.minHeight = 1080;
        constraints.video.mandatory.minAspectRatio = 1.77;
        break;
    case '720':
    case 'hd':
        constraints.video.mandatory.minWidth = 1280;
        constraints.video.mandatory.minHeight = 720;
        constraints.video.mandatory.minAspectRatio = 1.77;
        break;
    case '360':
        constraints.video.mandatory.minWidth = 640;
        constraints.video.mandatory.minHeight = 360;
        constraints.video.mandatory.minAspectRatio = 1.77;
        break;
    case '180':
        constraints.video.mandatory.minWidth = 320;
        constraints.video.mandatory.minHeight = 180;
        constraints.video.mandatory.minAspectRatio = 1.77;
        break;
        // 4:3
    case '960':
        constraints.video.mandatory.minWidth = 960;
        constraints.video.mandatory.minHeight = 720;
        break;
    case '640':
    case 'vga':
        constraints.video.mandatory.minWidth = 640;
        constraints.video.mandatory.minHeight = 480;
        break;
    case '320':
        constraints.video.mandatory.minWidth = 320;
        constraints.video.mandatory.minHeight = 240;
        break;
    default:
        if (navigator.userAgent.indexOf('Android') != -1) {
            constraints.video.mandatory.minWidth = 320;
            constraints.video.mandatory.minHeight = 240;
            constraints.video.mandatory.maxFrameRate = 15;
        }
        break;
    }

    if (bandwidth) { // doesn't work currently, see webrtc issue 1846
        if (!constraints.video) constraints.video = {mandatory: {}};//same behaviour as true
        constraints.video.optional = [{bandwidth: bandwidth}];
    }
    if (fps) { // for some cameras it might be necessary to request 30fps
        // so they choose 30fps mjpg over 10fps yuy2
        if (!constraints.video) constraints.video = {mandatory: {}};// same behaviour as tru;
        constraints.video.mandatory.minFrameRate = fps;
    }

    try {
        RTC.getUserMedia(constraints,
                function (stream) {
                    console.log('onUserMediaSuccess');
                    $(document).trigger('mediaready.jingle', [stream]);
                },
                function (error) {
                    console.warn('Failed to get access to local media. Error ', error);
                    $(document).trigger('mediafailure.jingle');
                });
    } catch (e) {
        console.error('GUM failed: ', e);
        $(document).trigger('mediafailure.jingle');
    }
}
<|endoftext|>


<commit_before>$(document).ready(function () {
    //object of array hirigana
    var hiragana = {};
    hiragana.a = ["あ", "か", "さ", "た", "な", "は", "ま", "や", "ら", "わ", "が", "ざ", "だ", "ば", "ぱ"];
    hiragana.i = ["い", "き", "し", "ち", "に", "ひ", "み", " ", "り", " ", "ぎ", "じ", "ぢ", "び", "ぴ"];
    hiragana.u = ["う", "く", "す", "つ", "ぬ", "ふ", "む", "ゆ", "る", " ", "ぐ", "ず", "づ", "ぶ", "ぷ"];
    hiragana.e = ["え", "け", "せ", "て", "ね", "へ", "め", " ", "れ", " ", 　"げ", "ぜ", "で", "べ", "ぺ"];
    hiragana.o = ["お", "こ", "そ", "と", "の", "ほ", "も", "よ", "ろ", "を", "ご", "ぞ", "ど", "ぼ", "ぽ"];
    hiragana.change = function (input, output, initVowel, desiredVowel) {
        var x = hiragana[initVowel].indexOf(input);
        console.log(x);
        output = hiragana[desiredVowel][x];
        console.log(output); //just set it to return
    }

    var groupOne = ["う", "く", "ぐ", "す", "つ", "ぬ", "ぶ", "む", "る"]
    var groupTwo = ["い", "き", "し", "ち", "に", "ひ", "み", "り", "え", "け", "せ", "て", "ね", "へ", "め", "れ", "ぎ", "じ", "び", "ぴ", "げ", "ぜ", "で", "べ", "ぺ"]
    var groupThree = ["来", "くる", "する"];

    //check if in array
    function isInArray(array, search) {
        return array.indexOf(search) >= 0;
    }

    //add input to the page
    function printPage(id, input) {
        $("#" + id).replaceWith("" + input + "");
    }

    //Click the button to get the form value.
    $("#submit").click(function () {
        var verb = {};
        //put an if check here for masu? LATER
        verb.group = "";
        verb.u = $('#enter').val();
        verb.end = verb.u.slice(-1);
        verb.endTwo = verb.u.slice(-2, -1);
        verb.stem = "";
        verb.masu = "";
        verb.preMasu = "";
        verb.ta = "";
        verb.te = "";

        printPage("u", verb.u);

        verb.getGroup = function () {
            if (isInArray(groupThree, verb.u)) {
                verb.group = "3";
            } else if (verb.end === "る" && isInArray(groupTwo, verb.endTwo)) {
                verb.group = "2";
            } else if (isInArray(groupOne, verb.end)) {
                verb.group = "1";
            }
            printPage("group", verb.group);
        }

        verb.getStem = function () {
            if (verb.group === "1") {
                /* function checkChangePreMasu(a, b) {
                    if (verb.end === a) {
                        verb.preMasu = b;
                        printPage("ta", verb.preMasu);
                    }
                }
                 checkChangePreMasu("む", "み");
                checkChangePreMasu("ぬ", "に");
                checkChangePreMasu("ぶ", "び");
                checkChangePreMasu("う", "い");
                checkChangePreMasu("つ", "ち");
                checkChangePreMasu("る", "り");
                checkChangePreMasu("く", "き");
                checkChangePreMasu("ぐ", "ぎ");
                checkChangePreMasu("す", "し"); */

                hiragana.change(verb["end"], verb["preMasu"], "u", "i");
                console.log(verb.preMasu);
                verb.stem = verb.u.slice(0, -1) + verb.preMasu;

            }
            if (verb.group === "2") {
                verb.stem = verb.u.slice(0, -1);
            }

            if (verb.group === "3") {

            }
            printPage("stem", verb.stem);
        }

        verb.getMasu = function () {
            verb.masu = verb.stem + "ます";
            printPage("masu", verb.masu);
        }
        verb.getTe = function () {

            //Check if it's a group three verb and conjugate accordingly.
            if (verb.group === "3" || verb.group === "2") {
                verb.te = verb.stem + "て";
            }
            //Since group three verbs can possibly intended to be group one verbs, we start a new if block.

            //We'll assume everything else that's not group one is a group two verb.

            //Check if the verb is possibly an exception to the usual group rules. We can add more else ifs for more exceptions and use printType and specify. Use either the group one method (preMasu.change) or the group two function verb.printStemTe accordingly.

        };
        verb.getGroup();
        verb.getStem();
        verb.getMasu();
    });
});<commit_msg>te and ta working<commit_after>$(document).ready(function () {
    //object of array hirigana
    var hiragana = {};
    hiragana.a = ["あ", "か", "さ", "た", "な", "は", "ま", "や", "ら", "わ", "が", "ざ", "だ", "ば", "ぱ"];
    hiragana.i = ["い", "き", "し", "ち", "に", "ひ", "み", " ", "り", " ", "ぎ", "じ", "ぢ", "び", "ぴ"];
    hiragana.u = ["う", "く", "す", "つ", "ぬ", "ふ", "む", "ゆ", "る", " ", "ぐ", "ず", "づ", "ぶ", "ぷ"];
    hiragana.e = ["え", "け", "せ", "て", "ね", "へ", "め", " ", "れ", " ", 　"げ", "ぜ", "で", "べ", "ぺ"];
    hiragana.o = ["お", "こ", "そ", "と", "の", "ほ", "も", "よ", "ろ", "を", "ご", "ぞ", "ど", "ぼ", "ぽ"];
    hiragana.teOne = ["み", "に", "び"]
    hiragana.teTwo = ["い", "ち", "り"]
    hiragana.change = function (input, initVowel, desiredVowel) {
        var x = hiragana[initVowel].indexOf(input);
        console.log(x);
        return hiragana[desiredVowel][x];

    }

    var groupThree = ["くる", "する"];

    //check if in array
    function isInArray(array, search) {
        return array.indexOf(search) >= 0;
    }

    //add input to the page
    function printPage(id, input) {
        $("#" + id).replaceWith("" + input + "");
    }

    //Click the button to get the form value.
    $("#submit").click(function () {
        var verb = {};
        //put an if check here for masu? LATER
        verb.group = "";
        verb.u = $('#enter').val();
        verb.end = verb.u.slice(-1);
        verb.endTwo = verb.u.slice(-2, -1);
        verb.withoutEnd = verb.u.slice(0, -1);
        verb.i = "";
        verb.preMasu = "";
        verb.masu = "";
        verb.ta = "";
        verb.taEnd = "";
        verb.te = "";
        verb.teEnd = "";
        verb.negative = "";

        printPage("u", verb.u);

        verb.getGroup = function () {
            if (isInArray(groupThree, verb.u)) {
                verb.group = "3";
            } else if (verb.end === "る" && (isInArray(hiragana.i, verb.endTwo) || isInArray(hiragana.e, verb.endTwo))) {
                verb.group = "2";
            } else if (isInArray(hiragana.u, verb.end)) {
                verb.group = "1";
            }
            printPage("group", verb.group);
        }

        verb.getI = function () {
            if (verb.group === "1") {
                verb.preMasu = hiragana.change(verb.end, "u", "i");
                verb.i = verb.u.slice(0, -1) + verb.preMasu;

            }
            if (verb.group === "2") {
                verb.i = verb.u.slice(0, -1);
            }

            if (verb.group === "3") {

            }
            printPage("i", verb.i);
        }

        verb.getMasu = function () {
            verb.masu = verb.i + "ます";
            printPage("masu", verb.masu);
        }

        verb.getTe = function () {

            //Check if it's a group three verb and conjugate accordingly.
            if (verb.group === "3" || verb.group === "2") {
                verb.te = verb.i + "て";
            }
            if (verb.group === "1") {
                console.log(verb.preMasu);
                if (isInArray(hiragana.teOne, verb.preMasu)) {
                    verb.teEnd = "んで";
                    console.log(verb.teEnd);
                } else if (isInArray(hiragana.teTwo, verb.preMasu)) {
                    verb.teEnd = "って";
                } else if (verb.preMasu = "き") {
                    verb.teEnd = "いて";
                } else if (verb.preMasu = "ぎ") {
                    verb.teEnd = "いで";
                } else if (verb.preMasu = "し") {
                    verb.teEnd = "して";
                }
                verb.te = verb.withoutEnd + verb.teEnd;
            }
            printPage("te", verb.te);
        };

        verb.getTa = function () {
            if (verb.group === "3" || verb.group === "2") {
                verb.ta = verb.i + "た";
            }
            if (verb.group === "1") {
                console.log(verb.preMasu);
                if (isInArray(hiragana.teOne, verb.preMasu)) {
                    verb.taEnd = "んだ";
                    console.log(verb.teEnd);
                } else if (isInArray(hiragana.teTwo, verb.preMasu)) {
                    verb.taEnd = "った";
                } else if (verb.preMasu = "き") {
                    verb.taEnd = "いた";
                } else if (verb.preMasu = "ぎ") {
                    verb.taEnd = "いだ";
                } else if (verb.preMasu = "し") {
                    verb.taEnd = "した";
                }
                verb.ta = verb.withoutEnd + verb.taEnd;
            }
            printPage("ta", verb.ta);
        };

        verb.getNeg

        verb.getGroup();
        verb.getStem();
        verb.getMasu();
        verb.getTe()
        verb.getTa();
    });
});<|endoftext|>