<commit_before>(function () {
'use strict';

/*
 * AngularJS Toaster
 * Version: 0.4.10
 *
 * Copyright 2013 Jiri Kavulak.
 * All Rights Reserved.
 * Use, reproduction, distribution, and modification of this code is subject to the terms and
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * Author: Jiri Kavulak
 * Related to project of John Papa and Hans Fjällemark
 */

angular.module('toaster', ['ngAnimate'])
.constant('toasterConfig', {
    'limit': 0,                   // limits max number of toasts
    'tap-to-dismiss': true,
    'close-button': false,
    'newest-on-top': true,
    //'fade-in': 1000,            // done in css
    //'on-fade-in': undefined,    // not implemented
    //'fade-out': 1000,           // done in css
    // 'on-fade-out': undefined,  // not implemented
    //'extended-time-out': 1000,    // not implemented
    'time-out': 5000, // Set timeOut and extendedTimeout to 0 to make it sticky
    'icon-classes': {
        error: 'toast-error',
        info: 'toast-info',
        wait: 'toast-wait',
        success: 'toast-success',
        warning: 'toast-warning'
    },
    'body-output-type': '',// Options: '', 'trustedHtml', 'template', 'templateWithData'
    'body-template': 'toasterBodyTmpl.html',
    'icon-class': 'toast-info',
    'position-class': 'toast-top-right',
    'title-class': 'toast-title',
    'message-class': 'toast-message',
    'mouseover-timer-stop': true // stop timeout on mouseover and restart timer on mouseout
})
.service('toaster', ['$rootScope', 'toasterConfig', function ($rootScope, toasterConfig) {
    this.pop = function (type, title, body, timeout, bodyOutputType, clickHandler) {
        if (angular.isObject(type)) {
            var params = type; // NOTE: anable parameters as pop argument
            this.toast = {
                type: params.type,
                title: params.title,
                body: params.body,
                timeout: params.timeout,
                bodyOutputType: params.bodyOutputType,
                clickHandler: params.clickHandler
            };
        }
        else {
            this.toast = {
                type: type,
                title: title,
                body: body,
                timeout: timeout,
                bodyOutputType: bodyOutputType,
                clickHandler: clickHandler
            };
        }
        $rootScope.$emit('toaster-newToast');
    };

    this.clear = function () {
        $rootScope.$emit('toaster-clearToasts');
    };

    for (var type in toasterConfig['icon-classes']) {
    this[type] = (function (toasterType){
                    return function(title, body, timeout, bodyOutputType, clickHandler) {
                                if (angular.isString(title))
                                    this.pop(toasterType, title, body, timeout, bodyOutputType, clickHandler);
                                else
                                    this.pop(angular.extend(title, {type: toasterType}));
                               }
                     })(type);
    }
}])
.factory('toasterRegisterEvents', function() {

  var toasterFactory = {
      _NewToastEvent: false,
      _ClearAllToastsEvent: false,
      registerNewToastEvent: function(){
        this._NewToastEvent = true;
      },
      registerClearAllToastsEvent: function(){
        this._ClearAllToastsEvent = true;
      },
      deregisterNewToastEvent: function(){
        this._NewToastEvent = false;
      },
      deregisterClearAllToastsEvent: function(){
        this._ClearAllToastsEvent = false;
      },
      isRegisteredNewToastEvent: function(){
        return this._NewToastEvent;
      },
      isRegisteredClearAllToastsEvent: function(){
        return this._ClearAllToastsEvent;
      }
    }
    return {
      registerNewToastEvent: toasterFactory.registerNewToastEvent,
      registerClearAllToastsEvent: toasterFactory.registerClearAllToastsEvent,
		deregisterNewToastEvent: toasterFactory.deregisterNewToastEvent,
		deregisterClearAllToastsEvent: toasterFactory.deregisterClearAllToastsEvent,
      isRegisteredNewToastEvent: toasterFactory.isRegisteredNewToastEvent,
      isRegisteredClearAllToastsEvent: toasterFactory.isRegisteredClearAllToastsEvent
  }
})
.directive('toasterContainer', ['$parse', '$rootScope', '$interval', '$sce', 'toasterConfig', 'toaster', 'toasterRegisterEvents',
function ($parse, $rootScope, $interval, $sce, toasterConfig, toaster, toasterRegisterEvents) {
    return {
        replace: true,
        restrict: 'EA',
        scope: true, // creates an internal scope for this directive
        link: function (scope, elm, attrs) {
            var id = 0,
                mergedConfig;

            mergedConfig = angular.extend({}, toasterConfig, scope.$eval(attrs.toasterOptions));

            scope.config = {
                position: mergedConfig['position-class'],
                title: mergedConfig['title-class'],
                message: mergedConfig['message-class'],
                tap: mergedConfig['tap-to-dismiss'],
                closeButton: mergedConfig['close-button'],
                animation: mergedConfig['animation-class'],
                mouseoverTimer:  mergedConfig['mouseover-timer-stop']
            };

            scope.deregClearToasts = null;
            scope.deregNewToast = null;

            scope.$on("$destroy",function () {
                if (scope.deregClearToasts) scope.deregClearToasts();
                if (scope.deregNewToast) scope.deregNewToast();
                scope.deregClearToasts=null;
                scope.deregNewToast=null;
				toasterRegisterEvents.deregisterNewToastEvent();
				toasterRegisterEvents.deregisterClearAllToastsEvent();
            });

            scope.configureTimer = function configureTimer(toast) {
                var timeout = typeof (toast.timeout) == "number" ? toast.timeout : mergedConfig['time-out'];
                if (timeout > 0)
                    setTimeout(toast, timeout);
            };

            function addToast(toast) {
                toast.type = mergedConfig['icon-classes'][toast.type];
                if (!toast.type)
                    toast.type = mergedConfig['icon-class'];

                id++;
                angular.extend(toast, { id: id });

                // Set the toast.bodyOutputType to the default if it isn't set
                toast.bodyOutputType = toast.bodyOutputType || mergedConfig['body-output-type'];
                switch (toast.bodyOutputType) {
                    case 'trustedHtml':
                        toast.html = $sce.trustAsHtml(toast.body);
                        break;
                    case 'template':
                        toast.bodyTemplate = toast.body || mergedConfig['body-template'];
                        break;
                    case 'templateWithData':
                        var fcGet = $parse(toast.body || mergedConfig['body-template']);
                        var templateWithData = fcGet(scope);
                        toast.bodyTemplate = templateWithData.template;
                        toast.data = templateWithData.data;
                        break;
                }

                scope.configureTimer(toast);

                if (mergedConfig['newest-on-top'] === true) {
                    scope.toasters.unshift(toast);
                    if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                        scope.toasters.pop();
                    }
                } else {
                    scope.toasters.push(toast);
                    if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                        scope.toasters.shift();
                    }
                }

                toast.mouseover = false;
            }

            function setTimeout(toast, time) {
                toast.timeout = $interval(function () {
                    if (!toast.mouseover)
                        scope.removeToast(toast.id);
                }, time);
            }

            scope.toasters = [];

            if(!toasterRegisterEvents.isRegisteredNewToastEvent()){
                toasterRegisterEvents.registerNewToastEvent();
                scope.deregNewToast = $rootScope.$on('toaster-newToast', function () {
                    addToast(toaster.toast);
              });
            }

            if(!toasterRegisterEvents.isRegisteredClearAllToastsEvent()){
                toasterRegisterEvents.registerClearAllToastsEvent();
                scope.deregClearToasts = $rootScope.$on('toaster-clearToasts', function () {
                    scope.toasters.splice(0, scope.toasters.length);
              });
            }
        },
        controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {

            $scope.stopTimer = function (toast) {
                toast.mouseover = true;
                if ($scope.config.mouseoverTimer === true) {
                    if (toast.timeout) {
                        $interval.cancel(toast.timeout);
                        toast.timeout = null;
                    }
                }
            };

            $scope.restartTimer = function (toast) {
                toast.mouseover = false;
                if ($scope.config.mouseoverTimer === true) {
                    if (!toast.timeout)
                        $scope.configureTimer(toast);
                }
                else if (toast.timeout === null) {
                    $scope.removeToast(toaster.id);
                }
            };

            $scope.removeToast = function (id) {
                var i = 0;
                for (i; i < $scope.toasters.length; i++) {
                    if ($scope.toasters[i].id === id)
                        break;
                }
                $scope.toasters.splice(i, 1);
            };

            $scope.click = function (toaster, isCloseButton) {
                if ($scope.config.tap === true || isCloseButton == true) {
                    var removeToast = true;
                    if (toaster.clickHandler) {
                        if (angular.isFunction(toaster.clickHandler)) {
                            removeToast = toaster.clickHandler(toaster, isCloseButton);
                        }
                        else if (angular.isFunction($scope.$parent.$eval(toaster.clickHandler))) {
                            removeToast = $scope.$parent.$eval(toaster.clickHandler)(toaster, isCloseButton);
                        }
                        else {
                            console.log("TOAST-NOTE: Your click handler is not inside a parent scope of toaster-container.");
                        }
                    }
                    if (removeToast) {
                        $scope.removeToast(toaster.id);
                    }
                }
            };
        }],
        template:
        '
' +
            '
' +
              '<button class="toast-close-button" ng-show="config.closeButton" ng-click="click(toaster, true)">×</button>' +
              '
{{toaster.title}}
' +
              '
' +
                '

' +
                '

' +
                '

' +
                '
{{toaster.body}}
' +
              '
' +
            '
' +
        '
'
    };
}]);
})(window, document);
<commit_msg>Fixed some formatting<commit_after>(function () {
'use strict';

/*
 * AngularJS Toaster
 * Version: 0.4.10
 *
 * Copyright 2013 Jiri Kavulak.
 * All Rights Reserved.
 * Use, reproduction, distribution, and modification of this code is subject to the terms and
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * Author: Jiri Kavulak
 * Related to project of John Papa and Hans Fjällemark
 */

angular.module('toaster', ['ngAnimate'])
.constant('toasterConfig', {
    'limit': 0,                   // limits max number of toasts
    'tap-to-dismiss': true,
    'close-button': false,
    'newest-on-top': true,
    //'fade-in': 1000,            // done in css
    //'on-fade-in': undefined,    // not implemented
    //'fade-out': 1000,           // done in css
    // 'on-fade-out': undefined,  // not implemented
    //'extended-time-out': 1000,    // not implemented
    'time-out': 5000, // Set timeOut and extendedTimeout to 0 to make it sticky
    'icon-classes': {
        error: 'toast-error',
        info: 'toast-info',
        wait: 'toast-wait',
        success: 'toast-success',
        warning: 'toast-warning'
    },
    'body-output-type': '',// Options: '', 'trustedHtml', 'template', 'templateWithData'
    'body-template': 'toasterBodyTmpl.html',
    'icon-class': 'toast-info',
    'position-class': 'toast-top-right',
    'title-class': 'toast-title',
    'message-class': 'toast-message',
    'mouseover-timer-stop': true // stop timeout on mouseover and restart timer on mouseout
})
.service('toaster', ['$rootScope', 'toasterConfig', function ($rootScope, toasterConfig) {
    this.pop = function (type, title, body, timeout, bodyOutputType, clickHandler) {
        if (angular.isObject(type)) {
            var params = type; // NOTE: anable parameters as pop argument
            this.toast = {
                type: params.type,
                title: params.title,
                body: params.body,
                timeout: params.timeout,
                bodyOutputType: params.bodyOutputType,
                clickHandler: params.clickHandler
            };
        }
        else {
            this.toast = {
                type: type,
                title: title,
                body: body,
                timeout: timeout,
                bodyOutputType: bodyOutputType,
                clickHandler: clickHandler
            };
        }
        $rootScope.$emit('toaster-newToast');
    };

    this.clear = function () {
        $rootScope.$emit('toaster-clearToasts');
    };

    for (var type in toasterConfig['icon-classes']) {
    this[type] = (function (toasterType){
                    return function(title, body, timeout, bodyOutputType, clickHandler) {
                                if (angular.isString(title))
                                    this.pop(toasterType, title, body, timeout, bodyOutputType, clickHandler);
                                else
                                    this.pop(angular.extend(title, {type: toasterType}));
                               }
                     })(type);
    }
}])
.factory('toasterRegisterEvents', function() {

  var toasterFactory = {
      _NewToastEvent: false,
      _ClearAllToastsEvent: false,
      registerNewToastEvent: function(){
        this._NewToastEvent = true;
      },
      registerClearAllToastsEvent: function(){
        this._ClearAllToastsEvent = true;
      },
      deregisterNewToastEvent: function(){
        this._NewToastEvent = false;
      },
      deregisterClearAllToastsEvent: function(){
        this._ClearAllToastsEvent = false;
      },
      isRegisteredNewToastEvent: function(){
        return this._NewToastEvent;
      },
      isRegisteredClearAllToastsEvent: function(){
        return this._ClearAllToastsEvent;
      }
    }
    return {
      registerNewToastEvent: toasterFactory.registerNewToastEvent,
      registerClearAllToastsEvent: toasterFactory.registerClearAllToastsEvent,
      deregisterNewToastEvent: toasterFactory.deregisterNewToastEvent,
      deregisterClearAllToastsEvent: toasterFactory.deregisterClearAllToastsEvent,
      isRegisteredNewToastEvent: toasterFactory.isRegisteredNewToastEvent,
      isRegisteredClearAllToastsEvent: toasterFactory.isRegisteredClearAllToastsEvent
  }
})
.directive('toasterContainer', ['$parse', '$rootScope', '$interval', '$sce', 'toasterConfig', 'toaster', 'toasterRegisterEvents',
function ($parse, $rootScope, $interval, $sce, toasterConfig, toaster, toasterRegisterEvents) {
    return {
        replace: true,
        restrict: 'EA',
        scope: true, // creates an internal scope for this directive
        link: function (scope, elm, attrs) {
            var id = 0,
                mergedConfig;

            mergedConfig = angular.extend({}, toasterConfig, scope.$eval(attrs.toasterOptions));

            scope.config = {
                position: mergedConfig['position-class'],
                title: mergedConfig['title-class'],
                message: mergedConfig['message-class'],
                tap: mergedConfig['tap-to-dismiss'],
                closeButton: mergedConfig['close-button'],
                animation: mergedConfig['animation-class'],
                mouseoverTimer:  mergedConfig['mouseover-timer-stop']
            };

            scope.deregClearToasts = null;
            scope.deregNewToast = null;

            scope.$on("$destroy",function () {
                if (scope.deregClearToasts) scope.deregClearToasts();
                if (scope.deregNewToast) scope.deregNewToast();
                scope.deregClearToasts=null;
                scope.deregNewToast=null;
                toasterRegisterEvents.deregisterNewToastEvent();
                toasterRegisterEvents.deregisterClearAllToastsEvent();
            });

            scope.configureTimer = function configureTimer(toast) {
                var timeout = typeof (toast.timeout) == "number" ? toast.timeout : mergedConfig['time-out'];
                if (timeout > 0)
                    setTimeout(toast, timeout);
            };

            function addToast(toast) {
                toast.type = mergedConfig['icon-classes'][toast.type];
                if (!toast.type)
                    toast.type = mergedConfig['icon-class'];

                id++;
                angular.extend(toast, { id: id });

                // Set the toast.bodyOutputType to the default if it isn't set
                toast.bodyOutputType = toast.bodyOutputType || mergedConfig['body-output-type'];
                switch (toast.bodyOutputType) {
                    case 'trustedHtml':
                        toast.html = $sce.trustAsHtml(toast.body);
                        break;
                    case 'template':
                        toast.bodyTemplate = toast.body || mergedConfig['body-template'];
                        break;
                    case 'templateWithData':
                        var fcGet = $parse(toast.body || mergedConfig['body-template']);
                        var templateWithData = fcGet(scope);
                        toast.bodyTemplate = templateWithData.template;
                        toast.data = templateWithData.data;
                        break;
                }

                scope.configureTimer(toast);

                if (mergedConfig['newest-on-top'] === true) {
                    scope.toasters.unshift(toast);
                    if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                        scope.toasters.pop();
                    }
                } else {
                    scope.toasters.push(toast);
                    if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                        scope.toasters.shift();
                    }
                }

                toast.mouseover = false;
            }

            function setTimeout(toast, time) {
                toast.timeout = $interval(function () {
                    if (!toast.mouseover)
                        scope.removeToast(toast.id);
                }, time);
            }

            scope.toasters = [];

            if(!toasterRegisterEvents.isRegisteredNewToastEvent()){
                toasterRegisterEvents.registerNewToastEvent();
                scope.deregNewToast = $rootScope.$on('toaster-newToast', function () {
                    addToast(toaster.toast);
              });
            }

            if(!toasterRegisterEvents.isRegisteredClearAllToastsEvent()){
                toasterRegisterEvents.registerClearAllToastsEvent();
                scope.deregClearToasts = $rootScope.$on('toaster-clearToasts', function () {
                    scope.toasters.splice(0, scope.toasters.length);
              });
            }
        },
        controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {

            $scope.stopTimer = function (toast) {
                toast.mouseover = true;
                if ($scope.config.mouseoverTimer === true) {
                    if (toast.timeout) {
                        $interval.cancel(toast.timeout);
                        toast.timeout = null;
                    }
                }
            };

            $scope.restartTimer = function (toast) {
                toast.mouseover = false;
                if ($scope.config.mouseoverTimer === true) {
                    if (!toast.timeout)
                        $scope.configureTimer(toast);
                }
                else if (toast.timeout === null) {
                    $scope.removeToast(toaster.id);
                }
            };

            $scope.removeToast = function (id) {
                var i = 0;
                for (i; i < $scope.toasters.length; i++) {
                    if ($scope.toasters[i].id === id)
                        break;
                }
                $scope.toasters.splice(i, 1);
            };

            $scope.click = function (toaster, isCloseButton) {
                if ($scope.config.tap === true || isCloseButton == true) {
                    var removeToast = true;
                    if (toaster.clickHandler) {
                        if (angular.isFunction(toaster.clickHandler)) {
                            removeToast = toaster.clickHandler(toaster, isCloseButton);
                        }
                        else if (angular.isFunction($scope.$parent.$eval(toaster.clickHandler))) {
                            removeToast = $scope.$parent.$eval(toaster.clickHandler)(toaster, isCloseButton);
                        }
                        else {
                            console.log("TOAST-NOTE: Your click handler is not inside a parent scope of toaster-container.");
                        }
                    }
                    if (removeToast) {
                        $scope.removeToast(toaster.id);
                    }
                }
            };
        }],
        template:
        '
' +
            '
' +
              '<button class="toast-close-button" ng-show="config.closeButton" ng-click="click(toaster, true)">×</button>' +
              '
{{toaster.title}}
' +
              '
' +
                '

' +
                '

' +
                '

' +
                '
{{toaster.body}}
' +
              '
' +
            '
' +
        '
'
    };
}]);
})(window, document);
<|endoftext|>


