<commit_before>define([
    'q',
    'knockout',
    'util/galaxy',
    'util/alerts',
    'util/form',
    'store/ProviderTypes',
    'store/Accounts',
    'store/Profiles',
    'store/Zones',
    'api/api'
],
function (Q, ko, $galaxy, alerts, formutils, ProviderTypeStore, AccountStore, ProfileStore, ZoneStore, API) {
    var vm = function () {
        var self = this;

        /*
         *  ==================================================================================
         *   V I E W   V A R I A B L E S
         *  ==================================================================================
         */
        self.selectedAccount = ko.observable(null);
        self.selectedProviderType = ko.observable(null);
        self.accountTitle = ko.observable(null);
        self.currentMode = ko.observable('create');
        self.$galaxy = $galaxy;

        self.ProviderTypeStore = ProviderTypeStore;
        self.AccountStore = AccountStore;
        self.ProfileStore = ProfileStore;
        self.ZoneStore = ZoneStore;

        /*
         *  ==================================================================================
         *   R E G I S T R A T I O N   S E C T I O N
         *  ==================================================================================
         */
        self.id = 'account.detail';
        self.templatePath = 'account.html';
        self.domBindingId = '#account-detail';

        try {
            $galaxy.join(self);
        } catch (ex) {
            console.log(ex);
        }

        /*
         *  ==================================================================================
         *   E V E N T   S U B S C R I P T I O N S
         *  ==================================================================================
         */
        $galaxy.network.subscribe(self.id + '.docked', function (data) {
            ZoneStore.populate();

            ProviderTypeStore.populate().then(function () {
                return AccountStore.populate();
            }).then(function () {
                return ProfileStore.populate();
            }).then(function () {
                self.init(data);
            });
        });

        /*
         *  ==================================================================================
         *   V I E W   M E T H O D S
         *  ==================================================================================
         */

        self.init = function (data) {
            var account = null;
            var provider_type = null;

            if (data.hasOwnProperty('account')) {
                account = AccountStore.collection().filter(function (a) {
                    return a.id === parseInt(data.account, 10);
                })[0];

                self.accountTitle(account.title);
                self.selectedAccount(account);
            } else {
                self.accountTitle('New Account');

                $('#account_title').val('');
                $('#account_description').val('');
                $('#account_id').val('');
                $('#access_key_id').val('');
                $('#secret_access_key').val('');
                $('#keypair').val('');
                $('#default_availability_zone').val('');
                $('#route53_domain').val('');
                $('#private_key_file').val('');
            }

            if (data.hasOwnProperty('type')) {
                provider_type = ProviderTypeStore.collection().filter(function (a) {
                    return a.id === parseInt(data.type, 10);
                })[0];

                self.selectedProviderType(provider_type);
            }

            if (account && account.hasOwnProperty('id')) {
                $('#account_provider').val(account.provider_type);
                $('#account_title').val(account.title);
                $('#account_description').val(account.description);
                $('#account_id').val(account.account_id);
                $('#default_availability_zone').val(account.default_availability_zone);
                $('#private_key_file').val(account.yaml);
                $('#private_key_file').attr('disabled', 'disabled');

                self.currentMode('edit');
            } else if (provider_type && provider_type.hasOwnProperty('id')) {
                $('#private_key_file').removeAttr('disabled');
                $('#account_provider').val(provider_type.id);
                self.currentMode('create');
            }
        };

        self.saveAccount = function (model, evt) {
            if (self.currentMode() === 'create') {
                self.createAccount(model, evt);
            } else {
                self.updateAccount(model, evt);
            }
        };

        self.createAccount = function (model, evt) {
            var record = formutils.collectFormFields(evt.target.form), account = {};

            account.provider_type = record.account_provider.value;
            account.title = record.account_title.value;
            account.description = record.account_description.value;
            account.default_availability_zone = record.default_availability_zone.value;
            account.account_id = record.account_id.value;
            account.access_key_id = record.access_key_id.value;
            account.secret_access_key = record.secret_access_key.value;
            account.keypair = record.keypair.value;
            account.route53_domain = record.route53_domain.value;
            account.private_key = record.private_key_file.value;

            API.Accounts.save(account).then(function (newAccount) {
                AccountStore.add(newAccount);
                $galaxy.transport('account.securitygroup');

                alerts.showMessage('#success', 'Provider account successfully created. You are strongly urged to specify at least default security group for this provider so that hosts can successfully be provisioned.', true, 10000);
            });
        };

        self.updateAccount = function (model, evt) {
            var record = formutils.collectFormFields(evt.target.form);
            var account = {};

            // Update property values with those submitted from form
            account.id = self.selectedAccount().id;
            account.url = self.selectedAccount().url;
            account.provider_type = record.account_provider.value;
            account.title = record.account_title.value;
            account.description = record.account_description.value;
            account.default_availability_zone = record.default_availability_zone.value;

            // PATCH the update, and on success, replace the current item in the store with new one
            API.Accounts.update(account).then(function () {
                $galaxy.transport('account.list');
            }).catch(function (err) {
                console.log(err);
            });
        };

        self.cancelChanges = function (model, evt) {
            $galaxy.transport('account.list');
        };
    };
    return new vm();
});
<commit_msg>Fixes issue: We need some help or warning messages when creating a new provider to let the user know that without security groups that open SSH and Salt ports then stacks will always fail<commit_after>define([
    'q',
    'knockout',
    'util/galaxy',
    'util/alerts',
    'util/form',
    'store/ProviderTypes',
    'store/Accounts',
    'store/Profiles',
    'store/Zones',
    'api/api'
],
function (Q, ko, $galaxy, alerts, formutils, ProviderTypeStore, AccountStore, ProfileStore, ZoneStore, API) {
    var vm = function () {
        var self = this;

        /*
         *  ==================================================================================
         *   V I E W   V A R I A B L E S
         *  ==================================================================================
         */
        self.selectedAccount = ko.observable(null);
        self.selectedProviderType = ko.observable(null);
        self.accountTitle = ko.observable(null);
        self.currentMode = ko.observable('create');
        self.$galaxy = $galaxy;

        self.ProviderTypeStore = ProviderTypeStore;
        self.AccountStore = AccountStore;
        self.ProfileStore = ProfileStore;
        self.ZoneStore = ZoneStore;

        /*
         *  ==================================================================================
         *   R E G I S T R A T I O N   S E C T I O N
         *  ==================================================================================
         */
        self.id = 'account.detail';
        self.templatePath = 'account.html';
        self.domBindingId = '#account-detail';

        try {
            $galaxy.join(self);
        } catch (ex) {
            console.log(ex);
        }

        /*
         *  ==================================================================================
         *   E V E N T   S U B S C R I P T I O N S
         *  ==================================================================================
         */
        $galaxy.network.subscribe(self.id + '.docked', function (data) {
            ZoneStore.populate();

            ProviderTypeStore.populate().then(function () {
                return AccountStore.populate();
            }).then(function () {
                return ProfileStore.populate();
            }).then(function () {
                self.init(data);
            });
        });

        /*
         *  ==================================================================================
         *   V I E W   M E T H O D S
         *  ==================================================================================
         */

        self.init = function (data) {
            var account = null;
            var provider_type = null;

            if (data.hasOwnProperty('account')) {
                account = AccountStore.collection().filter(function (a) {
                    return a.id === parseInt(data.account, 10);
                })[0];

                self.accountTitle(account.title);
                self.selectedAccount(account);
            } else {
                self.accountTitle('New Account');

                $('#account_title').val('');
                $('#account_description').val('');
                $('#account_id').val('');
                $('#access_key_id').val('');
                $('#secret_access_key').val('');
                $('#keypair').val('');
                $('#default_availability_zone').val('');
                $('#route53_domain').val('');
                $('#private_key_file').val('');
            }

            if (data.hasOwnProperty('type')) {
                provider_type = ProviderTypeStore.collection().filter(function (a) {
                    return a.id === parseInt(data.type, 10);
                })[0];

                self.selectedProviderType(provider_type);
            }

            if (account && account.hasOwnProperty('id')) {
                $('#account_provider').val(account.provider_type);
                $('#account_title').val(account.title);
                $('#account_description').val(account.description);
                $('#account_id').val(account.account_id);
                $('#default_availability_zone').val(account.default_availability_zone);
                $('#private_key_file').val(account.yaml);
                $('#private_key_file').attr('disabled', 'disabled');

                self.currentMode('edit');
            } else if (provider_type && provider_type.hasOwnProperty('id')) {
                $('#private_key_file').removeAttr('disabled');
                $('#account_provider').val(provider_type.id);
                self.currentMode('create');
            }
        };

        self.saveAccount = function (model, evt) {
            if (self.currentMode() === 'create') {
                self.createAccount(model, evt);
            } else {
                self.updateAccount(model, evt);
            }
        };

        self.createAccount = function (model, evt) {
            var record = formutils.collectFormFields(evt.target.form), account = {};

            account.provider_type = record.account_provider.value;
            account.title = record.account_title.value;
            account.description = record.account_description.value;
            account.default_availability_zone = record.default_availability_zone.value;
            account.account_id = record.account_id.value;
            account.access_key_id = record.access_key_id.value;
            account.secret_access_key = record.secret_access_key.value;
            account.keypair = record.keypair.value;
            account.route53_domain = record.route53_domain.value;
            account.private_key = record.private_key_file.value;

            API.Accounts.save(account).then(function (newAccount) {
                AccountStore.add(newAccount);
                $galaxy.transport('account.securitygroup');

                alerts.showMessage('#success', 'Provider account successfully created. You are strongly urged to specify at least one default security group for this provider that opens ports for SSH and Salt so that hosts can successfully be provisioned.', true, 10000);
            });
        };

        self.updateAccount = function (model, evt) {
            var record = formutils.collectFormFields(evt.target.form);
            var account = {};

            // Update property values with those submitted from form
            account.id = self.selectedAccount().id;
            account.url = self.selectedAccount().url;
            account.provider_type = record.account_provider.value;
            account.title = record.account_title.value;
            account.description = record.account_description.value;
            account.default_availability_zone = record.default_availability_zone.value;

            // PATCH the update, and on success, replace the current item in the store with new one
            API.Accounts.update(account).then(function () {
                $galaxy.transport('account.list');
            }).catch(function (err) {
                console.log(err);
            });
        };

        self.cancelChanges = function (model, evt) {
            $galaxy.transport('account.list');
        };
    };
    return new vm();
});
<|endoftext|>