<commit_before>$(function() {
  $(".plan-guard").draggable({ revert: true });
  $(".plan-action").draggable({ revert: true });

  var set_class = function() {
    $(".step-guard").droppable({
      accept: '.plan-guard',
      activeClass: 'ui-state-hover',
      hoverClass: 'ui-state-hover',
      drop: function(event, ui) {
        var d = ui['draggable'];
        $(this).children('ul').append('
'+d.html()+'
');
      }
    });

    $(".step-action").droppable({
      accept: '.plan-action',
      activeClass: 'ui-state-hover',
      hoverClass: 'ui-state-hover',
      drop: function(event, ui) {
        var d = ui['draggable'];
        $(this).children('ul').append('
'+d.html()+'
');
      }
    });

    $(".items").sortable({ placeholder: 'ui-state-highlight' });

    $("#plan").sortable({
      placeholder: 'ui-state-highlight'
    });
  };

  var prefix     = $("#prefix").val();
  var plan_name  = $("#plan_name").val();

  var guards_holder  = '

Guards

';
  var actions_holder = '

Actions

';
  var step_holder    = guards_holder+actions_holder;

  var guard_selector  = "#plan > li:last-child > .step-guard  > ul";
  var action_selector = "#plan > li:last-child > .step-action > ul";

  /* Load the data from the server */
  $.getJSON( prefix+'/json/billing/billing_plan', { plan_name: plan_name }, function(data){

    /* Remove all child nodes */
    $("#plan").empty();

    var step_i;
    for (step_i in data.rating_steps) {
      var step = data.rating_steps[step_i];

      $("#plan").append('
'+step_holder+'
');

      var guard_i;
      for (guard_i  in step.guards) {
        var guard = step.guards[guard_i];

        /* each guard is an array: [ name, p0, p1, .. ] */
        var name = guard.shift();

        $(guard_selector).append("

");

        /* Copy the template for this name */
        $("#"+name).clone().children().appendTo(guard_selector+" > li");

        /* Populate the parameters */
        for (i in guard) {
          var selector = "#plan > li:last-child > .step-guard > ul input,select[name='p"+i+"']";
          $(selector).val(guard[i]);
        }
      }

      var action_i;
      for (action_i in step.actions) {
        var action = step.actions[action_i];

        /* each action is an array: [ name, p0, p1, .. ] */
        var name = action.shift();

        $(action_selector).append("

");

        /* Copy the template for this name */
        $("#"+name).clone().children().appendTo(action_selector+" > li");

        /* Populate the parameters */
        var i;
        for (i in action) {
          var selector = "#plan > li:last-child > .step-action > ul input,select[name='p"+i+"']";
          $(selector).val(action[i]);
        }
      }
    }
    set_class();
  });

  $("#add_step").click(function(ev){
     $("#plan").append('
'+step_holder+'
');
     set_class();
  });

  $("#submit_steps").click(function(ev){
    var rating_steps = [];

    /* For each step ... */
    $("#plan > li").each(function(step_i){
      var guards  = [];
      var actions = [];

      /* Collect the guards and their parameters */
      $(this).children().filter(".step-guard > ul > li").each(function(guard_i){
        guards[guard_i] = [];
        var i;
        for(i=0;i<=2;i++) {
          var v = $(this).children.filter("[name='p"+i+"']");
          if(v) guards[guard_i][i] = v;
        }
      });
      /* Collect the actions and their parameters */
      $(this).children().filter(".step-action > ul > li").each(function(action_i){
        actions[action_i] = [];
        var i;
        for(i=0;i<=2;i++) {
          var v = $(this).children.filter("[name='p"+i+"']");
          if(v) actions[action_i][i] = v;
        }
      });
      /* Skip any node that has no actions (it's OK to not have guards) */
      if(actions.length) {
        rating_steps[step_i] = { guards: guards, actions: actions };
      }
    });

    rating_steps = JSON.stringify(rating_steps);

    $.post( prefix+'/json/billing/billing_plan', { plan_name: plan_name, rating_steps: rating_steps }, function(data){
      /* we will get { ok: "true" } iff everything went OK */
    });
  });
});
<commit_msg>proper find(); gather value<commit_after>$(function() {
  $(".plan-guard").draggable({ revert: true });
  $(".plan-action").draggable({ revert: true });

  var set_class = function() {
    $(".step-guard").droppable({
      accept: '.plan-guard',
      activeClass: 'ui-state-hover',
      hoverClass: 'ui-state-hover',
      drop: function(event, ui) {
        var d = ui['draggable'];
        $(this).children('ul').append('
'+d.html()+'
');
      }
    });

    $(".step-action").droppable({
      accept: '.plan-action',
      activeClass: 'ui-state-hover',
      hoverClass: 'ui-state-hover',
      drop: function(event, ui) {
        var d = ui['draggable'];
        $(this).children('ul').append('
'+d.html()+'
');
      }
    });

    $(".items").sortable({ placeholder: 'ui-state-highlight' });

    $("#plan").sortable({
      placeholder: 'ui-state-highlight'
    });
  };

  var prefix     = $("#prefix").val();
  var plan_name  = $("#plan_name").val();

  var guards_holder  = '

Guards

';
  var actions_holder = '

Actions

';
  var step_holder    = guards_holder+actions_holder;

  var guard_selector  = "#plan > li:last-child > .step-guard  > ul";
  var action_selector = "#plan > li:last-child > .step-action > ul";

  /* Load the data from the server */
  $.getJSON( prefix+'/json/billing/billing_plan', { plan_name: plan_name }, function(data){

    /* Remove all child nodes */
    $("#plan").empty();

    var step_i;
    for (step_i in data.rating_steps) {
      var step = data.rating_steps[step_i];

      $("#plan").append('
'+step_holder+'
');

      var guard_i;
      for (guard_i  in step.guards) {
        var guard = step.guards[guard_i];

        /* each guard is an array: [ name, p0, p1, .. ] */
        var name = guard.shift();

        $(guard_selector).append("

");

        /* Copy the template for this name */
        $("#"+name).clone().children().appendTo(guard_selector+" > li");

        /* Populate the parameters */
        for (i in guard) {
          var selector = "#plan > li:last-child > .step-guard > ul input,select[name='p"+i+"']";
          $(selector).val(guard[i]);
        }
      }

      var action_i;
      for (action_i in step.actions) {
        var action = step.actions[action_i];

        /* each action is an array: [ name, p0, p1, .. ] */
        var name = action.shift();

        $(action_selector).append("

");

        /* Copy the template for this name */
        $("#"+name).clone().children().appendTo(action_selector+" > li");

        /* Populate the parameters */
        var i;
        for (i in action) {
          var selector = "#plan > li:last-child > .step-action > ul input,select[name='p"+i+"']";
          $(selector).val(action[i]);
        }
      }
    }
    set_class();
  });

  $("#add_step").click(function(ev){
     $("#plan").append('
'+step_holder+'
');
     set_class();
  });

  $("#submit_steps").click(function(ev){
    var rating_steps = [];

    /* For each step ... */
    $("#plan > li").each(function(step_i){
      var guards  = [];
      var actions = [];

      /* Collect the guards and their parameters */
      $(".step-guard > ul > li",this).each(function(guard_i){
        guards[guard_i] = [];
        var i;
        for(i=0;i<=2;i++) {
          var v = $("[name='p"+i+"']",this);
          if(v) guards[guard_i][i] = v.val();
        }
      });
      /* Collect the actions and their parameters */
      $(".step-action > ul > li",this).each(function(action_i){
        actions[action_i] = [];
        var i;
        for(i=0;i<=2;i++) {
          var v = $("[name='p"+i+"']",this);
          if(v) actions[action_i][i] = v.val();
        }
      });
      /* Skip any node that has no actions (it's OK to not have guards) */
      if(actions.length) {
        rating_steps[step_i] = { guards: guards, actions: actions };
      }
    });

    rating_steps = JSON.stringify(rating_steps);

    $.post( prefix+'/json/billing/billing_plan', { plan_name: plan_name, rating_steps: rating_steps }, function(data){
      /* we will get { ok: "true" } iff everything went OK */
    });
  });
});
<|endoftext|>


<commit_before>/**
 *
 * jQuery module for accessible data tables
 *
 * Copyright (C) 2013 Dylan Barrell. All Rights Reserved as specified in the LICENSE file
 *
 */

(function (jQuery){
    var methods;

    methods = {
        init: function (options) {
            var opts = jQuery.extend({}, jQuery.fn.tables.defaults, options);
            return this.each(function () {
                var $table = jQuery(this),
                    $anchors, data, timeout, $select, cellIndex, dimensons, resizeTimer;

                function anchorClickHandler(e) {
                    var $this = jQuery(this),
                        sorted = $this.attr("data-sorted"),
                        direction = "asc",
                        index = this.parentNode.cellIndex,
                        $span = $this.find("span.offscreen"),
                        msg;

                    if (sorted) {
                        direction = (sorted === "asc" ? "desc" : "asc");
                    }
                    // reset all the previous sorting
                    $anchors.removeAttr("data-sorted");
                    sortTableData(data, direction, index);
                    redrawTable($table, data);
                    $this.attr("data-sorted", direction);
                    // Reset the offscreen text
                    $span.text("");
                    // Make announcement
                    if (direction === "asc") {
                        msg = jQuery.a11yfy.getI18nString("tableSortedAscending", {
                            column: $this.text()
                        }, jQuery.fn.tables.defaults.strings);
                    } else {
                        msg = jQuery.a11yfy.getI18nString("tableSortedDescending", {
                            column: $this.text()
                        }, jQuery.fn.tables.defaults.strings);
                    }
                    jQuery.a11yfy.politeAnnounce(msg);
                    // Set the offscreen text
                    setSortedText($span, $this);
                    e.preventDefault();
                }

                function selectChangeHandler() {
                    var $this = jQuery(this),
                        val = $this.val(),
                        $anchor = $this.parent().find("a"),
                        cellIndex = this.parentNode.cellIndex,
                        msg;

                    jQuery(data).each(function (index, value) {
                        if (val+"" === value[cellIndex]+"" || val === "__none__") {
                            value[value.length-1].show();
                        } else {
                            value[value.length-1].hide();
                        }
                    });
                    // Make announcement
                    msg = jQuery.a11yfy.getI18nString("tableFilteredOnAndBy", {
                        column: $anchor.text(),
                        value: (val === "__none__" ? jQuery.a11yfy.getI18nString("all") : val)
                    }, jQuery.fn.tables.defaults.strings);
                    jQuery.a11yfy.politeAnnounce(msg);

                    $this.hide();
                    $anchor.show().focus();
                }

                if (opts.sortFilter !== "none") {
                    if (opts.responsiveColumns) {
                        throw "responsiveColumns and sortFilter are mutually exclusive options because sortFilter implies a data table with row data and responsiveColumns implies columnar data";
                    }
                    $table.find("th").each(function (index, value) {
                        var $this = jQuery(value);

                        if ($this.attr("data-filter") &&
                            (opts.sortFilter === "both" || opts.sortFilter === "filter")) {
                            $this.wrapInner("");
                        } else if (!$this.attr("data-filter") && (opts.sortFilter === "both" || opts.sortFilter === "sort")) {
                            $this.wrapInner("");
                        }
                    });

                    $anchors = $table.find("th a");
                    data = getTableData($table);
                    $anchors.each( function (index, anchor) {
                        var $anchor = jQuery(anchor),
                            timeout;

                        function anchorFocusHandler(e) {
                            var $this = jQuery(this),
                                $span;

                            if ($this.attr("data-filter")) {
                                if (timeout) {
                                    clearTimeout(timeout);
                                    timeout = undefined;
                                }
                                $select = $this.parent().find("select");
                                cellIndex = $this.parent().get(0).cellIndex;
                                if (!$select.length) {
                                    $select = jQuery("<select>").attr("aria-label", $this.text() + jQuery.a11yfy.getI18nString("filterable", undefined, jQuery.fn.tables.defaults.strings));
                                    $select.append(jQuery("<option>").attr("value", "__none__").attr("label", jQuery.a11yfy.getI18nString("all", undefined, jQuery.fn.tables.defaults.strings)));
                                    jQuery(data).each(function (index, value) {
                                        $select.append(jQuery("<option>").text(value[cellIndex]));
                                    });
                                    $this.parent().append($select);
                                    $select.bind("mouseover focus", selectFocusHandler)
                                        .bind("mouseout blur", selectBlurHandler)
                                        .bind("change", selectChangeHandler);
                                } else {
                                    $select.show();
                                }
                                if (e.type === "focus") {
                                    $select.focus();
                                }
                                $this.hide();
                            } else {
                                $span = $this.find("span.offscreen");
                                if (!$span.length) {
                                    $span = jQuery("");
                                    $this.append($span);
                                }
                                setSortedText($span, $this);
                            }

                        }

                        function anchorBlurHandler() {
                            var $this = jQuery(this), $span;

                            if (!$this.attr("data-filter")) {
                                $span = $this.find("span.offscreen");
                                $span.empty().text("");
                            }
                        }

                        function selectFocusHandler() {
                            if (timeout) {
                                clearTimeout(timeout);
                                timeout = undefined;
                            }
                        }

                        function selectBlurHandler() {
                            var $this = jQuery(this);
                            timeout = setTimeout(function () {
                                $this.hide();
                                $this.parent().find("a").show();
                            }, 500);
                        }

                        $anchor.bind("click", anchorClickHandler)
                            .bind("focus mouseover", anchorFocusHandler)
                            .bind("blur mouseout", anchorBlurHandler);
                    });
                    if ((opts.sortFilter === "both" || opts.sortFilter === "sort")) {
                        $anchors.first().click();
                    }
                } else if (opts.responsiveColumns) {
                    data = getTableData($table);
                    headers = getTableHeaders($table);
                    dimensions = getDimensions();
                    drawTable( $table, data, headers, dimensions, opts);
                    jQuery(window).on("resize", function (e) {
                        newDimensions = getDimensions();
                        if (!equalDimensions(newDimensions, dimensions)) {
                            if (resizeTimer) {
                                clearTimeout(resizeTimer);
                                resizeTimer = undefined;
                            }
                            dimensions = newDimensions;
                            resizeTimer = setTimeout(function () {
                                drawTable( $table, data, headers, newDimensions, opts);
                            }, 50);
                        }
                    });
                }
            });
        },
        destroy: function () {
            return this.each(function () {
                // Do something
            });
        }
    };

    function drawSmartPhoneTable(data, headers, options) {
        var html = '', i, _ilen, j, _jlen;
        for (i = 0, _ilen = data[0].length - 1; i < _ilen; i++) {
            html += '
';
            if (headers) {
                html += '' + headers[i] + '	';
            }
            for (j = 0, _jlen = data.length; j < _jlen; j++) {
                html += '' + data[j][i] + '	';
            }
            html += '
';
        }
        return html;
    }

    function drawDesktopTable(data, headers, options) {
        var html = '', i, _ilen, j, _jlen;
        if (headers) {
            html += '
';
            jQuery(headers).each(function (index, value) {
                html += '' + value + '	';
            });
            html += '
';
        }
        for (j = 0, _jlen = data.length; j < _jlen; j++) {
            html += '
';
            for (i = 0, _ilen = data[0].length - 1; i < _ilen; i++) {
                html += '' + data[j][i] + '	';
            }
            html += '
';
        }
        return html;
    }

    function isSmartPhone(dimensions, breakPoint) {
        if (dimensions.width <= breakPoint) {
            return true;
        }
        return false;
    }

    function drawTable($table, data, headers, dimensions, options) {
        if (isSmartPhone(dimensions, options.responsiveColumns.breakPoint)) {
            $table.html(drawSmartPhoneTable(data, headers, options));
        } else {
            $table.html(drawDesktopTable(data, headers, options));
        }
    }

    function getDimensions() {
        var retVal = { width: 0, height: 0};
        retVal.width = window.innerWidth-1;
        retVal.height = window.innerHeight;
        return retVal;
    }

    function equalDimensions(first, second) {
        if (first.width === second.width && first.height === second.height) {
            return true;
        }
        return false;
    }

    function getSortedText($this) {
        var sorted = $this.attr("data-sorted");
        return (sorted === "asc" ? jQuery.a11yfy.getI18nString("sortableSortedAscending", undefined, jQuery.fn.tables.defaults.strings) :
                (sorted === "desc" ? jQuery.a11yfy.getI18nString("sortableSortedDescending", undefined, jQuery.fn.tables.defaults.strings) :
                jQuery.a11yfy.getI18nString("sortableNotSorted", undefined, jQuery.fn.tables.defaults.strings)));
    }

    function getTableData($table) {
        var retVal = [];
        $table.find("tbody tr").each(function (index, value) {
            var $this = jQuery(value), row = [];
            $this.find("td").each(function (index, td) {
                var text = jQuery.trim(jQuery(td).text()),
                    intNum, flt;

                intNum = parseInt(text, 10);
                flt = parseFloat(text);
                if (intNum.toString() === text) {
                    row.push(intNum);
                } else if (flt.toString() === text) {
                    row.push(flt);
                } else {
                    row.push(text);
                }
            });
            row.push($this); // put the row into the data so we can manipulate
            retVal.push(row);
        });
        return retVal;
    }
    function getTableHeaders($table) {
        var retVal = [];
        $table.find('tr').first().find('th').each(function (index, value) {
            var $this = jQuery(value);
            retVal.push($this.text());
        });
        return retVal;
    }

    function sortTableData(data, direction, index) {
        data.sort(function (first, second) {
            if (typeof first[index] !== typeof second[index]) {
                if (typeof first[index] === "string") {
                    return (direction === "asc" ? -1 : 1);
                } else if (typeof second[index] === "string") {
                    return (direction === "asc" ? 1 : -1);
                }
            }
            return first[index] < second[index] ? (direction === "asc" ? -1 : 1) :
                    ( first[index] > second[index] ? (direction === "asc" ? 1 : -1) : 0);
        });
    }
    function redrawTable($table, data) {
        var $tbody = $table.find("tbody");
        jQuery(data).each(function (index, value) {
            $tbody.append(value[value.length - 1]);
        });
    }
    function setSortedText($span, $this) {
        $span.text(getSortedText($this));
    }

    // add the jquery instance method
    jQuery.fn.tables = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1 ));
        } else if (typeof method === "object" || ! method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error("Method " +  method + " does not exist on jQuery.tables");
        }
    };

    jQuery.fn.tables.defaults = {
        sortFilter: "both",
        strings : {
            sortableSortedAscending: " Sortable, Sorted Ascending",
            sortableNotSorted: " Sortable, Not Sorted",
            sortableSortedDescending: " Sortable, Sorted Descending",
            filterable: ", Filterable",
            all: "All",
            tableSortedAscending: "Table sorted by ${column}, Ascending",
            tableSortedDescending: "Table sorted by ${column}, Descending",
            tableFilteredOnAndBy: "Table filtered on ${column}, by ${value}"
        }
    };
})(jQuery);
<commit_msg>add support for responsive css<commit_after>/**
 *
 * jQuery module for accessible data tables
 *
 * Copyright (C) 2013 Dylan Barrell. All Rights Reserved as specified in the LICENSE file
 *
 */

(function (jQuery){
    var methods;

    methods = {
        init: function (options) {
            var opts = jQuery.extend({}, jQuery.fn.tables.defaults, options);
            return this.each(function () {
                var $table = jQuery(this),
                    $anchors, data, timeout, $select, cellIndex, dimensons, resizeTimer;

                function anchorClickHandler(e) {
                    var $this = jQuery(this),
                        sorted = $this.attr("data-sorted"),
                        direction = "asc",
                        index = this.parentNode.cellIndex,
                        $span = $this.find("span.offscreen"),
                        msg;

                    if (sorted) {
                        direction = (sorted === "asc" ? "desc" : "asc");
                    }
                    // reset all the previous sorting
                    $anchors.removeAttr("data-sorted");
                    sortTableData(data, direction, index);
                    redrawTable($table, data);
                    $this.attr("data-sorted", direction);
                    // Reset the offscreen text
                    $span.text("");
                    // Make announcement
                    if (direction === "asc") {
                        msg = jQuery.a11yfy.getI18nString("tableSortedAscending", {
                            column: $this.text()
                        }, jQuery.fn.tables.defaults.strings);
                    } else {
                        msg = jQuery.a11yfy.getI18nString("tableSortedDescending", {
                            column: $this.text()
                        }, jQuery.fn.tables.defaults.strings);
                    }
                    jQuery.a11yfy.politeAnnounce(msg);
                    // Set the offscreen text
                    setSortedText($span, $this);
                    e.preventDefault();
                }

                function selectChangeHandler() {
                    var $this = jQuery(this),
                        val = $this.val(),
                        $anchor = $this.parent().find("a"),
                        cellIndex = this.parentNode.cellIndex,
                        msg;

                    jQuery(data).each(function (index, value) {
                        if (val+"" === value[cellIndex]+"" || val === "__none__") {
                            value[value.length-1].show();
                        } else {
                            value[value.length-1].hide();
                        }
                    });
                    // Make announcement
                    msg = jQuery.a11yfy.getI18nString("tableFilteredOnAndBy", {
                        column: $anchor.text(),
                        value: (val === "__none__" ? jQuery.a11yfy.getI18nString("all") : val)
                    }, jQuery.fn.tables.defaults.strings);
                    jQuery.a11yfy.politeAnnounce(msg);

                    $this.hide();
                    $anchor.show().focus();
                }

                if (opts.sortFilter !== "none") {
                    if (opts.responsiveColumns) {
                        throw "responsiveColumns and sortFilter are mutually exclusive options because sortFilter implies a data table with row data and responsiveColumns implies columnar data";
                    }
                    $table.find("th").each(function (index, value) {
                        var $this = jQuery(value);

                        if ($this.attr("data-filter") &&
                            (opts.sortFilter === "both" || opts.sortFilter === "filter")) {
                            $this.wrapInner("");
                        } else if (!$this.attr("data-filter") && (opts.sortFilter === "both" || opts.sortFilter === "sort")) {
                            $this.wrapInner("");
                        }
                    });

                    $anchors = $table.find("th a");
                    data = getTableData($table);
                    $anchors.each( function (index, anchor) {
                        var $anchor = jQuery(anchor),
                            timeout;

                        function anchorFocusHandler(e) {
                            var $this = jQuery(this),
                                $span;

                            if ($this.attr("data-filter")) {
                                if (timeout) {
                                    clearTimeout(timeout);
                                    timeout = undefined;
                                }
                                $select = $this.parent().find("select");
                                cellIndex = $this.parent().get(0).cellIndex;
                                if (!$select.length) {
                                    $select = jQuery("<select>").attr("aria-label", $this.text() + jQuery.a11yfy.getI18nString("filterable", undefined, jQuery.fn.tables.defaults.strings));
                                    $select.append(jQuery("<option>").attr("value", "__none__").attr("label", jQuery.a11yfy.getI18nString("all", undefined, jQuery.fn.tables.defaults.strings)));
                                    jQuery(data).each(function (index, value) {
                                        $select.append(jQuery("<option>").text(value[cellIndex]));
                                    });
                                    $this.parent().append($select);
                                    $select.bind("mouseover focus", selectFocusHandler)
                                        .bind("mouseout blur", selectBlurHandler)
                                        .bind("change", selectChangeHandler);
                                } else {
                                    $select.show();
                                }
                                if (e.type === "focus") {
                                    $select.focus();
                                }
                                $this.hide();
                            } else {
                                $span = $this.find("span.offscreen");
                                if (!$span.length) {
                                    $span = jQuery("");
                                    $this.append($span);
                                }
                                setSortedText($span, $this);
                            }

                        }

                        function anchorBlurHandler() {
                            var $this = jQuery(this), $span;

                            if (!$this.attr("data-filter")) {
                                $span = $this.find("span.offscreen");
                                $span.empty().text("");
                            }
                        }

                        function selectFocusHandler() {
                            if (timeout) {
                                clearTimeout(timeout);
                                timeout = undefined;
                            }
                        }

                        function selectBlurHandler() {
                            var $this = jQuery(this);
                            timeout = setTimeout(function () {
                                $this.hide();
                                $this.parent().find("a").show();
                            }, 500);
                        }

                        $anchor.bind("click", anchorClickHandler)
                            .bind("focus mouseover", anchorFocusHandler)
                            .bind("blur mouseout", anchorBlurHandler);
                    });
                    if ((opts.sortFilter === "both" || opts.sortFilter === "sort")) {
                        $anchors.first().click();
                    }
                } else if (opts.responsiveColumns) {
                    data = getTableData($table);
                    headers = getTableHeaders($table);
                    dimensions = getDimensions();
                    drawTable( $table, data, headers, dimensions, opts);
                    jQuery(window).on("resize", function (e) {
                        newDimensions = getDimensions();
                        if (!equalDimensions(newDimensions, dimensions)) {
                            if (resizeTimer) {
                                clearTimeout(resizeTimer);
                                resizeTimer = undefined;
                            }
                            dimensions = newDimensions;
                            resizeTimer = setTimeout(function () {
                                drawTable( $table, data, headers, newDimensions, opts);
                            }, 50);
                        }
                    });
                    if (opts.responsiveColumns.css) {
                        jQuery("body").append(
                            jQuery(""));
                    }
                }
            });
        },
        destroy: function () {
            return this.each(function () {
                // Do something
            });
        }
    };

    function drawSmartPhoneTable(data, headers, options) {
        var html = '', i, _ilen, j, _jlen;
        for (i = 0, _ilen = data[0].length - 1; i < _ilen; i++) {
            html += '
';
            if (headers) {
                html += '' + headers[i] + '	';
            }
            for (j = 0, _jlen = data.length; j < _jlen; j++) {
                html += '' + data[j][i] + '	';
            }
            html += '
';
        }
        return html;
    }

    function drawDesktopTable(data, headers, options) {
        var html = '', i, _ilen, j, _jlen;
        if (headers) {
            html += '
';
            jQuery(headers).each(function (index, value) {
                html += '' + value + '	';
            });
            html += '
';
        }
        for (j = 0, _jlen = data.length; j < _jlen; j++) {
            html += '
';
            for (i = 0, _ilen = data[0].length - 1; i < _ilen; i++) {
                html += '' + data[j][i] + '	';
            }
            html += '
';
        }
        return html;
    }

    function isSmartPhone(dimensions, breakPoint) {
        if (dimensions.width <= breakPoint) {
            return true;
        }
        return false;
    }

    function drawTable($table, data, headers, dimensions, options) {
        if (isSmartPhone(dimensions, options.responsiveColumns.breakPoint)) {
            $table.html(drawSmartPhoneTable(data, headers, options));
        } else {
            $table.html(drawDesktopTable(data, headers, options));
        }
    }

    function getDimensions() {
        var retVal = { width: 0, height: 0};
        retVal.width = window.innerWidth-1;
        retVal.height = window.innerHeight;
        return retVal;
    }

    function equalDimensions(first, second) {
        if (first.width === second.width && first.height === second.height) {
            return true;
        }
        return false;
    }

    function getSortedText($this) {
        var sorted = $this.attr("data-sorted");
        return (sorted === "asc" ? jQuery.a11yfy.getI18nString("sortableSortedAscending", undefined, jQuery.fn.tables.defaults.strings) :
                (sorted === "desc" ? jQuery.a11yfy.getI18nString("sortableSortedDescending", undefined, jQuery.fn.tables.defaults.strings) :
                jQuery.a11yfy.getI18nString("sortableNotSorted", undefined, jQuery.fn.tables.defaults.strings)));
    }

    function getTableData($table) {
        var retVal = [];
        $table.find("tbody tr").each(function (index, value) {
            var $this = jQuery(value), row = [];
            $this.find("td").each(function (index, td) {
                var text = jQuery.trim(jQuery(td).text()),
                    intNum, flt;

                intNum = parseInt(text, 10);
                flt = parseFloat(text);
                if (intNum.toString() === text) {
                    row.push(intNum);
                } else if (flt.toString() === text) {
                    row.push(flt);
                } else {
                    row.push(text);
                }
            });
            row.push($this); // put the row into the data so we can manipulate
            retVal.push(row);
        });
        return retVal;
    }
    function getTableHeaders($table) {
        var retVal = [];
        $table.find('tr').first().find('th').each(function (index, value) {
            var $this = jQuery(value);
            retVal.push($this.text());
        });
        return retVal;
    }

    function sortTableData(data, direction, index) {
        data.sort(function (first, second) {
            if (typeof first[index] !== typeof second[index]) {
                if (typeof first[index] === "string") {
                    return (direction === "asc" ? -1 : 1);
                } else if (typeof second[index] === "string") {
                    return (direction === "asc" ? 1 : -1);
                }
            }
            return first[index] < second[index] ? (direction === "asc" ? -1 : 1) :
                    ( first[index] > second[index] ? (direction === "asc" ? 1 : -1) : 0);
        });
    }
    function redrawTable($table, data) {
        var $tbody = $table.find("tbody");
        jQuery(data).each(function (index, value) {
            $tbody.append(value[value.length - 1]);
        });
    }
    function setSortedText($span, $this) {
        $span.text(getSortedText($this));
    }

    // add the jquery instance method
    jQuery.fn.tables = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1 ));
        } else if (typeof method === "object" || ! method) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error("Method " +  method + " does not exist on jQuery.tables");
        }
    };

    jQuery.fn.tables.defaults = {
        sortFilter: "both",
        strings : {
            sortableSortedAscending: " Sortable, Sorted Ascending",
            sortableNotSorted: " Sortable, Not Sorted",
            sortableSortedDescending: " Sortable, Sorted Descending",
            filterable: ", Filterable",
            all: "All",
            tableSortedAscending: "Table sorted by ${column}, Ascending",
            tableSortedDescending: "Table sorted by ${column}, Descending",
            tableFilteredOnAndBy: "Table filtered on ${column}, by ${value}"
        },
        css : {
              cssString: "@media\n" +
              "(max-width: ${breakPoint}px) {\n" +
                "/* Force table to not be like tables anymore but still be navigable as a table */\n" +
                "table, thead, tbody, tr {\n" +
                  "width: 100%;\n" +
                "}\n" +

                "td, th {\n" +
                  "display: block;\n" +
                "}\n" +

                "/* Hide table headers with display: none because accessibility APIs do not pick up reliably on these headers anyway */\n" +
                "thead tr {\n" +
                  "display:none;\n" +
                "}\n" +

                "tr { border: 1px solid #ccc; }\n" +

                "td, th {\n" +
                  "/* Behave  like a \"row\" */\n" +
                  "border: none;\n" +
                  "border-bottom: 1px solid #eee;\n" +
                  "position: relative;\n" +
                "}\n" +

                "td:before, th:before {\n" +
                  "/* Now like a table header */\n" +
                  "position: absolute;\n" +
                  "/* Top/left values mimic padding */\n" +
                  "top: 6px;\n" +
                  "left: 6px;\n" +
                  "width: 45%;\n" +
                  "padding-right: 10px;\n" +
                  "white-space: nowrap;\n" +
                "}\n" +
              "}\n"
        }
    };
})(jQuery);
<|endoftext|>


<commit_before>/*
 * clean.js - Clean only the bots messages.
 *
 * Contributed by Ovyerus
 */

exports.commands = [
    'clean'
];

exports.clean = {
    desc: 'clean messages created by the bot itself',
    main: (bot, ctx) => {
        return new Promise((resolve, reject) => {
            ctx.msg.channel.getMessages(100).then(msgs => {
                let delet = [];
                msgs = msgs.filter(m => m.author.id === bot.user.id);
                msgs.forEach(m => delet.push(m.delete()));
                return Promise.all(delet);
            }).then(amt => ctx.msg.channel.createMessage(amt)).then(resolve).catch(reject);
        });
    }
};

<commit_msg>Fix amt<commit_after>/*
 * clean.js - Clean only the bots messages.
 *
 * Contributed by Ovyerus
 */

exports.commands = [
    'clean'
];

exports.clean = {
    desc: 'clean messages created by the bot itself',
    main: (bot, ctx) => {
        return new Promise((resolve, reject) => {
            ctx.msg.channel.getMessages(100).then(msgs => {
                let delet = [];
                msgs = msgs.filter(m => m.author.id === bot.user.id);
                msgs.forEach(m => delet.push(m.delete()));
                return Promise.all(delet);
            }).then(amt => ctx.msg.channel.createMessage(`${amt.length}`)).then(resolve).catch(reject);
        });
    }
};

<|endoftext|>


<commit_before>/* global angular, console */

import 'ionic-sdk/release/js/ionic.bundle';

angular.module('app.modals.select-account', [])
.controller('SelectAccountCtrl', function ($scope, Wallet) {
	'use strict';

	const network = $scope.data.network;

	$scope.cancel = cancel;
	$scope.select = select;

	$scope.accounts = getAccounts();
	$scope.heading	= $scope.data.heading;

	function getAccounts() {
		return Wallet.accountList
		.filter(item => item.network === network)
		.map(item => item.alias);
	}

	function cancel() {
		$scope.closeModalService();
	}

	function select(contact) {
		$scope.modalResolve(contact);
	}
});
<commit_msg>Add account filtering to modal<commit_after>/* global angular */

import 'ionic-sdk/release/js/ionic.bundle';

angular.module('app.modals.select-account', [])
.controller('SelectAccountCtrl', function ($scope, Wallet) {
	'use strict';

	const network = $scope.data.network;

	$scope.cancel = cancel;
	$scope.select = select;

	$scope.heading	= $scope.data.heading;

	const accountList = getAccounts();
	if ('filter' in $scope.data) {
		$scope.accounts = accountList.filter($scope.data.filter);
	} else {
		$scope.accounts = accountList;
	}

	function getAccounts() {
		return Wallet.accountList
		.filter(item => item.network === network)
		.map(item => item.alias);
	}

	function cancel() {
		$scope.closeModalService();
	}

	function select(contact) {
		$scope.modalResolve(contact);
	}
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         GZH Paywall Killer
// @namespace    gmcamaratta
// @version      1.0
// @description  This script disables the paywall from GZH
// @author       Eduardo Camaratta
// @match        http*://gauchazh.clicrbs.com.br/*
// @match        http*://especiais.zh.clicrbs.com.br/*
// @grant        none
// @run-at       document-start
// @downloadURL  https://github.com/eduardocamaratta/tampermonkeyscripts/raw/master/GauchaZHPaywallKiller.user.js
// ==/UserScript==

// Don't execute for the root page. This is only needed because both the @match and @include tags don't support full RE syntax
if(window.location.href.match(/^https?\:\/\/gauchazh.clicrbs.com.br\/?$/)) return;

let altScriptPath        = "https://cdn.rawgit.com/eduardocamaratta/tampermonkeyscripts/af2fcc12/js/main.min.js";
let altSpecialScriptPath = "https://cdn.rawgit.com/eduardocamaratta/tampermonkeyscripts/af2fcc12/js/special-paywall.min.js";

(function() {
  window.stop();
  var htmlRequest = new XMLHttpRequest();

  htmlRequest.open('GET', location.href);
  htmlRequest.onload = function(event) {
    var html = htmlRequest.responseText.replace(/<script\s+src=\".*main.min.js[^\"]*\">/, '<script src="' + altScriptPath + '">');
    html = html.replace(/http.*special-paywall.*\.js/, altSpecialScriptPath);

    document.open();
    document.write(html);
    document.close();
  };
  htmlRequest.send(null);
})();<commit_msg>Support scripts references updated<commit_after>// ==UserScript==
// @name         GZH Paywall Killer
// @namespace    gmcamaratta
// @version      1.0
// @description  This script disables the paywall from GZH
// @author       Eduardo Camaratta
// @match        http*://gauchazh.clicrbs.com.br/*
// @match        http*://especiais.zh.clicrbs.com.br/*
// @grant        none
// @run-at       document-start
// @downloadURL  https://github.com/eduardocamaratta/tampermonkeyscripts/raw/master/GauchaZHPaywallKiller.user.js
// ==/UserScript==

// Don't execute for the root page. This is only needed because both the @match and @include tags don't support full RE syntax
if(window.location.href.match(/^https?\:\/\/gauchazh.clicrbs.com.br\/?$/)) return;

let altScriptPath        = "https://cdn.rawgit.com/eduardocamaratta/tampermonkeyscripts/182d6556/js/main.min.js";
let altSpecialScriptPath = "https://cdn.rawgit.com/eduardocamaratta/tampermonkeyscripts/182d6556/js/special-paywall.min.js";

(function() {
  window.stop();
  var htmlRequest = new XMLHttpRequest();

  htmlRequest.open('GET', location.href);
  htmlRequest.onload = function(event) {
    var html = htmlRequest.responseText.replace(/<script\s+src=\".*main.min.js[^\"]*\">/, '<script src="' + altScriptPath + '">');
    html = html.replace(/http.*special-paywall.*\.js/, altSpecialScriptPath);

    document.open();
    document.write(html);
    document.close();
  };
  htmlRequest.send(null);
})();<|endoftext|>


<commit_before>'use strict';

module.exports = function (t, a) {
	var expected, inputArray = [
		{
			hasOnlySystemicReasons: false,
			rejectionType: "rejected",
			rejectionReasons: [
				{
					types: [
						"other"
					],
					value: "not good",
					ownerType: "processingStep",
					path: ""
				},
				{
					types: [
						"illegible",
						"invalid"
					],
					value: "",
					ownerType: "requirementUpload",
					path: "/requirementUploads/map/passport"
				},
				{
					types: [
						"other"
					],
					value: "junk",
					ownerType: "requirementUpload",
					path: "/requirementUploads/map/electricityBill"
				}
			],
			service: {
				type: "BusinessProcessMerchant",
				id: "11bfwele0k21",
				businessName: "John Doe"
			},
			operator: {
				id: "218nvxux6gor",
				name: "John Doe"
			},
			processingStep: {
				path: "/processingSteps/map/revision",
				label: "Revision"
			},
			occurancesCount: 0,
			date: {
				ts: 1493307837863,
				date: 1493251200000
			}
		}];
	expected = [[
		[
			'other',
			'not good',
			'illegible',
			'invalid',
			'other',
			'junk'
		],
		'',
		'',
		'John Doe',
		'Revision',
		'27/4/2017',
		'John Doe'
	]];
	a.deep(t(inputArray), expected);
};
<commit_msg>fixed a date locale fault in test<commit_after>'use strict';

module.exports = function (t, a) {
	var expected, inputArray = [
		{
			hasOnlySystemicReasons: false,
			rejectionType: "rejected",
			rejectionReasons: [
				{
					types: [
						"other"
					],
					value: "not good",
					ownerType: "processingStep",
					path: ""
				},
				{
					types: [
						"illegible",
						"invalid"
					],
					value: "",
					ownerType: "requirementUpload",
					path: "/requirementUploads/map/passport"
				},
				{
					types: [
						"other"
					],
					value: "junk",
					ownerType: "requirementUpload",
					path: "/requirementUploads/map/electricityBill"
				}
			],
			service: {
				type: "BusinessProcessMerchant",
				id: "11bfwele0k21",
				businessName: "John Doe"
			},
			operator: {
				id: "218nvxux6gor",
				name: "John Doe"
			},
			processingStep: {
				path: "/processingSteps/map/revision",
				label: "Revision"
			},
			occurancesCount: 0,
			date: {
				ts: 1493307837863,
				date: 1493251200000
			}
		}];
	expected = [[
		[
			'other',
			'not good',
			'illegible',
			'invalid',
			'other',
			'junk'
		],
		'',
		'',
		'John Doe',
		'Revision',
		'4/27/2017',
		'John Doe'
	]];
	a.deep(t(inputArray), expected);
};
<|endoftext|>


<commit_before>define(["helper/OutputAudio", "Tone/source/Source", "helper/OutputAudioStereo",
	"Test", "helper/Offline", "helper/APITest"],
	function (OutputAudio, Source, OutputAudioStereo, Test, Offline, APITest) {

	return function(Constr, args){

		context("Source Tests", function(){

			it ("extends Tone.Source", function(){
				var instance = new Constr(args);
				expect(instance).to.be.an.instanceof(Source);
				instance.dispose();
			});

			it ("can connect the output", function(){
				var instance = new Constr(args);
				instance.connect(Test);
				instance.dispose();
			});

			it("starts and stops", function(){
				return Offline(function(){
					var instance = new Constr(args);
					expect(instance.state).to.equal("stopped");
					instance.start(0).stop(0.2);
					return function(time){
						if (time >= 0 && time < 0.2){
							expect(instance.state).to.equal("started");
						} else if (time > 0.2){
							expect(instance.state).to.equal("stopped");
						}
					};
				}, 0.3);
			});

			it("makes a sound", function(){
				return OutputAudio(function(){
					var instance = new Constr(args);
					instance.toMaster();
					instance.start();
				});
			});

			it("produces sound in both channels", function(){
				return OutputAudioStereo(function(){
					var instance = new Constr(args);
					instance.toMaster();
					instance.start();
				});
			});

			it("be scheduled to start in the future", function(){
				return Offline(function(){
					var instance = new Constr(args).toMaster();
					instance.start(0.1);
				}, 0.3).then(function(buffer){
					buffer.forEach(function(sample, time){
						if (sample > 0){
							expect(time).to.be.at.least(0.099);
						}
					});
				});
			});

			it("makes no sound if it is started and then stopped with a time at or before the start time", function(){
				return Offline(function(){
					var instance = new Constr(args).toMaster();
					instance.start(0.1).stop(0.05);
				}, 0.3).then(function(buffer){
					expect(buffer.isSilent()).to.be.true;
				});
			});

			it("can be muted", function(){
				return Offline(function(){
					var instance = new Constr(args).toMaster();
					instance.start(0);
					instance.mute = true;
				}, 0.3).then(function(buffer){
					expect(buffer.isSilent()).to.be.true;
				});
			});

			it("be scheduled to stop in the future", function(){
				return Offline(function(){
					var instance = new Constr(args).toMaster();
					instance.start(0).stop(0.2);
					instance.mute = true;
				}, 0.3).then(function(buffer){
					buffer.forEach(function(sample, time){
						if (time > 0.2){
							expect(sample).to.equal(0);
						}
					});
				});
			});

		});

		context("Source API", function(){
			APITest.method(Constr, "start", ["Time=", "Time=", "Time="], args);
			APITest.method(Constr, "stop", ["Time="], args);
		});

	};
});<commit_msg>source shouldn't be muted<commit_after>define(["helper/OutputAudio", "Tone/source/Source", "helper/OutputAudioStereo",
	"Test", "helper/Offline", "helper/APITest"],
	function (OutputAudio, Source, OutputAudioStereo, Test, Offline, APITest) {

	return function(Constr, args){

		context("Source Tests", function(){

			it ("extends Tone.Source", function(){
				var instance = new Constr(args);
				expect(instance).to.be.an.instanceof(Source);
				instance.dispose();
			});

			it ("can connect the output", function(){
				var instance = new Constr(args);
				instance.connect(Test);
				instance.dispose();
			});

			it("starts and stops", function(){
				return Offline(function(){
					var instance = new Constr(args);
					expect(instance.state).to.equal("stopped");
					instance.start(0).stop(0.2);
					return function(time){
						if (time >= 0 && time < 0.2){
							expect(instance.state).to.equal("started");
						} else if (time > 0.2){
							expect(instance.state).to.equal("stopped");
						}
					};
				}, 0.3);
			});

			it("makes a sound", function(){
				return OutputAudio(function(){
					var instance = new Constr(args);
					instance.toMaster();
					instance.start();
				});
			});

			it("produces sound in both channels", function(){
				return OutputAudioStereo(function(){
					var instance = new Constr(args);
					instance.toMaster();
					instance.start();
				});
			});

			it("be scheduled to start in the future", function(){
				return Offline(function(){
					var instance = new Constr(args).toMaster();
					instance.start(0.1);
				}, 0.3).then(function(buffer){
					buffer.forEach(function(sample, time){
						if (sample > 0){
							expect(time).to.be.at.least(0.099);
						}
					});
				});
			});

			it("makes no sound if it is started and then stopped with a time at or before the start time", function(){
				return Offline(function(){
					var instance = new Constr(args).toMaster();
					instance.start(0.1).stop(0.05);
				}, 0.3).then(function(buffer){
					expect(buffer.isSilent()).to.be.true;
				});
			});

			it("can be muted", function(){
				return Offline(function(){
					var instance = new Constr(args).toMaster();
					instance.start(0);
					instance.mute = true;
				}, 0.3).then(function(buffer){
					expect(buffer.isSilent()).to.be.true;
				});
			});

			it("be scheduled to stop in the future", function(){
				return Offline(function(){
					var instance = new Constr(args).toMaster();
					instance.start(0).stop(0.2);
				}, 0.3).then(function(buffer){
					buffer.forEach(function(sample, time){
						if (time > 0.2){
							expect(sample).to.equal(0);
						}
					});
				});
			});

		});

		context("Source API", function(){
			APITest.method(Constr, "start", ["Time=", "Time=", "Time="], args);
			APITest.method(Constr, "stop", ["Time="], args);
		});

	};
});<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var deadCell = function() {
    return {
	dead: true
    };
};

var liveCell = function() {

    var states = [
	deadCell,
	deadCell,
	liveCell,
	liveCell,
	deadCell,
	deadCell,
	deadCell,
	deadCell,
	deadCell
    ];

    return {
	live: true,
	next: function(n) {
	    return states[n]();
	}
    };
};

describe('game of life', function() {
    describe('rules', function() {
	it('under population', function() {
	    assert(liveCell().next(1).dead);
	});

	it('persistence', function() {
	    assert(liveCell().next(2).live);
	});

	it('over population', function() {
	    assert(liveCell().next(4).dead);
	});
    });
});
<commit_msg>ensure full test coverage<commit_after>"use strict";

var assert = require('assert');

var deadCell = function() {
    return {
	dead: true
    };
};

var liveCell = function() {

    var states = [
	deadCell,
	deadCell,
	liveCell,
	liveCell,
	deadCell,
	deadCell,
	deadCell,
	deadCell,
	deadCell
    ];

    return {
	live: true,
	next: function(n) {
	    return states[n]();
	}
    };
};

describe('game of life', function() {
    describe('rules', function() {
	it('under population', function() {
	    for (var i=0;i<2;++i)
		assert(liveCell().next(i).dead);
	});

	it('persistence', function() {
	    assert(liveCell().next(2).live);
	    assert(liveCell().next(3).live);
	});

	it('over population', function() {
	    for (var i=4;i<9;++i)
		assert(liveCell().next(i).dead);
	});
    });
});
<|endoftext|>


<commit_before>/*
 * marry.js - Marry your imaginary waifu or someone
 *
 *  Contributed by Capuccino
 */

/* eslint-env node */

exports.commands = [
    'marry',
    'divorce'
];

exports.marry = {
    desc: 'Marry Someone',
    longDesc: 'Marry your waifu in the guild.',
    usage: '<Mention>',
    main(bot, ctx) {
        return new Promise((resolve, reject) => {
            if (!ctx.suffix) {
                ctx.createMessage('Mention or cite your partner\'s name.');
            } else if (ctx.mentions[0].id === ctx.author.id) {
                ctx.createMessage('Hey! You\'re not allowed to marry yourself.');
            } else {
                ctx.createMessage(`${ctx.mentions[0].mention}, Will you marry ${ctx.author.mention}?\n You have 30 seconds to respond yes or no.`).then(() => {
                    bot.awaitMessage(ctx.channel.id, ctx.mentions[0].id, () => true, 30000).then(m => {
                        if (/y(es)?/i.test(m.content)) {
                            return ctx.createMessage(`I hereby Pronounce ${ctx.mentions[0].mention} and ${ctx.author.mention} as husband and wife! :two_hearts:`);
                        } else if (/no?/i.test(m.content)) {
                            return ctx.createMessage(`I'm sorry ${ctx.author.mention}, but your partner declined.`);
                        }
                    }).then(resolve).catch(() => {
                        ctx.createMessage('Your partner didn\'t respond in time.');
                    });
                }).then(resolve).catch(reject);
            }
        });
    }
};

exports.divorce = {
    desc: 'Divorce your waifu',
    main(bot, ctx) {
        return new Promise((resolve, reject) => {
            if (!ctx.suffix) {
                ctx.createMessage('We need to find out the partner you are trying to divorce first. Mention him/her.');
            } else if (ctx.mentions[0].id === ctx.author.id) {
                ctx.createMessage('Wew lad.');
            } else {
                ctx.createMessage(`${ctx.mentions[0].mention}, will you let go of ${ctx.author.mention}?\n You have 30 seconds to respond yes or no.`).then(() => {
                    bot.awaitMessage(ctx.channel.id, ctx.mentions[0].id, () => true, 30000).then(m => {
                        if (/y(es)?/i.test(m.content)) {
                            return ctx.createMessage(`${ctx.msg.author}, you're no longer married to ${ctx.mentions[0].mention}`);
                        } else if (/no?/i.test(m.content)) {
                            return ctx.createMessage('Your partner decided not to let go of you. I can\'t seperate you.');
                        }
                    }).then(resolve).catch(() => {
                        ctx.createMessage('Your partner didn\'t respond in time.');
                    });
                }).then(resolve).catch(reject);
            }
        });
    }
}<commit_msg>redo sentence<commit_after>/*
 * marry.js - Marry your imaginary waifu or someone
 *
 *  Contributed by Capuccino
 */

/* eslint-env node */

exports.commands = [
    'marry',
    'divorce'
];

exports.marry = {
    desc: 'Marry Someone',
    longDesc: 'Marry your waifu in the guild.',
    usage: '<Mention>',
    main(bot, ctx) {
        return new Promise((resolve, reject) => {
            if (!ctx.suffix) {
                ctx.createMessage('Mention or cite your partner\'s name.');
            } else if (ctx.mentions[0].id === ctx.author.id) {
                ctx.createMessage('Hey! You\'re not allowed to marry yourself.');
            } else {
                ctx.createMessage(`${ctx.mentions[0].mention}, Will you marry ${ctx.author.mention}?\n You have 30 seconds to respond yes or no.`).then(() => {
                    bot.awaitMessage(ctx.channel.id, ctx.mentions[0].id, () => true, 30000).then(m => {
                        if (/y(es)?/i.test(m.content)) {
                            return ctx.createMessage(`I hereby Pronounce ${ctx.mentions[0].mention} and ${ctx.author.mention} as husband and wife! :two_hearts:`);
                        } else if (/no?/i.test(m.content)) {
                            return ctx.createMessage(`I'm sorry ${ctx.author.mention}, but your partner declined.`);
                        }
                    }).then(resolve).catch(() => {
                        ctx.createMessage('Your partner didn\'t respond in time or gave an invalid response.');
                    });
                }).then(resolve).catch(reject);
            }
        });
    }
};

exports.divorce = {
    desc: 'Divorce your waifu',
    main(bot, ctx) {
        return new Promise((resolve, reject) => {
            if (!ctx.suffix) {
                ctx.createMessage('We need to find out the partner you are trying to divorce first. Mention him/her.');
            } else if (ctx.mentions[0].id === ctx.author.id) {
                ctx.createMessage('Wew lad.');
            } else {
                ctx.createMessage(`${ctx.mentions[0].mention}, will you let go of ${ctx.author.mention}?\n You have 30 seconds to respond yes or no.`).then(() => {
                    bot.awaitMessage(ctx.channel.id, ctx.mentions[0].id, () => true, 30000).then(m => {
                        if (/y(es)?/i.test(m.content)) {
                            return ctx.createMessage(`${ctx.msg.author}, you're no longer married to ${ctx.mentions[0].mention}`);
                        } else if (/no?/i.test(m.content)) {
                            return ctx.createMessage('Your partner decided not to let go of you. I can\'t seperate you.');
                        }
                    }).then(resolve).catch(() => {
                        ctx.createMessage('Your partner didn\'t respond in time or gave an invalid response.');
                    });
                }).then(resolve).catch(reject);
            }
        });
    }
};<|endoftext|>