<commit_before>
(function (window) {

  var undefined; // "undefined", deixar essa var sem valor !!!
  function _isStr( val ){ return typeof val === 'string'; }
  function _is$( val ){ return val instanceof $; }
  function _isUndefined( val ){ return val === undefined; }

  //===========================================================================
  //          Function prototype

  var FunctionProto = window.Function.prototype;
  if( !FunctionProto.bind ) FunctionProto.bind = function(that){
    var me = this, arr = Array.prototype.slice(arguments,1);
    return function(){
      return me.apply( that, arr );
    };
  };

  //===========================================================================
  //          EventTarget prototype

  var EventTypeProto = window.EventTarget.prototype;
  EventTypeProto.off = function (eventName, callback, useCapture) {
    return this.removeEventListener(eventName, callback, useCapture);
  };
  EventTypeProto.on = function (eventName, callback, useCapture) {
    this.addEventListener(eventName, callback, useCapture);
    return EventTypeProto.off.bind(this, eventName, callback, useCapture);
  };
  EventTypeProto.one = function (eventName, callback, useCapture, times) {
    if (!times)
      times = 1;
    else if (times < 1)
      return function () {};
    var _retirar = null;
    var _func = function () {
      callback();
      if (!--times)
        _retirar();
    };
    return _retirar = this.on(eventName, _func, useCapture);
  };

  EventTypeProto.bind = EventTypeProto.on;
  EventTypeProto.unbind = EventTypeProto.off;

  //===========================================================================
  //          Element prototype

  var ElementProto = window.Element.prototype;
  ElementProto.find = function (str) {
    var nodeList = this.querySelectorAll(str), len = nodeList.length;
    var arr = [];
    for (var i = 0; i < len; i++)
      arr.push(nodeList[i]);
    return $(arr);
  };
  if ('classList' in ElementProto) {
    ElementProto.hasClass = function () {
      return this.classList.contains.apply(this.classList, arguments );
    };
    ElementProto.addClass = function () {
      this.classList.add.apply(this.classList, arguments );
      return this;
    };
    ElementProto.removeClass = function () {
      this.classList.remove.apply(this.classList, arguments );
      return this;
    };
  } else {
    ElementProto.hasClass = function (str) {
      return new RegExp('\\b' + str + '\\b').test(this.className);
    };
    ElementProto.addClass = function () {
      var i = arguments.length, str;
      while( i-- ){
        str = arguments[i];
        if( !this.hasClass(str) ) this.className += ' ' + str;
      }
      return this;
    };
    ElementProto.removeClass = function (str) {
      var i = arguments.length, str;
      while( i-- ){
        str = arguments[i];
        this.className = this.className.replace(new RegExp('\\b'+ str+'\\b', 'g'), '');
      }
      return this;
    };
  }
  ElementProto.toggleClass = function (str) {
    if (this.hasClass(str))
      this.removeClass(str);
    else
      this.addClass(str);
    return this;
  };
  ElementProto.text = function (str){
    if( str === undefined ) return this.textContent;
    this.textContent = str;
    return this;
  };
  ElementProto.empty = function(){
    while(this.hasChildNodes()) {
      this.removeChild(this.firstChild);
    }
    return this;
  };
  ElementProto.html = function (str){
    if( str === undefined ) return this.innerHTML;
    this.innerHTML = str;
    return this;
  };
  ElementProto.attr = function( str, val ){
    if( str instanceof Object ){
      for( var g in str ){
        this.setAttribute( g, str[g] );
      }
      return this;
    }
    if( val === undefined ) return this.getAttribute( str );
    this.setAttribute( str, val );
    return this;
  };
  ElementProto.removeAttr = function( str ){
    this.removeAttribute(str);
    return this;
  };
  ElementProto.append = function( el ){
    if( el instanceof $ ){
      var len = el.length, i = len;
      while( i-- ) this.appendChild( el[len-i-1] );
    }else{
      this.appendChild( _idStr(el)? _createElFromStr(el) : el );
    }
    return this;
  };
  if(!ElementProto.remove) ElementProto.remove = function(){
    this.parentNode.removeChild( this );
    return this;
  };
  ElementProto.clone = function( val ){
    return this.cloneNode( val );
  };
  ElementProto.parent = function(){
    return this.parentNode;
  };
  ElementProto.replaceWith = function( el ){
    el = _idStr(el)? _createElFromStr(el) : el;
    this.parent().replaceChild( el, this );
    return el;
  };
  ElementProto.css = function( obj, val ){
    if( typeof obj === 'string' ){
      if( val === undefined )
        return window.getComputedStyle(this)[obj];
      this.style[obj] = val;
    }
    for( var g in obj ){
      this.style[g] = obj[g];
    }
    return this;
  };

  //===========================================================================
  //          $ function

  function $(param) {
    if (!(this instanceof $))
      return new $(param);
    if (param instanceof $)
      return param;
    if (typeof param === 'string')
      return ElementProto.find.call(document, param);
    if (typeof param === 'undefined')
      param = [];
    if (!(param instanceof Array))
      param = [param];

    for (var g in param)
      this.push(param[g]);
    if (!this.length)
      this.length = 0;

    _defineProperty(this, 5, 'length');
    return this;
  };
  var proto = ($.prototype = new Array());

  var funcs = [
      'bind',
      'unbind',
      'on',
      'off',
      'one',
      'find',
      'hasClass',
      'addClass',
      'removeClass',
      'toggleClass',
      'text',
      'empty',
      'attr',
      'removeAttr',
      'children',
      'remove',
      'clone',
      'parent',
      'append',
      'eq',
      'replaceWith',
      'css',
      'chidren',
      'html'
    ], funcsI = funcs.length;

    // comportamento padrão;
  while( funcsI-- ){
     _normalElementCall(proto, funcs[funcsI]);
  }

    //  Sobreescrever as funções que precisam de comportamento 'especial':

  proto.find = function (str) {
    var res = _forEachApply(this, ElementProto.find, [str]);
    var obj = $(), len = res.length;
    for (var i = 0; i < len; i++) {
      var resI = res[i], lenI = resI.length;
      for (var j = 0; j < lenI; j++) {
        obj.push(resI[j]);
      }
    }
    return obj;
  };
  proto.hasClass = function(){
    var res = _forEachApply(this, ElementProto.hasClass, arguments), i = res.length;
    while( i-- ) if( !res[i] ) return false;
    return true;
  };
  proto.text = function( str ){
    if( !this.length ) return '';
    var res = _forEachApply( str===undefined?[this[0]]:this , ElementProto.text, [str]);
    return res[0];
  };
  proto.chidren = function(str){
    if( str ) return $(_forEachApply(this, ElementProto.find, str));
    var res = [], len = this.length, i = len, j, lenJ, arrJ;
    while( i-- ){
      arrJ = this[len-i-1].children;
      j = lenJ = arrJ.length;
      while( j-- ){
        res.push( arrJ[lenJ-j-1] );
      }
    }
    return $( _removeEquals( res ) );
  };
  proto.html = function(str){
    if( !this.length ) return '';
    if( str ){
      _forEachApply(this, ElementProto.html, str);
      return this;
    }
    return this[0].html();
  };
  proto.eq = function(val){
    return $([ this[val] ]);
  };
  proto.clone = function(){
    return $( _forEachApply(this, ElementProto.clone, [true]) );
  };
  proto.parent = function(){
    return $( _removeEquals(  _forEachApply(this, ElementProto.parent) ) );
  };
  proto.replaceWith = function(){
    return $( _removeEquals(  _forEachApply(this, ElementProto.replaceWith, arguments) ) );
  };

    // bloquear a iteração desses elementos:
  funcsI = funcs.length;
  while( funcsI-- ){
    _defineProperty(proto, 5, funcs[funcsI]);
  }

  //===========================================================================
  //    Funções auxiliares

  function _normalElementCall(proto, funcName){
    proto[funcName] = function(){
      _forEachApply(this, ElementProto[funcName], arguments);
      return this;
    };
  }
  function _forEachApply(arr, func, arrApply) {
    var ret = [], len = arr.length;
    for (var i = 0; i < len; i++)
      ret.push(func.apply(arr[i], arrApply));
    return ret;
  }
  function _defineProperty(obj, intConf, prop ) {
    if (!intConf)
      intConf = 0;

    Object.defineProperty(obj, prop, {
      configurable: !!(1 & intConf),
      enumerable: !!(2 & intConf),
      writable: !!(4 & intConf),
      iterable: !!(8 & intConf)
        //value: conf.value,
        //get: conf.get,
        //set: conf.set
    });
  }
  function _removeEquals( arr ){
    var len = arr.length, i = len, j;
    while(i--){
      j = len - i;
      while(--j){
        if( arr[i] === arr[i+j] ) arr.splice(i+j, 1);
      }
    }
    return arr;
  }
  function _createElFromStr( str ){
    var div = document.createElement('div'),
        frag = document.createDocumentFragment(),
        len, i;
    div.innerHTML = str;
    len = i = div.childNodes.length;
    while(i--){
      frag.appendChild( div.childNodes[len-i-1] );
    }
    return frag;
  }

  //===========================================================================
  //    Publicando funções

  if (!window.$)
    window.$ = $;
  if (!window.$$)
    window.$$ = $;

})(window);
<commit_msg>Corrigindo falha no IE: add "(window.EventTarget || window.Node)" para pegar o prototipo de "EventTarget" (para addEventListener)<commit_after>
(function (window) {

  var undefined; // "undefined", deixar essa var sem valor !!!
  function _isStr( val ){ return typeof val === 'string'; }
  function _is$( val ){ return val instanceof $; }
  function _isUndefined( val ){ return val === undefined; }

  //===========================================================================
  //          Function prototype

  var FunctionProto = window.Function.prototype;
  if( !FunctionProto.bind ) FunctionProto.bind = function(that){
    var me = this, arr = Array.prototype.slice(arguments,1);
    return function(){
      return me.apply( that, arr );
    };
  };

  //===========================================================================
  //          EventTarget prototype

  var EventTypeProto = (window.EventTarget || window.Node).prototype;
  EventTypeProto.off = function (eventName, callback, useCapture) {
    return this.removeEventListener(eventName, callback, useCapture);
  };
  EventTypeProto.on = function (eventName, callback, useCapture) {
    this.addEventListener(eventName, callback, useCapture);
    return EventTypeProto.off.bind(this, eventName, callback, useCapture);
  };
  EventTypeProto.one = function (eventName, callback, useCapture, times) {
    if (!times)
      times = 1;
    else if (times < 1)
      return function () {};
    var _retirar = null;
    var _func = function () {
      callback();
      if (!--times)
        _retirar();
    };
    return _retirar = this.on(eventName, _func, useCapture);
  };

  EventTypeProto.bind = EventTypeProto.on;
  EventTypeProto.unbind = EventTypeProto.off;

  //===========================================================================
  //          Element prototype

  var ElementProto = window.Element.prototype;
  ElementProto.find = function (str) {
    var nodeList = this.querySelectorAll(str), len = nodeList.length;
    var arr = [];
    for (var i = 0; i < len; i++)
      arr.push(nodeList[i]);
    return $(arr);
  };
  if ('classList' in ElementProto) {
    ElementProto.hasClass = function () {
      return this.classList.contains.apply(this.classList, arguments );
    };
    ElementProto.addClass = function () {
      this.classList.add.apply(this.classList, arguments );
      return this;
    };
    ElementProto.removeClass = function () {
      this.classList.remove.apply(this.classList, arguments );
      return this;
    };
  } else {
    ElementProto.hasClass = function (str) {
      return new RegExp('\\b' + str + '\\b').test(this.className);
    };
    ElementProto.addClass = function () {
      var i = arguments.length, str;
      while( i-- ){
        str = arguments[i];
        if( !this.hasClass(str) ) this.className += ' ' + str;
      }
      return this;
    };
    ElementProto.removeClass = function (str) {
      var i = arguments.length, str;
      while( i-- ){
        str = arguments[i];
        this.className = this.className.replace(new RegExp('\\b'+ str+'\\b', 'g'), '');
      }
      return this;
    };
  }
  ElementProto.toggleClass = function (str) {
    if (this.hasClass(str))
      this.removeClass(str);
    else
      this.addClass(str);
    return this;
  };
  ElementProto.text = function (str){
    if( str === undefined ) return this.textContent;
    this.textContent = str;
    return this;
  };
  ElementProto.empty = function(){
    while(this.hasChildNodes()) {
      this.removeChild(this.firstChild);
    }
    return this;
  };
  ElementProto.html = function (str){
    if( str === undefined ) return this.innerHTML;
    this.innerHTML = str;
    return this;
  };
  ElementProto.attr = function( str, val ){
    if( str instanceof Object ){
      for( var g in str ){
        this.setAttribute( g, str[g] );
      }
      return this;
    }
    if( val === undefined ) return this.getAttribute( str );
    this.setAttribute( str, val );
    return this;
  };
  ElementProto.removeAttr = function( str ){
    this.removeAttribute(str);
    return this;
  };
  ElementProto.append = function( el ){
    if( el instanceof $ ){
      var len = el.length, i = len;
      while( i-- ) this.appendChild( el[len-i-1] );
    }else{
      this.appendChild( _idStr(el)? _createElFromStr(el) : el );
    }
    return this;
  };
  if(!ElementProto.remove) ElementProto.remove = function(){
    this.parentNode.removeChild( this );
    return this;
  };
  ElementProto.clone = function( val ){
    return this.cloneNode( val );
  };
  ElementProto.parent = function(){
    return this.parentNode;
  };
  ElementProto.replaceWith = function( el ){
    el = _idStr(el)? _createElFromStr(el) : el;
    this.parent().replaceChild( el, this );
    return el;
  };
  ElementProto.css = function( obj, val ){
    if( typeof obj === 'string' ){
      if( val === undefined )
        return window.getComputedStyle(this)[obj];
      this.style[obj] = val;
    }
    for( var g in obj ){
      this.style[g] = obj[g];
    }
    return this;
  };

  //===========================================================================
  //          $ function

  function $(param) {
    if (!(this instanceof $))
      return new $(param);
    if (param instanceof $)
      return param;
    if (typeof param === 'string')
      return ElementProto.find.call(document, param);
    if (typeof param === 'undefined')
      param = [];
    if (!(param instanceof Array))
      param = [param];

    for (var g in param)
      this.push(param[g]);
    if (!this.length)
      this.length = 0;

    _defineProperty(this, 5, 'length');
    return this;
  };
  var proto = ($.prototype = new Array());

  var funcs = [
      'bind',
      'unbind',
      'on',
      'off',
      'one',
      'find',
      'hasClass',
      'addClass',
      'removeClass',
      'toggleClass',
      'text',
      'empty',
      'attr',
      'removeAttr',
      'children',
      'remove',
      'clone',
      'parent',
      'append',
      'eq',
      'replaceWith',
      'css',
      'chidren',
      'html'
    ], funcsI = funcs.length;

    // comportamento padrão;
  while( funcsI-- ){
     _normalElementCall(proto, funcs[funcsI]);
  }

    //  Sobreescrever as funções que precisam de comportamento 'especial':

  proto.find = function (str) {
    var res = _forEachApply(this, ElementProto.find, [str]);
    var obj = $(), len = res.length;
    for (var i = 0; i < len; i++) {
      var resI = res[i], lenI = resI.length;
      for (var j = 0; j < lenI; j++) {
        obj.push(resI[j]);
      }
    }
    return obj;
  };
  proto.hasClass = function(){
    var res = _forEachApply(this, ElementProto.hasClass, arguments), i = res.length;
    while( i-- ) if( !res[i] ) return false;
    return true;
  };
  proto.text = function( str ){
    if( !this.length ) return '';
    var res = _forEachApply( str===undefined?[this[0]]:this , ElementProto.text, [str]);
    return res[0];
  };
  proto.chidren = function(str){
    if( str ) return $(_forEachApply(this, ElementProto.find, str));
    var res = [], len = this.length, i = len, j, lenJ, arrJ;
    while( i-- ){
      arrJ = this[len-i-1].children;
      j = lenJ = arrJ.length;
      while( j-- ){
        res.push( arrJ[lenJ-j-1] );
      }
    }
    return $( _removeEquals( res ) );
  };
  proto.html = function(str){
    if( !this.length ) return '';
    if( str ){
      _forEachApply(this, ElementProto.html, str);
      return this;
    }
    return this[0].html();
  };
  proto.eq = function(val){
    return $([ this[val] ]);
  };
  proto.clone = function(){
    return $( _forEachApply(this, ElementProto.clone, [true]) );
  };
  proto.parent = function(){
    return $( _removeEquals(  _forEachApply(this, ElementProto.parent) ) );
  };
  proto.replaceWith = function(){
    return $( _removeEquals(  _forEachApply(this, ElementProto.replaceWith, arguments) ) );
  };

    // bloquear a iteração desses elementos:
  funcsI = funcs.length;
  while( funcsI-- ){
    _defineProperty(proto, 5, funcs[funcsI]);
  }

  //===========================================================================
  //    Funções auxiliares

  function _normalElementCall(proto, funcName){
    proto[funcName] = function(){
      _forEachApply(this, ElementProto[funcName], arguments);
      return this;
    };
  }
  function _forEachApply(arr, func, arrApply) {
    var ret = [], len = arr.length;
    for (var i = 0; i < len; i++)
      ret.push(func.apply(arr[i], arrApply));
    return ret;
  }
  function _defineProperty(obj, intConf, prop ) {
    if (!intConf)
      intConf = 0;

    Object.defineProperty(obj, prop, {
      configurable: !!(1 & intConf),
      enumerable: !!(2 & intConf),
      writable: !!(4 & intConf),
      iterable: !!(8 & intConf)
        //value: conf.value,
        //get: conf.get,
        //set: conf.set
    });
  }
  function _removeEquals( arr ){
    var len = arr.length, i = len, j;
    while(i--){
      j = len - i;
      while(--j){
        if( arr[i] === arr[i+j] ) arr.splice(i+j, 1);
      }
    }
    return arr;
  }
  function _createElFromStr( str ){
    var div = document.createElement('div'),
        frag = document.createDocumentFragment(),
        len, i;
    div.innerHTML = str;
    len = i = div.childNodes.length;
    while(i--){
      frag.appendChild( div.childNodes[len-i-1] );
    }
    return frag;
  }

  //===========================================================================
  //    Publicando funções

  if (!window.$)
    window.$ = $;
  if (!window.$$)
    window.$$ = $;

})(window);
<|endoftext|>


<commit_before>/* global done:false */
/* global error:false */
/* global PaymentRequest:false */

/**
 * Initializes the payment request object.
 */
function buildPaymentRequest() {
  if (!window.PaymentRequest) {
    return null;
  }

  var supportedInstruments = [{
    supportedMethods:
      'basic-card',

  }];

  var details = {
    total: {
      label: 'Donation',
      amount: {
        currency: 'USD',
        value: '55.00'
      }
    },
    displayItems: [{
      label: 'Original donation amount',
      amount: {
        currency: 'USD',
        value: '65.00'
      }
    }, {
      label: 'Friends and family discount',
      amount: {
        currency: 'USD',
        value: '-10.00'
      }
    }],
    modifiers: [{
      supportedMethods: 'basic-card',
      total: {
        label: 'Discounted donation',
        amount: {
          currency: 'USD',
          value: '45.00'
        }
      },
      additionalDisplayItems: [{
        label: 'VISA discount',
        amount: {
          currency: 'USD',
          value: '-10.00'
        }
      }],
      data: {
        discountProgramParticipantId: '86328764873265',
        supportedNetworks: ['visa'],
      }
    }]
  };

  var request = null;

  try {
    request = new PaymentRequest(supportedInstruments, details);
    if (request.canMakePayment) {
      request.canMakePayment().then(function(result) {
        info(result ? "Can make payment" : "Cannot make payment");
      }).catch(function(err) {
        error(err);
      });
    }
  } catch (e) {
    error('Developer mistake: \'' + e + '\'');
  }

  return request;
}

var request = buildPaymentRequest();

/**
 * Launches payment request for credit cards.
 */
function onBuyClicked() { // eslint-disable-line no-unused-vars
  if (!window.PaymentRequest || !request) {
    error('PaymentRequest API is not supported.');
    return;
  }

  try {
    request.show()
      .then(function(instrumentResponse) {
        window.setTimeout(function() {
          instrumentResponse.complete('success')
            .then(function() {
              done('This is a demo website. No payment will be processed.', instrumentResponse);
            })
            .catch(function(err) {
              error(err);
              request = buildPaymentRequest();
            });
        }, 2000);
      })
      .catch(function(err) {
        error(err);
        request = buildPaymentRequest();
      });
  } catch (e) {
    error('Developer mistake: \'' + e + '\'');
    request = buildPaymentRequest();
  }
}
<commit_msg>Print payment method change event details<commit_after>/* global done:false */
/* global error:false */
/* global PaymentRequest:false */

/**
 * Initializes the payment request object.
 */
function buildPaymentRequest() {
  if (!window.PaymentRequest) {
    return null;
  }

  var supportedInstruments = [{
    supportedMethods:
      'basic-card',

  }];

  var details = {
    total: {
      label: 'Donation',
      amount: {
        currency: 'USD',
        value: '55.00'
      }
    },
    displayItems: [{
      label: 'Original donation amount',
      amount: {
        currency: 'USD',
        value: '65.00'
      }
    }, {
      label: 'Friends and family discount',
      amount: {
        currency: 'USD',
        value: '-10.00'
      }
    }],
    modifiers: [{
      supportedMethods: 'basic-card',
      total: {
        label: 'Discounted donation',
        amount: {
          currency: 'USD',
          value: '45.00'
        }
      },
      additionalDisplayItems: [{
        label: 'VISA discount',
        amount: {
          currency: 'USD',
          value: '-10.00'
        }
      }],
      data: {
        discountProgramParticipantId: '86328764873265',
        supportedNetworks: ['visa'],
      }
    }]
  };

  var request = null;

  try {
    request = new PaymentRequest(supportedInstruments, details);
    if (request.canMakePayment) {
      request.canMakePayment().then(function(result) {
        info(result ? "Can make payment" : "Cannot make payment");
      }).catch(function(err) {
        error(err);
      });
    }

    if (request.onpaymentmethodchange !== undefined) {
      info('Will print out payment method change event details here.');
      request.addEventListener('paymentmethodchange', (evt) => {
        info('Payment method change event: ' + JSON.stringify({'methodName': evt.methodName, 'methodDetails': evt.methodDetails}, undefined, 2));
      });
    }
  } catch (e) {
    error('Developer mistake: \'' + e + '\'');
  }

  return request;
}

var request = buildPaymentRequest();

/**
 * Launches payment request for credit cards.
 */
function onBuyClicked() { // eslint-disable-line no-unused-vars
  if (!window.PaymentRequest || !request) {
    error('PaymentRequest API is not supported.');
    return;
  }

  try {
    request.show()
      .then(function(instrumentResponse) {
        window.setTimeout(function() {
          instrumentResponse.complete('success')
            .then(function() {
              done('This is a demo website. No payment will be processed.', instrumentResponse);
            })
            .catch(function(err) {
              error(err);
              request = buildPaymentRequest();
            });
        }, 2000);
      })
      .catch(function(err) {
        error(err);
        request = buildPaymentRequest();
      });
  } catch (e) {
    error('Developer mistake: \'' + e + '\'');
    request = buildPaymentRequest();
  }
}
<|endoftext|>


<commit_before>/* Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * Edited by Vinícius Garcia: https://github.com/vingarcia/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\bsuper\b/ : /.*/;

  // Require deep copy method:
  var copy = require('./copy.js').copy
  var instanceOf = require('./copy.js').instanceOf
  var id_count=0

  // The base Class implementation (does nothing)
  this.Class = function(){
    hide(this, 'apply', apply)
    hide(this, 'instanceof', instanceOf)
  }
  this.Class.prototype.init = function(){}

  // Used to hide special attributes:
  function hide(obj, name, value) {
    var options = {}

    options.value = value !== undefined ? value : obj[name]

    options.enumerable = false
    options.writable = true

    Object.defineProperty(obj, name, options)
  }

  function apply(func, args) {
    func.apply(this, [].splice.call(arguments, 1));
    return this;
  }

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {

    if(!prop || typeof prop !== 'object') prop = {}

    var _super = this.prototype;
    var constructor = this

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    /* * * * * Wrap the prop functions: * * * * */

    // Wrap the the init function:
    prototype.init = wrapInit(Class, _super, prop, id_count++)

    // Wrap and copy the functions and shared variables to the prototype:
    for (var name in prop) {
      if(name == 'init') continue;

      // Copy functions and wrap `this.super` around them:
      if( typeof prop[name] == 'function' )
        prototype[name] = wrapSuper(_super[name], prop[name])

      // Also copy shared variables
      // ('$' denotes $hared variables):
      else if(name[0] == '$')
        prototype[name] = prop[name]
    }

    // The class constructor
    function Class() {

      if(initializing) return

      // On the first run prepare the hidden
      // variables of this class instance:
      if(!this.__init_map__) {
        hide(this, '__init_map__', {})

        // Hide this super in this class instance, so the user won't see it.
        hide(this, 'super')
      }

      // The rest of the construction is done in the init method:
      if( this.init )
        prototype.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };

  function wrapSuper(_super, func) {
    // If the function does not call this.super, or there is no super to call:
    if( typeof _super != 'function' || !fnTest.test(func) ) return func;

    // Else:
    return function() {

      var bkp = _super
      this['super'] = _super

      var ret = func.apply(this, arguments)

      this['super'] = bkp

      return ret;
    }
  }

  function wrapInit(Class, _super, prop, id) {
    return function() {

      // If already initialized:
      if( this.__init_map__[id] ) {
        // If a reinit function is available:
        if(arguments.length>0 && typeof prop.reinit == 'function')
          wrapSuper(_super.reinit, prop.reinit).apply(this, arguments)

        return
      }
      this.__init_map__[id] = true

      // Copy the non-static properties from the prototype:
      for (var name in prop) {
        // Don't add functions and $hared variables:
        if( typeof prop[name] != 'function' && name[0] != '$')
          // If name is not defined:
          if(!this[name])
            this[name] = copy(prop[name])
      }

      // Call default super if not called by the user,
      // or if the user did not define an init function.
      if(!fnTest.test(prop.init) || !prop.init)
        Super.apply(this)

      // If the user defined no init, the job is done.
      if(!prop.init) return

      /* * * * * Prepare to run init * * * * */

      /* * * * * Memorize current functions * * * * */
      var _superFuncs = {}
      for (var name in this) {
        if( typeof this[name] == 'function' )
          _superFuncs[name] = this[name]
      }

      /* * * * * Wrap it with this.super * * * * */
      var bkp = this.super
      this.super = Super

      prop.init.apply(this, arguments);

      this.super = bkp

      /* * * * * Wrap any priviledged functions with `super` * * * * */
      for(var name in _superFuncs) {
        // If the priviledged function overwritten an older function:
        if( _superFuncs[name] != this[name] && this.hasOwnProperty(name) )
          this[name] = wrapSuper( _superFuncs[name], this[name] )
      }

      function Super() {
        _super.init.apply(this, arguments)

        /* In case of multiple inheritance we need to merge,
         * the prototype chain of the two Classes.
         *
         * The merging process is put in this function to make sure
         * it is done in the right order and at the right time.
         *
         * To detect if the user is merging two different classes
         * we check if this is an instance of Class, the only reason
         * it would not be, is because `this` is another's Class instance.
         *
         * The merging is complex, consider two prototype chains:
         *  - `this` prototype chain refer to the one accessible by: this.__proto__
         *  - `the` prototype chain refer to the one accessible by: Class.prototype
         *
         * The merging is as follows:
         *
         * 1. For each prototype on `the` prototype chain we need to
         *    add a copy of it to the end of `this` prototype chain.
         *
         * 2. The order is important. So the first one added must be
         *    be the one on the higher hierarchy, followed by the rest.
         *
         * 3. To allow it we use recursion, so everytime a super constructor
         *    finishes its execution we copy its subclass prototype
         *
         * Please NOTE: The user should not try accessing Class attributes
         * from inside init before calling Super, because there is an edge
         * situation (multiple-inheritance) where they will be accesible
         * only after the call.
         *
         * Also NOTE: instanceof won't work on multiple inherited objects.
         * instead use: `(new Class()).instanceof(Class)`
         */
        if(!this.instanceof(Class)) {
          // Shallow copy to allow the correct behavior of $shared variables.
          var proto = copy(Class.prototype, function(name, obj) { return obj })
          var this_proto = Object.getPrototypeOf(this)
          Object.setPrototypeOf(proto, this_proto)
          Object.setPrototypeOf(this, proto)
        }
      }
    }
  }
})();

<commit_msg>Add suport to overwrite priviledge funcs with normal ones<commit_after>/* Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * Edited by Vinícius Garcia: https://github.com/vingarcia/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\bsuper\b/ : /.*/;

  // Require deep copy method:
  var copy = require('./copy.js').copy
  var instanceOf = require('./copy.js').instanceOf
  var id_count=0

  // The base Class implementation (does nothing)
  this.Class = function(){
    hide(this, 'apply', apply)
    hide(this, 'instanceof', instanceOf)
  }
  this.Class.prototype.init = function(){}

  // Used to hide special attributes:
  function hide(obj, name, value) {
    var options = {}

    options.value = value !== undefined ? value : obj[name]

    options.enumerable = false
    options.writable = true

    Object.defineProperty(obj, name, options)
  }

  function apply(func, args) {
    func.apply(this, [].splice.call(arguments, 1));
    return this;
  }

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {

    if(!prop || typeof prop !== 'object') prop = {}

    var _super = this.prototype;
    var constructor = this

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    /* * * * * Wrap the prop functions: * * * * */

    // Wrap the the init function:
    prototype.init = wrapInit(Class, _super, prop, id_count++)

    // Wrap and copy the functions and shared variables to the prototype:
    for (var name in prop) {
      if(name == 'init') continue;

      // Copy functions and wrap `this.super` around them:
      if( typeof prop[name] == 'function' )
        prototype[name] = wrapSuper(_super[name], prop[name])

      // Also copy shared variables
      // ('$' denotes $hared variables):
      else if(name[0] == '$')
        prototype[name] = prop[name]
    }

    // The class constructor
    function Class() {

      if(initializing) return

      // On the first run prepare the hidden
      // variables of this class instance:
      if(!this.__init_map__) {
        hide(this, '__init_map__', {})

        // Hide this super in this class instance, so the user won't see it.
        hide(this, 'super')
      }

      // The rest of the construction is done in the init method:
      if( this.init )
        prototype.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };

  function wrapSuper(_super, func) {
    // If the function does not call this.super, or there is no super to call:
    if( typeof _super != 'function' || !fnTest.test(func) ) return func;

    // Else:
    return function() {

      var bkp = _super
      this['super'] = _super

      var ret = func.apply(this, arguments)

      this['super'] = bkp

      return ret;
    }
  }

  function wrapInit(Class, _super, prop, id) {
    return function() {

      // If already initialized:
      if( this.__init_map__[id] ) {
        // If a reinit function is available:
        if(arguments.length>0 && typeof prop.reinit == 'function')
          wrapSuper(_super.reinit, prop.reinit).apply(this, arguments)

        return
      }
      this.__init_map__[id] = true

      // Copy the non-static properties from the prototype:
      for (var name in prop) {
        // Don't add functions and $hared variables:
        if( typeof prop[name] != 'function' && name[0] != '$')
          // If name is not defined:
          if(!this[name])
            this[name] = copy(prop[name])
      }

      // Call default super if not called by the user,
      // or if the user did not define an init function.
      if(!fnTest.test(prop.init) || !prop.init)
        Super.apply(this)

      // If the user defined no init, the job is done.
      if(!prop.init) return

      /* * * * * Prepare to run init * * * * */

      /* * * * * Memorize current functions * * * * */
      var _superFuncs = {}
      for (var name in this) {
        if( typeof this[name] == 'function' )
          _superFuncs[name] = this[name]
      }

      /* * * * * Wrap it with this.super * * * * */
      var bkp = this.super
      this.super = Super

      prop.init.apply(this, arguments);

      this.super = bkp

      /* * * * * Wrap any priviledged functions with `super` * * * * */
      for(var name in _superFuncs) {
        // If the priviledged function overwritten an older function:
        if( _superFuncs[name] != this[name] && this.hasOwnProperty(name) )
          this[name] = wrapSuper( _superFuncs[name], this[name] )
      }

      function Super() {
        _super.init.apply(this, arguments)

        /* In case of multiple inheritance we need to merge,
         * the prototype chain of the two Classes.
         *
         * The merging process is put in this function to make sure
         * it is done in the right order and at the right time.
         *
         * To detect if the user is merging two different classes
         * we check if this is an instance of Class, the only reason
         * it would not be, is because `this` is another's Class instance.
         *
         * The merging is complex, consider two prototype chains:
         *  - `this` prototype chain refer to the one accessible by: this.__proto__
         *  - `the` prototype chain refer to the one accessible by: Class.prototype
         *
         * The merging is as follows:
         *
         * 1. For each prototype on `the` prototype chain we need to
         *    add a copy of it to the end of `this` prototype chain.
         *
         * 2. The order is important. So the first one added must be
         *    be the one on the higher hierarchy, followed by the rest.
         *
         * 3. To allow it we use recursion, so everytime a super constructor
         *    finishes its execution we copy its subclass prototype
         *
         * Please NOTE: The user should not try accessing Class attributes
         * from inside init before calling Super, because there is an edge
         * situation (multiple-inheritance) where they will be accesible
         * only after the call.
         *
         * Also NOTE: instanceof won't work on multiple inherited objects.
         * instead use: `(new Class()).instanceof(Class)`
         */
        var proto = Class.prototype
        if(!this.instanceof(Class)) {
          // Shallow copy to allow the correct behavior of $shared variables.
          var proto = copy(proto, function(name, obj) { return obj })
          var this_proto = Object.getPrototypeOf(this)
          Object.setPrototypeOf(proto, this_proto)
          Object.setPrototypeOf(this, proto)
        }

        // Allow extension of priviledged functions with normal functions:
        for(var name in proto) {
          if(typeof proto[name] == 'function' &&
             this.hasOwnProperty(name) &&
             typeof this[name] == 'function')
            // Use prop[name] instead of proto[name]
            // because proto[name] is already wrapped.
            this[name] = wrapSuper(this[name], prop[name])
        }
      }
    }
  }
})();

<|endoftext|>


<commit_before>$(document).on('ready', function() {
  if($('#call-tool').length > 0){
    height_changed();

    var call_campaign_id = $('[data-call-campaign-id]').attr('data-call-campaign-id');
    var $phone_number_field = $("#inputPhone");
    var $zip_field = $("#inputZip");
    var $street_address_field = $("#inputStreetAddress");
    var required_location = !!$street_address_field.length;

    $phone_number_field.each(function(){
      $(this).bfhphone($(this).data());
    });

    function determine_location(cb, zip_code, street_address){
      if(required_location) {
        // When address field is present, lookup congressional district
        $.ajax({
          url: '/smarty_streets/street_address/?street=' + encodeURIComponent(street_address) + '&zipcode=' + encodeURIComponent(zip_code),
          success: function(res){
            if (res.length == 1) {
              var state = res[0].components.state_abbreviation;
              var district = res[0].metadata.congressional_district;

              if (district == undefined)
                cb(App.Strings.districtLookupFailed);
              else
                cb(null, state + "-" + district);
            } else {
              cb(App.Strings.districtLookupFailed);
            }
          },
          error: function(err){
            cb("There was an error processing this request.");
          }
        });
      } else {
        // When address field is not present, use zip code for location
        cb(null, zip_code);
      }
    }

    function show_form(){
      $('.call-body-phone-saved').addClass('hidden');
      $('.tool-title.precall').removeClass('hidden');
      $('.tool-title.postcall').addClass('hidden');
      $('.call-body-phone-not-saved').removeClass('hidden');
      $('.call-body-active').addClass('hidden');
    }
    function hide_form(){
      $('.tool-title.precall').addClass('hidden');
      $('.tool-title.postcall').removeClass('hidden');
      $('.call-body-phone-not-saved').addClass('hidden');
      $('.call-body-active').removeClass('hidden');
      $('.call-body-phone-saved').addClass('hidden');
    }

    $('form.call-tool, form.call-tool-saved').on('submit', function(ev) {
      var form = $(ev.currentTarget);

      var update_user_data = $('#update_user_data', form).val();
      var phone_number = $phone_number_field.val().replace(/[^\d.]/g, '');
      var street_address = $street_address_field.val();
      var zip_code = ($zip_field.val() || "").replace(/[^\d.]/g, '').slice(0,5);
      var action_id = $('[name="action-id"]', form).val();

      if (!isValidPhoneNumber(phone_number)){
        rumbleEl($phone_number_field);
      } else if ($zip_field.length && zip_code.length != 5) {
        rumbleEl($zip_field);
      } else {
        form.find('.form-errors').addClass("hidden");
        determine_location(function(err, location){
          if (err) {
            form.find('.form-errors').text(err).removeClass("hidden");
          } else if (location) {
            hide_form();
            height_changed();

            var fd = new FormData();
            fd.append("action_id", action_id);
            fd.append("call_campaign_id", call_campaign_id);
            fd.append("phone", phone_number);
            fd.append("location", location);
            if (street_address != '')
              fd.append("street_address", street_address);
            fd.append("zipcode", zip_code);
            fd.append("update_user_data", update_user_data);

            if (form.find("input[name=subscribe]:checked").val() == "1") {
              fd.append("subscription[email]", form.find("input[type=email]").val());
              fd.append("subscription[zipcode]", zip_code);
              form.attr("data-signed-up-for-mailings", "true");
            }

            $.ajax({
              url: "/tools/call",
              type: "POST",
              data: fd,
              processData: false,
              contentType: false
            });
          }
        }, zip_code, street_address);
      }

      ev.preventDefault();
    });

    $('.call-tool-try-again').on('click', function(ev){
      show_form();
      height_changed();
      return false;
    });

    $('.call-tool-different-number').on('click', function(ev){
      show_form();
      $('#inputPhone').val('').focus();
      height_changed();
      return false;
    });
  }
});
<commit_msg>Fix custom target calls<commit_after>$(document).on('ready', function() {
  if($('#call-tool').length > 0){
    height_changed();

    var call_campaign_id = $('[data-call-campaign-id]').attr('data-call-campaign-id');
    var $phone_number_field = $("#inputPhone");
    var $zip_field = $("#inputZip");
    var $street_address_field = $("#inputStreetAddress");
    var required_location = !!$street_address_field.length;

    $phone_number_field.each(function(){
      $(this).bfhphone($(this).data());
    });

    function determine_location(cb, zip_code, street_address){
      if(required_location) {
        // When address field is present, lookup congressional district
        $.ajax({
          url: '/smarty_streets/street_address/?street=' + encodeURIComponent(street_address) + '&zipcode=' + encodeURIComponent(zip_code),
          success: function(res){
            if (res.length == 1) {
              var state = res[0].components.state_abbreviation;
              var district = res[0].metadata.congressional_district;

              if (district == undefined)
                cb(App.Strings.districtLookupFailed);
              else
                cb(null, state + "-" + district);
            } else {
              cb(App.Strings.districtLookupFailed);
            }
          },
          error: function(err){
            cb("There was an error processing this request.");
          }
        });
      } else {
        // When address field is not present, use zip code for location
        cb(null, zip_code);
      }
    }

    function show_form(){
      $('.call-body-phone-saved').addClass('hidden');
      $('.tool-title.precall').removeClass('hidden');
      $('.tool-title.postcall').addClass('hidden');
      $('.call-body-phone-not-saved').removeClass('hidden');
      $('.call-body-active').addClass('hidden');
    }
    function hide_form(){
      $('.tool-title.precall').addClass('hidden');
      $('.tool-title.postcall').removeClass('hidden');
      $('.call-body-phone-not-saved').addClass('hidden');
      $('.call-body-active').removeClass('hidden');
      $('.call-body-phone-saved').addClass('hidden');
    }

    $('form.call-tool, form.call-tool-saved').on('submit', function(ev) {
      var form = $(ev.currentTarget);

      var update_user_data = $('#update_user_data', form).val();
      var phone_number = $phone_number_field.val().replace(/[^\d.]/g, '');
      var street_address = $street_address_field.val();
      var zip_code = ($zip_field.val() || "").replace(/[^\d.]/g, '').slice(0,5);
      var action_id = $('[name="action-id"]', form).val();

      if (!isValidPhoneNumber(phone_number)){
        rumbleEl($phone_number_field);
      } else if ($zip_field.length && zip_code.length != 5) {
        rumbleEl($zip_field);
      } else {
        form.find('.form-errors').addClass("hidden");
        determine_location(function(err, location){
          if (err) {
            form.find('.form-errors').text(err).removeClass("hidden");
          } else {
            hide_form();
            height_changed();

            var fd = new FormData();
            fd.append("action_id", action_id);
            fd.append("call_campaign_id", call_campaign_id);
            fd.append("phone", phone_number);
            fd.append("location", location);
            if (street_address != '')
              fd.append("street_address", street_address);
            fd.append("zipcode", zip_code);
            fd.append("update_user_data", update_user_data);

            if (form.find("input[name=subscribe]:checked").val() == "1") {
              fd.append("subscription[email]", form.find("input[type=email]").val());
              fd.append("subscription[zipcode]", zip_code);
              form.attr("data-signed-up-for-mailings", "true");
            }

            $.ajax({
              url: "/tools/call",
              type: "POST",
              data: fd,
              processData: false,
              contentType: false
            });
          }
        }, zip_code, street_address);
      }

      ev.preventDefault();
    });

    $('.call-tool-try-again').on('click', function(ev){
      show_form();
      height_changed();
      return false;
    });

    $('.call-tool-different-number').on('click', function(ev){
      show_form();
      $('#inputPhone').val('').focus();
      height_changed();
      return false;
    });
  }
});
<|endoftext|>


<commit_before>/* eslint-disable promise/catch-or-return */

import RecentSearchesService from '~/filtered_search/services/recent_searches_service';
import AccessorUtilities from '~/lib/utils/accessor';

describe('RecentSearchesService', () => {
  let service;

  beforeEach(() => {
    service = new RecentSearchesService();
    window.localStorage.removeItem(service.localStorageKey);
  });

  describe('fetch', () => {
    beforeEach(() => {
      spyOn(RecentSearchesService, 'isAvailable').and.returnValue(true);
    });

    it('should default to empty array', (done) => {
      const fetchItemsPromise = service.fetch();

      fetchItemsPromise
        .then((items) => {
          expect(items).toEqual([]);
          done();
        })
        .catch((err) => {
          done.fail('Shouldn\'t reject with empty localStorage key', err);
        });
    });

    it('should reject when unable to parse', (done) => {
      window.localStorage.setItem(service.localStorageKey, 'fail');
      const fetchItemsPromise = service.fetch();

      fetchItemsPromise
        .catch((error) => {
          expect(error).toEqual(jasmine.any(SyntaxError));
          done();
        });
    });

    it('should reject when service is unavailable', (done) => {
      RecentSearchesService.isAvailable.and.returnValue(false);

      service.fetch().catch((error) => {
        expect(error).toEqual(jasmine.any(Error));
        done();
      });
    });

    it('should return items from localStorage', (done) => {
      window.localStorage.setItem(service.localStorageKey, '["foo", "bar"]');
      const fetchItemsPromise = service.fetch();

      fetchItemsPromise
        .then((items) => {
          expect(items).toEqual(['foo', 'bar']);
          done();
        });
    });

    describe('if .isAvailable returns `false`', () => {
      beforeEach(() => {
        RecentSearchesService.isAvailable.and.returnValue(false);

        spyOn(window.localStorage, 'getItem');

        RecentSearchesService.prototype.fetch();
      });

      it('should not call .getItem', () => {
        expect(window.localStorage.getItem).not.toHaveBeenCalled();
      });
    });
  });

  describe('setRecentSearches', () => {
    beforeEach(() => {
      spyOn(RecentSearchesService, 'isAvailable').and.returnValue(true);
    });

    it('should save things in localStorage', () => {
      const items = ['foo', 'bar'];
      service.save(items);
      const newLocalStorageValue = window.localStorage.getItem(service.localStorageKey);
      expect(JSON.parse(newLocalStorageValue)).toEqual(items);
    });
  });

  describe('save', () => {
    beforeEach(() => {
      spyOn(window.localStorage, 'setItem');
      spyOn(RecentSearchesService, 'isAvailable');
    });

    describe('if .isAvailable returns `true`', () => {
      const searchesString = 'searchesString';
      const localStorageKey = 'localStorageKey';
      const recentSearchesService = {
        localStorageKey,
      };

      beforeEach(() => {
        RecentSearchesService.isAvailable.and.returnValue(true);

        spyOn(JSON, 'stringify').and.returnValue(searchesString);

        RecentSearchesService.prototype.save.call(recentSearchesService);
      });

      it('should call .setItem', () => {
        expect(window.localStorage.setItem).toHaveBeenCalledWith(localStorageKey, searchesString);
      });
    });

    describe('if .isAvailable returns `false`', () => {
      beforeEach(() => {
        RecentSearchesService.isAvailable.and.returnValue(false);

        RecentSearchesService.prototype.save();
      });

      it('should not call .setItem', () => {
        expect(window.localStorage.setItem).not.toHaveBeenCalled();
      });
    });
  });

  describe('isAvailable', () => {
    let isAvailable;

    beforeEach(() => {
      spyOn(AccessorUtilities, 'isLocalStorageAccessSafe').and.callThrough();

      isAvailable = RecentSearchesService.isAvailable();
    });

    it('should call .isLocalStorageAccessSafe', () => {
      expect(AccessorUtilities.isLocalStorageAccessSafe).toHaveBeenCalled();
    });

    it('should return a boolean', () => {
      expect(typeof isAvailable).toBe('boolean');
    });
  });
});
<commit_msg>Handle Promise rejections in RecentSearchesService spec (!11206)<commit_after>import RecentSearchesService from '~/filtered_search/services/recent_searches_service';
import RecentSearchesServiceError from '~/filtered_search/services/recent_searches_service_error';
import AccessorUtilities from '~/lib/utils/accessor';

describe('RecentSearchesService', () => {
  let service;

  beforeEach(() => {
    service = new RecentSearchesService();
    window.localStorage.removeItem(service.localStorageKey);
  });

  describe('fetch', () => {
    beforeEach(() => {
      spyOn(RecentSearchesService, 'isAvailable').and.returnValue(true);
    });

    it('should default to empty array', (done) => {
      const fetchItemsPromise = service.fetch();

      fetchItemsPromise
        .then((items) => {
          expect(items).toEqual([]);
        })
        .then(done)
        .catch(done.fail);
    });

    it('should reject when unable to parse', (done) => {
      window.localStorage.setItem(service.localStorageKey, 'fail');
      const fetchItemsPromise = service.fetch();

      fetchItemsPromise
        .then(done.fail)
        .catch((error) => {
          expect(error).toEqual(jasmine.any(SyntaxError));
        })
        .then(done)
        .catch(done.fail);
    });

    it('should reject when service is unavailable', (done) => {
      RecentSearchesService.isAvailable.and.returnValue(false);

      service.fetch()
        .then(done.fail)
        .catch((error) => {
          expect(error).toEqual(jasmine.any(Error));
        })
        .then(done)
        .catch(done.fail);
    });

    it('should return items from localStorage', (done) => {
      window.localStorage.setItem(service.localStorageKey, '["foo", "bar"]');
      const fetchItemsPromise = service.fetch();

      fetchItemsPromise
        .then((items) => {
          expect(items).toEqual(['foo', 'bar']);
        })
        .then(done)
        .catch(done.fail);
    });

    describe('if .isAvailable returns `false`', () => {
      beforeEach(() => {
        RecentSearchesService.isAvailable.and.returnValue(false);

        spyOn(window.localStorage, 'getItem');
      });

      it('should not call .getItem', (done) => {
        RecentSearchesService.prototype.fetch()
          .then(done.fail)
          .catch((err) => {
            expect(err).toEqual(new RecentSearchesServiceError());
            expect(window.localStorage.getItem).not.toHaveBeenCalled();
          })
          .then(done)
          .catch(done.fail);
      });
    });
  });

  describe('setRecentSearches', () => {
    beforeEach(() => {
      spyOn(RecentSearchesService, 'isAvailable').and.returnValue(true);
    });

    it('should save things in localStorage', () => {
      const items = ['foo', 'bar'];
      service.save(items);
      const newLocalStorageValue = window.localStorage.getItem(service.localStorageKey);
      expect(JSON.parse(newLocalStorageValue)).toEqual(items);
    });
  });

  describe('save', () => {
    beforeEach(() => {
      spyOn(window.localStorage, 'setItem');
      spyOn(RecentSearchesService, 'isAvailable');
    });

    describe('if .isAvailable returns `true`', () => {
      const searchesString = 'searchesString';
      const localStorageKey = 'localStorageKey';
      const recentSearchesService = {
        localStorageKey,
      };

      beforeEach(() => {
        RecentSearchesService.isAvailable.and.returnValue(true);

        spyOn(JSON, 'stringify').and.returnValue(searchesString);
      });

      it('should call .setItem', () => {
        RecentSearchesService.prototype.save.call(recentSearchesService);

        expect(window.localStorage.setItem).toHaveBeenCalledWith(localStorageKey, searchesString);
      });
    });

    describe('if .isAvailable returns `false`', () => {
      beforeEach(() => {
        RecentSearchesService.isAvailable.and.returnValue(false);
      });

      it('should not call .setItem', () => {
        RecentSearchesService.prototype.save();

        expect(window.localStorage.setItem).not.toHaveBeenCalled();
      });
    });
  });

  describe('isAvailable', () => {
    let isAvailable;

    beforeEach(() => {
      spyOn(AccessorUtilities, 'isLocalStorageAccessSafe').and.callThrough();

      isAvailable = RecentSearchesService.isAvailable();
    });

    it('should call .isLocalStorageAccessSafe', () => {
      expect(AccessorUtilities.isLocalStorageAccessSafe).toHaveBeenCalled();
    });

    it('should return a boolean', () => {
      expect(typeof isAvailable).toBe('boolean');
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var jsonrpc = require('jsonrpc-tcp'),
    log4js = require('log4js'),
    _ = require('lodash');

var Camera = require('./camera');

var JSONRPC_PORT = 50800;
var STATUS_INTERVAL = 60000;  // status report interval; less than gateway one.
var logger;

log4js.configure(__dirname + '/logger_cfg.json', { reloadSecs: 30, cwd: 'log' });
logger = log4js.getLogger('T+EMBEDDED');

function _actuatingCamera(sensor, cmd, options, cb) {
  function _callback(err, url) {
    if (err) {
      logger.error('camera actuating failed');
      return cb && cb(new Error('camera actuating failed'));
    }

    var result = {
      contentType: 'image/jpeg',
      url: url
    };

    return cb && cb(null, result);
  }

  switch (cmd) {
  case 'snapPicture':
    sensor.driver.snapPicture(_callback);
    break;
  default:
    if (cb) {
      process.nextTick(function () {
        cb(new Error('unknown cmd(%s)', cmd));
      });
    }
    break;
  }
}

function Device(id) {
  this.sensors = [{
    name: 'camera',
    type: 'camera',
    constructor: Camera,
    actuating: _actuatingCamera
  }];

  this.id = id;
  this.pushStatus = [];
  this.pushStatusTimer = null;

  this._init();
  this._serverInit();
}

function getSensorById(sensors, id) {
  var name = id.substring(id.indexOf('-')+1);
  return _.find(sensors, {'name': name} );
}

Device.prototype.sensing = function () {
  var self = this;

  return {
    get: function (id, result) {
      var sensor = getSensorById(self.sensors, id); //TODO change delete hardcodded
      if (_.isNull(sensor) || _.isUndefined(sensor)) {
        logger.error('getsensorbyid failed. id:' + id);
        return result('err');
      }

      sensor.driver.getValue(function (err, value) {
        logger.info('%s value:%s', sensor.name, value);
        return result(null, {value: value, status: 'on'});
      });
    },

    setNotification: function (id, result) {
      var sensor = getSensorById(self.sensors, id);

      if (_.isNull(sensor) || _.isUndefined(sensor)) {
        logger.error('getsensorbyid failed. id:' + id);
        return result('err');
      }

      if (!sensor.notification) {
        logger.error('%s can`t setNotification', sensor.name);
        return result('err');
      }

      if (_.find(self.pushStatus, {'name': sensor.name})) {
        logger.warn('%s is already notified', sensor.name);
        return result(null);
      }

      self.pushStatus.push(sensor);

      sensor.driver.trigger(function (err, value) {
        if (_.isNull(self.client)) {
          return;
        }

        self.client.send({method: 'sensor.notification',
          params: [id, {value: value}] });
      });

      if (self.pushStatusTimer) {
        return result(null);
      }

      self.pushStatusTimer = setInterval(function () {
        if ( _.isNull(self.client) || _.isUndefined(self.client)) {
          return;
        }

       self.pushStatus.forEach(function (sensor) {
         self.client.send({method: 'sensor.notification',
           params: [sensor.id, {status: sensor.driver.statusSync()}]
         });
       });
      }, STATUS_INTERVAL);

      return result(null);
    },

    set: function(id, cmd, options, result) {
      var sensor = getSensorById(self.sensors, id);

      if (_.isNull(sensor) || _.isUndefined(sensor)) {
        logger.error('getsensorbyid failed. id:' + id);
        result('err');
      }

      sensor.actuating(sensor, cmd, options, result);
    }
  };
};

Device.prototype.discovering = function (result) {
  var devices = [];
  var self = this;

  devices[this.id] = {deviceAddress: this.id, deviceModelId: 'jsonrpcFullV1.0'};
  devices[this.id]['sensors'] = [];

  _.forEach(this.sensors, function (sensor) {
    sensor.id = [self.id, sensor.name].join('-'); //FIXME make function
    devices[self.id]['sensors'].push(
      {
        id:sensor.id,
        type:sensor.type,
        name: sensor.name,
        notification: sensor.notification
      });
    logger.info('discovered. name:%s type:%s', sensor.name, sensor.type);
  });

  return result(null, devices);
};

Device.prototype._init = function () {
  _.forEach(this.sensors, function (sensor) {
    sensor.driver = new sensor.constructor();
  });
};

Device.prototype._serverInit = function () {
  var self = this;
  var server = jsonrpc.createServer(function (client/*, remote*/) {
    logger.info('New client connected');
    self.client = client;
  });

  server.on('clientError', function (err, conn) {
    self.client = null;

    if (self.pushStatusTimer) {
      clearInterval(self.pushStatusTimer);
    }

    self.pushStatus.splice(0, self.pushStatus.length);

    _.forEach(self.sensors, function (sensor) {
      if (sensor.driver.cleanup) {
        sensor.driver.cleanup();
      }
    });

    logger.info('client disconnected');
  });

  server.expose('discover', this.discovering.bind(this));
  server.expose('sensor', this.sensing.bind(this)());

  server.listen(JSONRPC_PORT, function () {
    logger.info('listening port=%d', JSONRPC_PORT);
  });
};

var device = new Device('0');
<commit_msg>[rasp/camera] Fix device model ID<commit_after>'use strict';

var jsonrpc = require('jsonrpc-tcp'),
    log4js = require('log4js'),
    _ = require('lodash');

var Camera = require('./camera');

var JSONRPC_PORT = 50800;
var STATUS_INTERVAL = 60000;  // status report interval; less than gateway one.
var logger;

log4js.configure(__dirname + '/logger_cfg.json', { reloadSecs: 30, cwd: 'log' });
logger = log4js.getLogger('T+EMBEDDED');

function _actuatingCamera(sensor, cmd, options, cb) {
  function _callback(err, url) {
    if (err) {
      logger.error('camera actuating failed');
      return cb && cb(new Error('camera actuating failed'));
    }

    var result = {
      contentType: 'image/jpeg',
      url: url
    };

    return cb && cb(null, result);
  }

  switch (cmd) {
  case 'snapPicture':
    sensor.driver.snapPicture(_callback);
    break;
  default:
    if (cb) {
      process.nextTick(function () {
        cb(new Error('unknown cmd(%s)', cmd));
      });
    }
    break;
  }
}

function Device(id) {
  this.sensors = [{
    name: 'camera',
    type: 'camera',
    constructor: Camera,
    actuating: _actuatingCamera
  }];

  this.id = id;
  this.pushStatus = [];
  this.pushStatusTimer = null;

  this._init();
  this._serverInit();
}

function getSensorById(sensors, id) {
  var name = id.substring(id.indexOf('-')+1);
  return _.find(sensors, {'name': name} );
}

Device.prototype.sensing = function () {
  var self = this;

  return {
    get: function (id, result) {
      var sensor = getSensorById(self.sensors, id); //TODO change delete hardcodded
      if (_.isNull(sensor) || _.isUndefined(sensor)) {
        logger.error('getsensorbyid failed. id:' + id);
        return result('err');
      }

      sensor.driver.getValue(function (err, value) {
        logger.info('%s value:%s', sensor.name, value);
        return result(null, {value: value, status: 'on'});
      });
    },

    setNotification: function (id, result) {
      var sensor = getSensorById(self.sensors, id);

      if (_.isNull(sensor) || _.isUndefined(sensor)) {
        logger.error('getsensorbyid failed. id:' + id);
        return result('err');
      }

      if (!sensor.notification) {
        logger.error('%s can`t setNotification', sensor.name);
        return result('err');
      }

      if (_.find(self.pushStatus, {'name': sensor.name})) {
        logger.warn('%s is already notified', sensor.name);
        return result(null);
      }

      self.pushStatus.push(sensor);

      sensor.driver.trigger(function (err, value) {
        if (_.isNull(self.client)) {
          return;
        }

        self.client.send({method: 'sensor.notification',
          params: [id, {value: value}] });
      });

      if (self.pushStatusTimer) {
        return result(null);
      }

      self.pushStatusTimer = setInterval(function () {
        if ( _.isNull(self.client) || _.isUndefined(self.client)) {
          return;
        }

       self.pushStatus.forEach(function (sensor) {
         self.client.send({method: 'sensor.notification',
           params: [sensor.id, {status: sensor.driver.statusSync()}]
         });
       });
      }, STATUS_INTERVAL);

      return result(null);
    },

    set: function(id, cmd, options, result) {
      var sensor = getSensorById(self.sensors, id);

      if (_.isNull(sensor) || _.isUndefined(sensor)) {
        logger.error('getsensorbyid failed. id:' + id);
        result('err');
      }

      sensor.actuating(sensor, cmd, options, result);
    }
  };
};

Device.prototype.discovering = function (result) {
  var devices = [];
  var self = this;

  devices[this.id] = {deviceAddress: this.id, deviceModelId: 'GrovePiPlusStarterKitForRaspberryPi'};
  devices[this.id]['sensors'] = [];

  _.forEach(this.sensors, function (sensor) {
    sensor.id = [self.id, sensor.name].join('-'); //FIXME make function
    devices[self.id]['sensors'].push(
      {
        id:sensor.id,
        type:sensor.type,
        name: sensor.name,
        notification: sensor.notification
      });
    logger.info('discovered. name:%s type:%s', sensor.name, sensor.type);
  });

  return result(null, devices);
};

Device.prototype._init = function () {
  _.forEach(this.sensors, function (sensor) {
    sensor.driver = new sensor.constructor();
  });
};

Device.prototype._serverInit = function () {
  var self = this;
  var server = jsonrpc.createServer(function (client/*, remote*/) {
    logger.info('New client connected');
    self.client = client;
  });

  server.on('clientError', function (err, conn) {
    self.client = null;

    if (self.pushStatusTimer) {
      clearInterval(self.pushStatusTimer);
    }

    self.pushStatus.splice(0, self.pushStatus.length);

    _.forEach(self.sensors, function (sensor) {
      if (sensor.driver.cleanup) {
        sensor.driver.cleanup();
      }
    });

    logger.info('client disconnected');
  });

  server.expose('discover', this.discovering.bind(this));
  server.expose('sensor', this.sensing.bind(this)());

  server.listen(JSONRPC_PORT, function () {
    logger.info('listening port=%d', JSONRPC_PORT);
  });
};

var device = new Device('0');
<|endoftext|>


<commit_before>/*
Copyright 2016 First People's Cultural Council

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

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

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

import Immutable, { List, Map } from 'immutable';

const toJSKeepId = function (js) {
  return typeof js !== 'object' || js === null ? js :
    Array.isArray(js) ?
      Immutable.Seq(js).map(toJSKeepId).toList() :
      (js.hasOwnProperty('id')) ? Immutable.Seq(js).toMap() : Immutable.Seq(js).map(toJSKeepId).toMap();
}

const proxiesKeys = [
  {
    workspace: 'fv-word:categories',
    section: 'fvproxy:proxied_categories'
  },
  {
    workspace: 'fv-phrase:phrase_books',
    section: 'fvproxy:proxied_categories'
  },
  {
    workspace: 'fvm:origin',
    section: 'fvproxy:proxied_origin'
  },
  {
    workspace: 'fv:related_pictures',
    section: 'fvproxy:proxied_pictures'
  },
  {
    workspace: 'fv:related_videos',
    section: 'fvproxy:proxied_videos'
  },
  {
    workspace: 'fv:related_audio',
    section: 'fvproxy:proxied_audio'
  }
];

export default {
  getEntry: function (wordResults, path) {
    if (!wordResults || wordResults.isEmpty() || !path)
      return null;

    let result = wordResults.find(function(entry) {
        return entry.get('id') === path;
    });

	if (result)
    	return result.toJS();

    return null;
  },
  toJSKeepId: function(js) { return toJSKeepId(js)},
  /*hasExtendedGroup: function (extendedGroups, group) {

    if (extendedGroups && extendedGroups.size > 0) {
      if (extendedGroups.findIndex(function(entry) { return (entry.get('name') === group) }) === -1) {
        return false;
      } else {
        return true;
      }
    }

    return false;
  },*/
  isActiveRole: function(roles) {
    if (roles && roles.length > 0) {
      if (roles.indexOf("Record") !== -1 || roles.indexOf("Approve") !== -1 || roles.indexOf("Manage") !== -1 || roles.indexOf("Member") !== -1) {
        return true;
      }
    }

    return false;
  },
  getDialectPathFromURLArray: function (url) {
  	return decodeURI(url.slice(1, 7).join('/'));
  },
  switchWorkspaceSectionKeys: function (workspaceKey, area) {

    let row = proxiesKeys.find(function (mapping) {
      return mapping.workspace === workspaceKey;
    })

    if (row){
      if (area == 'sections') {
        return row.section;
      } else {
        return row.workspace;
      }
    }

    return workspaceKey;
  },
  replaceAllWorkspaceSectionKeys: function (string, area) {

    let searchKey = (area == 'sections') ? 'workspace' : 'section';
    let replaceKey = (area == 'sections') ? 'section' : 'workspace';

    for (let proxyKey in proxiesKeys) {
      string = string.replace(new RegExp(proxiesKeys[proxyKey][searchKey],'g'), proxiesKeys[proxyKey][replaceKey]);
    }

    return string;
  },
  filtersToNXQL: function (filterArray) {

    let nxqlFilterString = '';

    for (let appliedFilterKey in filterArray) {
        let ak = Object.assign({}, filterArray[appliedFilterKey]);
        if (ak && ak.hasOwnProperty('filterOptions') && ak.filterOptions && ak.filterOptions.hasOwnProperty('nxql')) {

            if (ak.appliedFilter === true) (ak.appliedFilter = 1);
            if (ak.appliedFilter === false) (ak.appliedFilter = 0);

            nxqlFilterString += ' AND ' + ak.filterOptions.nxql.replace(/\$\{value\}/g, ak.appliedFilter);
        }
    }

    return (!nxqlFilterString || nxqlFilterString.length == 0) ? '' : nxqlFilterString;
  },
  regex: {
    ANYTHING_BUT_SLASH : "([^/]*)",
    WORKSPACE_OR_SECTION : "(sections|Workspaces)",
    KIDS_OR_DEFAULT : "(kids|explore)"
  }
}<commit_msg>Added get dialect groups and group nxql filtering<commit_after>/*
Copyright 2016 First People's Cultural Council

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

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

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

import Immutable, { List, Map } from 'immutable';
import StringHelpers from './StringHelpers'

const toJSKeepId = function (js) {
  return typeof js !== 'object' || js === null ? js :
    Array.isArray(js) ?
      Immutable.Seq(js).map(toJSKeepId).toList() :
      (js.hasOwnProperty('id')) ? Immutable.Seq(js).toMap() : Immutable.Seq(js).map(toJSKeepId).toMap();
}

const proxiesKeys = [
  {
    workspace: 'fv-word:categories',
    section: 'fvproxy:proxied_categories'
  },
  {
    workspace: 'fv-phrase:phrase_books',
    section: 'fvproxy:proxied_categories'
  },
  {
    workspace: 'fvm:origin',
    section: 'fvproxy:proxied_origin'
  },
  {
    workspace: 'fv:related_pictures',
    section: 'fvproxy:proxied_pictures'
  },
  {
    workspace: 'fv:related_videos',
    section: 'fvproxy:proxied_videos'
  },
  {
    workspace: 'fv:related_audio',
    section: 'fvproxy:proxied_audio'
  }
];

export default {
  getEntry: function (wordResults, path) {
    if (!wordResults || wordResults.isEmpty() || !path)
      return null;

    let result = wordResults.find(function(entry) {
        return entry.get('id') === path;
    });

	if (result)
    	return result.toJS();

    return null;
  },
  toJSKeepId: function(js) { return toJSKeepId(js)},
  /*hasExtendedGroup: function (extendedGroups, group) {

    if (extendedGroups && extendedGroups.size > 0) {
      if (extendedGroups.findIndex(function(entry) { return (entry.get('name') === group) }) === -1) {
        return false;
      } else {
        return true;
      }
    }

    return false;
  },*/
  isActiveRole: function(roles) {
    if (roles && roles.length > 0) {
      if (roles.indexOf("Record") !== -1 || roles.indexOf("Approve") !== -1 || roles.indexOf("Manage") !== -1 || roles.indexOf("Member") !== -1) {
        return true;
      }
    }

    return false;
  },
  getDialectPathFromURLArray: function (url) {
  	return decodeURI(url.slice(1, 7).join('/'));
  },
  switchWorkspaceSectionKeys: function (workspaceKey, area) {

    let row = proxiesKeys.find(function (mapping) {
      return mapping.workspace === workspaceKey;
    })

    if (row){
      if (area == 'sections') {
        return row.section;
      } else {
        return row.workspace;
      }
    }

    return workspaceKey;
  },
  getDialectGroups: function (aces = [], currentlyAssignedGroups = []) {

        if (aces.length === 0)
        {
            return {
              all: null,
              new: null
            };
        }

        // Generate list of groups this user can be added to
        let allAvailableGroups = {};

        // Generate list of all groups related to this dialect
        let newAvailableGroups = {};

        (aces).forEach(function(group, i) {
            let groupArray = group.username.split('_');
            if (group.username.match(/members|recorders|administrators/g) != null) {

                let groupLabel = groupArray.map((group) => StringHelpers.toTitleCase(group)).join(' ');

                allAvailableGroups[group.username] = groupLabel;

                // If user is not already a memeber of this group, add to new available groups
                if (currentlyAssignedGroups.indexOf(group.username) === -1) {
                    newAvailableGroups[group.username] = groupLabel;
                }
            }
        });

        return {
            all: allAvailableGroups,
            new: newAvailableGroups
        };
  },
  replaceAllWorkspaceSectionKeys: function (string, area) {

    let searchKey = (area == 'sections') ? 'workspace' : 'section';
    let replaceKey = (area == 'sections') ? 'section' : 'workspace';

    for (let proxyKey in proxiesKeys) {
      string = string.replace(new RegExp(proxiesKeys[proxyKey][searchKey],'g'), proxiesKeys[proxyKey][replaceKey]);
    }

    return string;
  },
  filtersToNXQL: function (filterArray) {

    let nxqlFilterString = '';
    let nxqlGroups = {};

    const generateNXQLString = function(nxql, appliedFilter) {
      return nxql.replace(/\$\{value\}/g, appliedFilter);
    }

    for (let appliedFilterKey in filterArray) {
        let ak = Object.assign({}, filterArray[appliedFilterKey]);
        if (ak && ak.hasOwnProperty('filterOptions') && ak.filterOptions && ak.filterOptions.hasOwnProperty('nxql')) {

            if (ak.appliedFilter === true) (ak.appliedFilter = 1);
            if (ak.appliedFilter === false) (ak.appliedFilter = 0);

            if (!ak.filterOptions.hasOwnProperty('nxqlGroup')) {
              nxqlFilterString += ' ' + (ak.filterOptions.hasOwnProperty('operator') ? ak.filterOptions.operator : 'AND') + ' ' + generateNXQLString(ak.filterOptions.nxql, ak.appliedFilter);
            } else {
              if (nxqlGroups.hasOwnProperty(ak.filterOptions.nxqlGroup) && nxqlGroups[ak.filterOptions.nxqlGroup].length > 0) {
                nxqlGroups[ak.filterOptions.nxqlGroup].push(generateNXQLString(ak.filterOptions.nxql, ak.appliedFilter));
              } else {
                nxqlGroups[ak.filterOptions.nxqlGroup] = [generateNXQLString(ak.filterOptions.nxql, ak.appliedFilter)];
              }
            }
        }
    }

    let appendGroupNXQL = '';

    for (var key in nxqlGroups) {
      appendGroupNXQL += ' AND (' + nxqlGroups[key].join(' OR ') + ')'
    }

    return nxqlFilterString + appendGroupNXQL;
  },
  regex: {
    ANYTHING_BUT_SLASH : "([^/]*)",
    WORKSPACE_OR_SECTION : "(sections|Workspaces)",
    KIDS_OR_DEFAULT : "(kids|explore)"
  }
}<|endoftext|>


<commit_before>var five = require("johnny-five");

var nanomsg = require("nanomsg");
var sub = nanomsg.socket('sub');

var addr = 'tcp://127.0.0.1:7789';
sub.connect(addr);

var keypress = require("keypress");
keypress(process.stdin);

var state = {
  pins   :[11,10,09, 06,05,03], // x,x,x  y,y,y  Pin numbers
  written:[0,0,0,0,0,0],        // x,x,x  y,y,y
  nextpwm:[0,0,0,0,0,0],        // x,x,x  y,y,y
  origin: [0,0],  // origin_x, origin_y
  offset: [0,0]   // offset_x, offset_y
}

var board = new five.Board();
board.on("ready", function() {
  function motors_freewheel() {
    var p=pwm_width(0);
    for(var k=0;k<state.pins.length;k++) {
      // Since these are all at the same PWM, there is no net current in the windings...
      state.nextpwm[i]=p;
    }
  }
  function motors_pwmcalc() {
    var i,j,p;
    for(i=0; i<2; i++) {   // 0->x 1->y
      p = state.origin[i] + state.offset[i];
      for(j=0;j<3; j++) {  // each of 3 pins
        state.nextpwm[j + i*3] = pwm_width(p + j/3);
      }
    }
  }
  function motors_update() {
    for(var k=0;k<state.pins.length;k++) {
      if(state.nextpwm[k] != state.written[k]) { // Only send if different
        console.log("motor_pos("+pp(state.pin[k],2,0)+", "+pp(state.nextpwm[k],3,0)+")");
        board.analogWrite(state.pin[k], state.nextpwm[k]);
        state.written[i]=state.nextpwm[k];
      }
    }
  }
  console.log("Ready!");

  for(var i=0;i<state.pins.length;i++) {
    board.pinMode(state.pins[i], five.Pin.PWM);
    state.written[i]=-1;  // Nothing written yet - will be written soon
  }
  motors_freewheel();
  motors_update();

  var led = new five.Led(8);
  led.blink(100);

  console.log("Use Up/Down/Left/Right arrows to control gimbal directly. Space to stop.");

  var origin_jog=[ 0.025, 0.025 ];

  process.stdin.resume();
  process.stdin.setEncoding("utf8");
  process.stdin.setRawMode(true);

  process.stdin.on("keypress", function(ch, key) {
    if (!key) {
      return;
    }

    var pwm = true;
    if (key.name === "q") {
      console.log("Quitting");
      process.exit();
    } else if (key.name === "up") {
      state.origin[1] += origin_jog[1];
    } else if (key.name === "down") {
      state.origin[1] -= origin_jog[1];
    } else if (key.name === "right") {
      state.origin[0] += origin_jog[0];
    } else if (key.name === "left") {
      state.origin[0] -= origin_jog[0];
    } else if (key.name === "space") {
      console.log("Reset");
      motors_freewheel();
      pwm = false; // Don't recalculate PWMs
    }
    if(pwm) {
      //console.log("(x,y)=("+pp(x,4,2)+","+pp(y,4,2)+")");
      motors_pwmcalc();
    }
    motors_update();
  });

  sub.on('data', function (buf) {
    var json=JSON.parse(buf);
    console.log("Executing :", json);
    var a=json.a || '';
    if(a=='to') {
      state.offset = json.xy;
      console.log("Moved to  :", x, y );
      motors_pwmcalc();
      motors_update();
    }

  });

});

function pp(v,width,dp) {
  var s="          "+v.toFixed(dp);
  return s.substr(s.length-width);
}
function pp62(v) {
  return pp(v,6,2);
}

function p2dp(x,y,z) {
  return "(" + pp(x,4,2) +","+ pp(y,4,2) +","+ pp(y,4,2) +")";
}

var pwm_mag=160;  // Can be up to 256 (very maximum...)
function pwm_width(pos) {  // pos is a fraction position, 1 loops around to 0
  //console.log("pwm_width("+pos+")");
  return (128 + Math.sin(2.0 * pos * 3.14159265) * pwm_mag / 2.0) | 0; // integer
}

<commit_msg>Sending over necessary changes only<commit_after>var five = require("johnny-five");

var nanomsg = require("nanomsg");
var sub = nanomsg.socket('sub');

var addr = 'tcp://127.0.0.1:7789';
sub.connect(addr);

var keypress = require("keypress");
keypress(process.stdin);

var state = {
  pins   :[11,10,09, 06,05,03], // x,x,x  y,y,y  Pin numbers
  written:[0,0,0,0,0,0],        // x,x,x  y,y,y
  nextpwm:[0,0,0,0,0,0],        // x,x,x  y,y,y
  origin: [0,0],  // origin_x, origin_y
  offset: [0,0]   // offset_x, offset_y
}

var board = new five.Board();
board.on("ready", function() {
  function motors_freewheel() {
    var p=pwm_width(0);
    for(var k=0;k<state.pins.length;k++) {
      // Since these are all at the same PWM, there is no net current in the windings...
      state.nextpwm[i]=p;
    }
  }
  function motors_pwmcalc() {
    var i,j,p;
    for(i=0; i<2; i++) {   // 0->x 1->y
      p = state.origin[i] + state.offset[i];
      for(j=0; j<3; j++) {  // each of 3 pins
        state.nextpwm[j + i*3] = pwm_width(p + j/3);
      }
    }
  }
  function motors_update() {
    for(var k=0; k<state.pins.length; k++) {
      if(state.nextpwm[k] != state.written[k]) { // Only send if different
        console.log("motor_pos("+pp(state.pins[k],2,0)+", "+pp(state.nextpwm[k],3,0)+")");
        board.analogWrite(state.pins[k], state.nextpwm[k]);
        state.written[k]=state.nextpwm[k];
      }
    }
  }
  console.log("Ready!");

  for(var i=0;i<state.pins.length;i++) {
    board.pinMode(state.pins[i], five.Pin.PWM);
    state.written[i]=-1;  // Nothing written yet - will be written soon
  }
  motors_freewheel();
  motors_update();

  var led = new five.Led(8);
  led.blink(100);

  console.log("Use Up/Down/Left/Right arrows to control gimbal directly. Space to stop.");

  var origin_jog=[ 0.025, 0.025 ];

  process.stdin.resume();
  process.stdin.setEncoding("utf8");
  process.stdin.setRawMode(true);

  process.stdin.on("keypress", function(ch, key) {
    if (!key) {
      return;
    }

    var pwm = true;
    if (key.name === "q") {
      console.log("Quitting");
      process.exit();
    } else if (key.name === "up") {
      state.origin[1] += origin_jog[1];
    } else if (key.name === "down") {
      state.origin[1] -= origin_jog[1];
    } else if (key.name === "left") {
      state.origin[0] += origin_jog[0];
    } else if (key.name === "right") {
      state.origin[0] -= origin_jog[0];
    } else if (key.name === "space") {
      console.log("Reset");
      motors_freewheel();
      pwm = false; // Don't recalculate PWMs
    }
    if(pwm) {
      //console.log("(x,y)=("+pp(x,4,2)+","+pp(y,4,2)+")");
      motors_pwmcalc();
    }
    motors_update();
  });

  sub.on('data', function (buf) {
    var json=JSON.parse(buf);
    console.log("Executing :", json);
    var a=json.a || '';
    if(a=='to') {
      state.offset = json.xy;
      console.log("Moved to  :", x, y );
      motors_pwmcalc();
      motors_update();
    }

  });

});

function pp(v,width,dp) {
  var s="          "+v.toFixed(dp);
  return s.substr(s.length-width);
}
function pp62(v) {
  return pp(v,6,2);
}

function p2dp(x,y,z) {
  return "(" + pp(x,4,2) +","+ pp(y,4,2) +","+ pp(y,4,2) +")";
}

var pwm_mag=160;  // Can be up to 256 (very maximum...)
function pwm_width(pos) {  // pos is a fraction position, 1 loops around to 0
  //console.log("pwm_width("+pos+")");
  return (128 + Math.sin(2.0 * pos * 3.14159265) * pwm_mag / 2.0) | 0; // integer
}

<|endoftext|>