<commit_before>// documentation:
// This will allow numerous validations enforcing all sorts of requirements that can be used on one or many field(s) in a page. All you need to do is include this
// function in between the <script> and </script> tags on the page and call this function with the correct arguments that set what
// restrictions you want for the field. Here is an example:
//
// If you had a page with a field for phone number, you will need to ensure that a user enters number that is 10 digits in lengts and
// a whole number is entered for the entry to be useful. Let's say have a variable named phoneNumber, you would use this cade to validate this field this way:
// validateAll(phoneNumber, 1, null, null, null, "the phone number field");
// validateAll(phoneNumber, 6, null, null, 10, "the phone number field");
// This would render an alert reading "Please enter something in the phone number field that is a whole number." if anything not a whole number is entered.
// It will also render an alert reading "Please enter something in the phone number field that is 10 characters long." if a user enters something not 10 characters long.
// Now all you need to do is call this function with the selected arguments, and you can put any restriction on a field entry without having to write any code!
//
//
// userInput is the input from the field on the user interface being validated.
// dataType is the selector for which type of restriction you want to place on the field. See the key below.
//
//            Key for 'dataType'
//                   - dataType                                               1 = sets the restriction: Integer - whole numbers will be accepted, anything else will be rejected
//                                                                            2 = sets the restriction: Number - any number will be accepted any non-number will be rejected
//                                                                            3 = Sets the restriction: Alphabetical strings without numbers or cpecial characters accepted, all others rejected
//                                                                            4 = date   # reserved for future use.
//                                                                            5 = starts with - Sets the requirement for the first few digits by setting the "StartsWith" parameter with the requirement as an argument
//                                                                                what the user's input should begin with. Set how many letters it should start with with the 'startsWithHowMany' parameter
//                                                                                (for instance something that is being validated to start with AL should be set to 2).
//                                                                            6 = length - rejects user inputs that are not a prescribed length. Set the parameter 'length' to the prescribed lengh as an integer argument.
//                                                                                Simply choose a datatype to restrict the input to and the parameters that go with that datatype as mentioned above. set all others parameters to the argument  null.

function validateAll(userInput, dataType, startsWith, startsWithHowMany, length, fieldID){
        switch (dataType){
                case 1: {
                         isIntnt = Number.isInteger(userInput)
                         if (isIntnt === false)
                                problem = "is a whole number.";
                                        else problem = null;
                         break;
                         }
                case 2:{
                        if (isNaN(userInput) === true)
                                problem = "is a number.";
                        else problem = null;
                        break;
                        }
                case 3:{
                        function lettersOnly(userInput){
                                        acceptable = RegExp(/^[a-z]+$/i);
                                        if (acceptable.test(userInput) === false)
                                                problem = "is letters only.";
                                        else problem = null;
                                        return problem;
                                                       }
                        lettersOnly(userInput);
                        break;
                        }
                case 4: {
                         // COMPLETE THIS LATER
                         alert("Date") // Test code delete this later
                         break;
                        }
                case 5:{

                        function validatesStartsWith(userInput, startsWith, startsWithHowMany){
                                        switch(startsWithHowMany){
                                                case 1: {
                                                        if (userInput.charAt(0).toUpperCase() === startsWith.toUpperCase() && userInput.length >= 1)
                                                                problem = null;
                                                        else
                                                                {
                                                                toconcat = "starts with ";
                                                                problem =  toconcat.concat(startsWith);
                                                                }
                                                         break;
                                                        }

                                                case 2: {
                                                        l1=userInput.charAt(0);
                                                        l2=userInput.charAt(1);
                                                        check=l1.concat(l2);
                                                        if (check.toUpperCase() === startsWith.toUpperCase() && userInput.length >= 2)
                                                                problem = null;
                                                        else
                                                               {
                                                                toconcat2 = "starts with ";
                                                                problem = toconcat2.concat(startsWith);
                                                                }
                                                        break;
                                                        }
                                                case 3: {
                                                         l1=userInput.charAt(0);
                                                         l2=userInput.charAt(1);
                                                         l3=userInput.charAt(2);
                                                         l1and2=l1.concat(l2);
                                                         check=l1and2.concat(l3);
                                                                if (check.toUpperCase() === startsWith.toUpperCase() && userInput.length >= 3 )
                                                                        problem = null;
                                                                else
                                                                        {
                                                                        toconcat3 = "starts with ";
                                                                        problem = toconcat3.concat(startsWith);
                                                                        }
                                                        break;
                                                        }
                                                case 4:{
                                                        l1=userInput.charAt(0);
                                                        l2=userInput.charAt(1);
                                                        l3=userInput.charAt(2);
                                                        l4=userInput.charAt(3);
                                                        l1and2=l1.concat(l2);
                                                        l1andl2andl3=l1and2.concat(l3);
                                                        check=l1andl2andl3.concat(l4);
                                                        if (check.toUpperCase() === startsWith.toUpperCase() && userInput.length >= 4)
                                                                problem = null;
                                                        else
                                                                {
                                                                toconcat4 = "starts with ";
                                                                problem =  toconcat4.concat(startsWith);
                                                                }
                                                        break;
                                                        }
                                                }

                                                return problem;
                                                }
                                problem = validatesStartsWith(userInput, startsWith, startsWithHowMany);
                                break;
                                }
                case 6:{
                        if (userInput.length === length)
                                problem = null;
                        else
                                {
                                warnString1 = "is ";
                                warnString2 = length;
                                warnString3 = " characters long";
                                warn1and2=warnString1.concat(warnString2);
                                problem = warn1and2.concat(warnString3);
                                }
                                break;
                        }
                return problem;
                }

function warning(problem, fieldID) {
                                if (problem != null)
                                                alert("Please enter something in " + fieldID + " that " + problem);
                                else return null;
                                }
warning(problem, fieldID);
problem = null;
}
//Readme
// (C) 2016 David W. Thrower, PSM
// This is offered for anyone's use under the terms of the Apache License with the following exceptions:
// This shall not be used in any software that is used for any of the following purposes:
//    A. To commit any act of fraud, deceit, extortion, or for the production, sale, distribution, or marketing ofany illicit, obscene, or prohibited materials
//    B. For critical applications such as operation of an aircraft controls, critical orienteering applications, or control of heavy machinery
//    C. To use in any way that deprives another of their basic rights, promotes discrimination including promoting hate crime, encourages Female Genital Mutilation, or similar purposes
//    D. Use in war operations
//    E. Use in systems/apps/websites used to operate or promote an abortion facility  <commit_msg>Update validatesAll.js<commit_after>// documentation:
// This will allow numerous validations enforcing all sorts of requirements that can be used on one or many field(s) in a page. All you need to do is include this
// function in between the <script> and </script> tags on the page and call this function with the correct arguments that set what
// restrictions you want for the field. Here is an example:
//
// If you had a page with a field for phone number, you will need to ensure that a user enters number that is 10 digits in lengts and
// a whole number is entered for the entry to be useful. Let's say have a variable named phoneNumber, you would use this code to validate this field this way:
// validateAll(phoneNumber, 1, null, null, null, "the phone number field");
// validateAll(phoneNumber, 6, null, null, 10, "the phone number field");
// This would render an alert reading "Please enter something in the phone number field that is a whole number." if anything not a whole number is entered.
// It will also render an alert reading "Please enter something in the phone number field that is 10 characters long." if a user enters something not 10 characters long.
// Now all you need to do is call this function with the selected arguments, and you can put any restriction on a field entry without having to write any code!
//
//
// userInput is the input from the field on the user interface being validated.
// dataType is the selector for which type of restriction you want to place on the field. See the key below.
//
//            Key for 'dataType'
//                   - dataType                                               1 = sets the restriction: Integer - whole numbers will be accepted, anything else will be rejected
//                                                                            2 = sets the restriction: Number - any number will be accepted any non-number will be rejected
//                                                                            3 = Sets the restriction: Alphabetical strings without numbers or cpecial characters accepted, all others rejected
//                                                                            4 = date   # reserved for future use.
//                                                                            5 = starts with - Sets the requirement for the first few digits by setting the "StartsWith" parameter with the requirement as an argument
//                                                                                what the user's input should begin with. Set how many letters it should start with with the 'startsWithHowMany' parameter
//                                                                                (for instance something that is being validated to start with AL should be set to 2).
//                                                                            6 = length - rejects user inputs that are not a prescribed length. Set the parameter 'length' to the prescribed lengh as an integer argument.
//                                                                                Simply choose a datatype to restrict the input to and the parameters that go with that datatype as mentioned above. set all others parameters to the argument  null.

function validateAll(userInput, dataType, startsWith, startsWithHowMany, length, fieldID){
        switch (dataType){
                case 1: {
                         isIntnt = Number.isInteger(userInput)
                         if (isIntnt === false)
                                problem = "is a whole number.";
                                        else problem = null;
                         break;
                         }
                case 2:{
                        if (isNaN(userInput) === true)
                                problem = "is a number.";
                        else problem = null;
                        break;
                        }
                case 3:{
                        function lettersOnly(userInput){
                                        acceptable = RegExp(/^[a-z]+$/i);
                                        if (acceptable.test(userInput) === false)
                                                problem = "is letters only.";
                                        else problem = null;
                                        return problem;
                                                       }
                        lettersOnly(userInput);
                        break;
                        }
                case 4: {
                         // COMPLETE THIS LATER
                         alert("Date") // Test code delete this later
                         break;
                        }
                case 5:{

                        function validatesStartsWith(userInput, startsWith, startsWithHowMany){
                                        switch(startsWithHowMany){
                                                case 1: {
                                                        if (userInput.charAt(0).toUpperCase() === startsWith.toUpperCase() && userInput.length >= 1)
                                                                problem = null;
                                                        else
                                                                {
                                                                toconcat = "starts with ";
                                                                problem =  toconcat.concat(startsWith);
                                                                }
                                                         break;
                                                        }

                                                case 2: {
                                                        l1=userInput.charAt(0);
                                                        l2=userInput.charAt(1);
                                                        check=l1.concat(l2);
                                                        if (check.toUpperCase() === startsWith.toUpperCase() && userInput.length >= 2)
                                                                problem = null;
                                                        else
                                                               {
                                                                toconcat2 = "starts with ";
                                                                problem = toconcat2.concat(startsWith);
                                                                }
                                                        break;
                                                        }
                                                case 3: {
                                                         l1=userInput.charAt(0);
                                                         l2=userInput.charAt(1);
                                                         l3=userInput.charAt(2);
                                                         l1and2=l1.concat(l2);
                                                         check=l1and2.concat(l3);
                                                                if (check.toUpperCase() === startsWith.toUpperCase() && userInput.length >= 3 )
                                                                        problem = null;
                                                                else
                                                                        {
                                                                        toconcat3 = "starts with ";
                                                                        problem = toconcat3.concat(startsWith);
                                                                        }
                                                        break;
                                                        }
                                                case 4:{
                                                        l1=userInput.charAt(0);
                                                        l2=userInput.charAt(1);
                                                        l3=userInput.charAt(2);
                                                        l4=userInput.charAt(3);
                                                        l1and2=l1.concat(l2);
                                                        l1andl2andl3=l1and2.concat(l3);
                                                        check=l1andl2andl3.concat(l4);
                                                        if (check.toUpperCase() === startsWith.toUpperCase() && userInput.length >= 4)
                                                                problem = null;
                                                        else
                                                                {
                                                                toconcat4 = "starts with ";
                                                                problem =  toconcat4.concat(startsWith);
                                                                }
                                                        break;
                                                        }
                                                }

                                                return problem;
                                                }
                                problem = validatesStartsWith(userInput, startsWith, startsWithHowMany);
                                break;
                                }
                case 6:{
                        if (userInput.length === length)
                                problem = null;
                        else
                                {
                                warnString1 = "is ";
                                warnString2 = length;
                                warnString3 = " characters long";
                                warn1and2=warnString1.concat(warnString2);
                                problem = warn1and2.concat(warnString3);
                                }
                                break;
                        }
                return problem;
                }

function warning(problem, fieldID) {
                                if (problem != null)
                                                alert("Please enter something in " + fieldID + " that " + problem);
                                else return null;
                                }
warning(problem, fieldID);
problem = null;
}
//Readme
// (C) 2016 David W. Thrower, PSM
// This is offered for anyone's use under the terms of the Apache License with the following exceptions:
// This shall not be used in any software that is used for any of the following purposes:
//    A. To commit any act of fraud, deceit, extortion, or for the production, sale, distribution, or marketing ofany illicit, obscene, or prohibited materials
//    B. For critical applications such as operation of an aircraft controls, critical orienteering applications, or control of heavy machinery
//    C. To use in any way that deprives another of their basic rights, promotes discrimination including promoting hate crime, encourages Female Genital Mutilation, or similar purposes
//    D. Use in war operations
//    E. Use in systems/apps/websites used to operate or promote an abortion facility
<|endoftext|>


<commit_before>const d3 = require('d3')

export const BubbleGraphService = [

class BubbleGraphService {
  constructor(){}

  drawingBubbleChart (sortedWords) {
    const diameter = 400
    const colorArr = [ '#9CCBC5', '#64A39A', '#3F897F',
                  '#247267', '#105A50', '#904A19',
                  '#B66D3A', '#FFC59C', '#FFDCC4', '#b1695a']
    const maxBubbleRadius = 48;
    const textColor = 'black'
    const textFont = 'monospace';
    const textSize = '15px';
    const smallerTextSize = '13px';
    const legendColorBox = 20;
    const spacingBetweenLegend = 30;
    const highestCount = sortedWords[0].count;

    var svg = d3.select('#bubble-chart').append('svg')
      .attr('width',diameter+200)
      .attr('height',diameter)

    var bubble = d3.layout.pack()
      .size([diameter,diameter])
      .value(function(d) {
        return d.count;})
      .padding(1.5);

    var nodes = bubble.nodes(processData(sortedWords))
      .filter(function(d) {return !d.children;});

    var nodeLegend = bubble.nodes(processData(sortedWords))
      .filter(function(d) {return !d.children});

    var vis = svg.selectAll('circle')
      .data(nodes)
      .enter()
      .append('circle')
        .attr('class', 'circle')
        .attr('transform', function(d) {
        return `translate(${d.x},${d.y})`;
        })
        .attr('r', function(d) {
          if (d.count === highestCount) {
            return maxBubbleRadius;
          } else {
            return maxBubbleRadius*((d.count)/highestCount)
          }
        })
        .attr('class', function(d) {
        return d.className;
        })
        .style('fill', function(d) {
        return colorArr[d.colorIndex];
        })
        .append("svg:title")
        .style("position", "absolute")
        .style("z-index", "10")
        .style("visibility", "hidden")
        .text(function(d) { return d.word; })
        .on("mouseover", function(){return title.style("visibility", "visible");})
        .on("mouseout", function(){return title.style("visibility", "hidden");})

    var legend = d3.select('svg')
      .append('g')
        .attr('class', 'legend')
      .selectAll('g')
      .data(nodeLegend)
      .enter()
      .append('g')
        .attr('class', 'legend')
        .attr('transform', function(d) {
          return `translate(${450},${spacingBetweenLegend*d.colorIndex})`
        })

    legend.append('rect')
      .attr('width',legendColorBox)
      .attr('height',legendColorBox)
      .style('fill', function(d) {
        return colorArr[d.colorIndex];
      })

    legend.append('text')
      .attr('y','1em')
      .attr('x', legendColorBox + 5)
      .text(function(d) {
        return `${d.count} ${d.word}`
      })
      .style('fill',textColor)
      .style('font-family', textFont)
      .style('font-size',function(d) {
        if (d.word.length > 11) {
          return smallerTextSize;
        } else {
          return textSize
        }
      })

    function processData(data) {
      data = data.map((wordObj, index) =>{
        wordObj.colorIndex = index;
        return wordObj;
      })
      return {children: data};
    }
  }
}];<commit_msg>attaches legend to bubble chart svg<commit_after>const d3 = require('d3')

export const BubbleGraphService = [

class BubbleGraphService {
  constructor(){}

  drawingBubbleChart (sortedWords) {
    const diameter = 400
    const colorArr = [ '#9CCBC5', '#64A39A', '#3F897F',
                  '#247267', '#105A50', '#904A19',
                  '#B66D3A', '#FFC59C', '#FFDCC4', '#b1695a']
    const maxBubbleRadius = 48;
    const textColor = 'black'
    const textFont = 'monospace';
    const textSize = '15px';
    const smallerTextSize = '13px';
    const legendColorBox = 20;
    const spacingBetweenLegend = 30;
    const highestCount = sortedWords[0].count;

    var svg = d3.select('#bubble-chart').append('svg')
      .attr("id", "bubble-svg")
      .attr('width',diameter+200)
      .attr('height',diameter)

    var bubble = d3.layout.pack()
      .size([diameter,diameter])
      .value(function(d) {
        return d.count
      ;})
      .padding(1.5);

    var nodes = bubble.nodes(processData(sortedWords))
      .filter(function(d) {return !d.children;});

    var nodeLegend = bubble.nodes(processData(sortedWords))
      .filter(function(d) {return !d.children});

    var vis = svg.selectAll('circle')
      .data(nodes)
      .enter()
      .append('circle')
        .attr('class', 'circle')
        .attr('transform', function(d) {
          return `translate(${d.x},${d.y})`;
        })
        .attr('r', function(d) {
          if (d.count === highestCount) {
            return maxBubbleRadius;
          } else {
            return maxBubbleRadius*((d.count)/highestCount)
          }
        })
        .attr('class', function(d) {
          return d.className;
        })
        .style('fill', function(d) {
          return colorArr[d.colorIndex];
        })
        .append("svg:title")
        .style("position", "absolute")
        .style("z-index", "10")
        .style("visibility", "hidden")
        .text(function(d) { return d.word; })
        .on("mouseover", function(){return title.style("visibility", "visible");})
        .on("mouseout", function(){return title.style("visibility", "hidden");})

    var legend = d3.select('svg#bubble-svg')
      .append('g')
        .attr('class', 'legend')
      .selectAll('g')
      .data(nodeLegend)
      .enter()
      .append('g')
        .attr('class', 'legend')
        .attr('transform', function(d) {
          return `translate(${450},${spacingBetweenLegend*d.colorIndex})`
        })

    legend.append('rect')
      .attr('width',legendColorBox)
      .attr('height',legendColorBox)
      .style('fill', function(d) {
        return colorArr[d.colorIndex];
      })

    legend.append('text')
      .attr('y','1em')
      .attr('x', legendColorBox + 5)
      .text(function(d) {
        return `${d.count} ${d.word}`
      })
      .style('fill',textColor)
      .style('font-family', textFont)
      .style('font-size',function(d) {
        if (d.word.length > 11) {
          return smallerTextSize;
        } else {
          return textSize
        }
      })

    function processData(data) {
      data = data.map((wordObj, index) =>{
        wordObj.colorIndex = index;
        return wordObj;
      })
      return {children: data};
    }
  }
}];<|endoftext|>


<commit_before>/*
 * Zest Component Inheritor
 *
 * Can be used as AMD or global.
 *
 * When used as a global, must be included after 'zoe.js' and 'zest-render.js'.
 *
 */
(function (root, factory) {
  if (typeof define === 'function' && define.amd)
    define(['zoe', 'is!browser?./zest-render'], factory);
  else
    root.$z.Component = factory($z, $z);
}(this, function(zoe, $z) {
  /*
   * Component
   *
   * Creates a component with rendering or as attach-only
   *
   * The component is entirely rendered by $z.render.
   *
   * Read more at http://zestjs.org/docs#$z.Component
   *
   */
  return {
    _implement: [zoe.Constructor, zoe.InstanceChains],

    _extend: {
      'options': 'DAPPEND',
      'type': 'REPLACE',
      'pipe': zoe.extend.makeChain(function(self, args, fns) {
        var o = {};
        var p = [];
        for (var i = 0, len = fns.length; i < len; i++) {
          var fn = fns[i];
          if (typeof fn == 'function')
            zoe.extend(o, fn.apply(self, args), {
              '*': 'REPLACE',
              'global': 'APPEND'
            });
          else if (fn instanceof Array)
            for (var j = 0; j < fn.length; j++)
              o[fn[j]] = args[0][fn[j]];
          else if (fn === true)
            return args[0];
        }
        return o;
      }),
      'class': function(a, b) {
        a = a || '';
        if (a instanceof Array)
          a = a.join(' ');
        if (b instanceof Array)
          b = b.join(' ');
        return a + b;
      },
      'load': zoe.extend.makeChain('ASYNC')
    },

    _integrate: function(def) {
      if (def.construct || def.prototype)
        this.attach = this.attach || function(el, o, register) {
          if (!register)
            return new this(el, o);

          // helper for attachment-only components to also be registered
          if (!el.getAttribute('component'))
            el.setAttribute('component', '');
          el.id = el.id || $z._nextComponentId++;

          return ($z._components[el.id] = new this(el, o));

        }
    },

    construct: function(el, o, system) {
      this.el = el;
      this.o = o;
    },

    prototype: {
      $: $z && $z.$,
      $z: $z && $z.select
    }
  };
}));
<commit_msg>piping correction<commit_after>/*
 * Zest Component Inheritor
 *
 * Can be used as AMD or global.
 *
 * When used as a global, must be included after 'zoe.js' and 'zest-render.js'.
 *
 */
(function (root, factory) {
  if (typeof define === 'function' && define.amd)
    define(['zoe', 'is!browser?./zest-render'], factory);
  else
    root.$z.Component = factory($z, $z);
}(this, function(zoe, $z) {
  /*
   * Component
   *
   * Creates a component with rendering or as attach-only
   *
   * The component is entirely rendered by $z.render.
   *
   * Read more at http://zestjs.org/docs#$z.Component
   *
   */
  return {
    _implement: [zoe.Constructor, zoe.InstanceChains],

    _extend: {
      'options': 'DAPPEND',
      'type': 'REPLACE',
      'pipe': zoe.extend.makeChain(function(self, args, fns) {
        var o = {};
        var p = [];
        for (var i = 0, len = fns.length; i < len; i++) {
          var fn = fns[i];
          if (typeof fn == 'function')
            zoe.extend(o, fn.apply(self, args), {
              '*': 'REPLACE',
              'global': 'APPEND'
            });
          else if (fn instanceof Array)
            for (var j = 0; j < fn.length; j++)
              o[fn[j]] = args[0][fn[j]];
          else if (fn === true)
            return args[0];
        }
        return o;
      }),
      'class': function(a, b) {
        a = a || '';
        if (a instanceof Array)
          a = a.join(' ');
        if (b instanceof Array)
          b = b.join(' ');
        return a + b;
      },
      'load': zoe.extend.makeChain('ASYNC')
    },

    _integrate: function(def) {
      if (def.construct || def.prototype)
        this.attach = this.attach || function(el, o, register) {
          if (!register)
            return new this(el, o);

          // helper for attachment-only components to also be registered
          if (!el.getAttribute('component'))
            el.setAttribute('component', '');
          el.id = el.id || $z._nextComponentId++;

          return ($z._components[el.id] = new this(el, o));
        }
    },

    _built: function() {
      if (!this.render)
        this.pipe = this.pipe || true;
    }

    construct: function(el, o, system) {
      this.el = el;
      this.o = o;
    },

    prototype: {
      $: $z && $z.$,
      $z: $z && $z.select
    }
  };
}));
<|endoftext|>


<commit_before>(function ($) {
  "use strict";

  var defaultOptions = {
    tagClass: function(item) {
      return 'label label-info';
    },
    itemValue: function(item) {
      return item ? item.toString() : item;
    },
    itemText: function(item) {
      return this.itemValue(item);
    },
    freeInput: true,
    maxTags: undefined,
    confirmKeys: [13],
    onTagExists: function(item, $tag) {
      $tag.hide().fadeIn();
    }
  };

  /**
   * Constructor function
   */
  function TagsInput(element, options) {
    this.itemsArray = [];

    this.$element = $(element);
    this.$element.hide();

    this.isSelect = (element.tagName === 'SELECT');
    this.multiple = (this.isSelect && element.hasAttribute('multiple'));
    this.objectItems = options && options.itemValue;
    this.placeholderText = element.hasAttribute('placeholder') ? this.$element.attr('placeholder') : '';
    this.inputSize = Math.max(1, this.placeholderText.length);

    this.$container = $('

');
    this.$input = $('<input size="' + this.inputSize + '" type="text" placeholder="' + this.placeholderText + '"/>').appendTo(this.$container);

    this.$element.after(this.$container);

    this.build(options);
  }

  TagsInput.prototype = {
    constructor: TagsInput,

    /**
     * Adds the given item as a new tag. Pass true to dontPushVal to prevent
     * updating the elements val()
     */
    add: function(item, dontPushVal) {
      var self = this;

      if (self.options.maxTags && self.itemsArray.length >= self.options.maxTags)
        return;

      // Ignore falsey values, except false
      if (item !== false && !item)
        return;

      // Throw an error when trying to add an object while the itemValue option was not set
      if (typeof item === "object" && !self.objectItems)
        throw("Can't add objects when itemValue option is not set");

      // Ignore strings only containg whitespace
      if (item.toString().match(/^\s*$/))
        return;

      // If SELECT but not multiple, remove current tag
      if (self.isSelect && !self.multiple && self.itemsArray.length > 0)
        self.remove(self.itemsArray[0]);

      if (typeof item === "string" && this.$element[0].tagName === 'INPUT') {
        var items = item.split(',');
        if (items.length > 1) {
          for (var i = 0; i < items.length; i++) {
            this.add(items[i], true);
          }

          if (!dontPushVal)
            self.pushVal();
          return;
        }
      }

      var itemValue = self.options.itemValue(item),
          itemText = self.options.itemText(item),
          tagClass = self.options.tagClass(item);

      // Ignore items allready added
      var existing = $.grep(self.itemsArray, function(item) { return self.options.itemValue(item) === itemValue; } )[0];
      if (existing) {
        // Invoke onTagExists
        if (self.options.onTagExists) {
          var $existingTag = $(".tag", self.$container).filter(function() { return $(this).data("item") === existing; });
          self.options.onTagExists(item, $existingTag);
        }
        return;
      }

      // register item in internal array and map
      self.itemsArray.push(item);

      // add a tag element
      var $tag = $('' + htmlEncode(itemText) + '');
      $tag.data('item', item);
      self.findInputWrapper().before($tag);
      $tag.after(' ');

      // add <option /> if item represents a value not present in one of the <select />'s options
      if (self.isSelect && !$('option[value="' + escape(itemValue) + '"]',self.$element)[0]) {
        var $option = $('<option selected>' + htmlEncode(itemText) + '</option>');
        $option.data('item', item);
        $option.attr('value', itemValue);
        self.$element.append($option);
      }

      if (!dontPushVal)
        self.pushVal();

      // Add class when reached maxTags
      if (self.options.maxTags === self.itemsArray.length)
        self.$container.addClass('bootstrap-tagsinput-max');

      self.$element.trigger($.Event('itemAdded', { item: item }));
    },

    /**
     * Removes the given item. Pass true to dontPushVal to prevent updating the
     * elements val()
     */
    remove: function(item, dontPushVal) {
      var self = this;

      if (self.objectItems) {
        if (typeof item === "object")
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  self.options.itemValue(item); } )[0];
        else
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  item; } )[0];
      }

      if (item) {
        $('.tag', self.$container).filter(function() { return $(this).data('item') === item; }).remove();
        $('option', self.$element).filter(function() { return $(this).data('item') === item; }).remove();
        self.itemsArray.splice($.inArray(item, self.itemsArray), 1);
      }

      if (!dontPushVal)
        self.pushVal();

      // Remove class when reached maxTags
      if (self.options.maxTags > self.itemsArray.length)
        self.$container.removeClass('bootstrap-tagsinput-max');

      self.$element.trigger($.Event('itemRemoved',  { item: item }));
    },

    /**
     * Removes all items
     */
    removeAll: function() {
      var self = this;

      $('.tag', self.$container).remove();
      $('option', self.$element).remove();

      while(self.itemsArray.length > 0)
        self.itemsArray.pop();

      self.pushVal();

      if (self.options.maxTags && !this.isEnabled())
        this.enable();
    },

    /**
     * Refreshes the tags so they match the text/value of their corresponding
     * item.
     */
    refresh: function() {
      var self = this;
      $('.tag', self.$container).each(function() {
        var $tag = $(this),
            item = $tag.data('item'),
            itemValue = self.options.itemValue(item),
            itemText = self.options.itemText(item),
            tagClass = self.options.tagClass(item);

          // Update tag's class and inner text
          $tag.attr('class', null);
          $tag.addClass('tag ' + htmlEncode(tagClass));
          $tag.contents().filter(function() {
            return this.nodeType == 3;
          })[0].nodeValue = htmlEncode(itemText);

          if (self.isSelect) {
            var option = $('option', self.$element).filter(function() { return $(this).data('item') === item; });
            option.attr('value', itemValue);
          }
      });
    },

    /**
     * Returns the items added as tags
     */
    items: function() {
      return this.itemsArray;
    },

    /**
     * Assembly value by retrieving the value of each item, and set it on the
     * element.
     */
    pushVal: function() {
      var self = this,
          val = $.map(self.items(), function(item) {
            return self.options.itemValue(item).toString();
          });

      self.$element.val(val, true).trigger('change');
    },

    /**
     * Initializes the tags input behaviour on the element
     */
    build: function(options) {
      var self = this;

      self.options = $.extend({}, defaultOptions, options);
      var typeahead = self.options.typeahead || {};

      // When itemValue is set, freeInput should always be false
      if (self.objectItems)
        self.options.freeInput = false;

      makeOptionItemFunction(self.options, 'itemValue');
      makeOptionItemFunction(self.options, 'itemText');
      makeOptionItemFunction(self.options, 'tagClass');

      // for backwards compatibility, self.options.source is deprecated
      if (self.options.source)
        typeahead.source = self.options.source;

      if (typeahead.source && $.fn.typeahead) {
        makeOptionFunction(typeahead, 'source');

        self.$input.typeahead({
          source: function (query, process) {
            function processItems(items) {
              var texts = [];

              for (var i = 0; i < items.length; i++) {
                var text = self.options.itemText(items[i]);
                map[text] = items[i];
                texts.push(text);
              }
              process(texts);
            }

            this.map = {};
            var map = this.map,
                data = typeahead.source(query);

            if ($.isFunction(data.success)) {
              // support for Angular promises
              data.success(processItems);
            } else {
              // support for functions and jquery promises
              $.when(data)
               .then(processItems);
            }
          },
          updater: function (text) {
            self.add(this.map[text]);
          },
          matcher: function (text) {
            return (text.toLowerCase().indexOf(this.query.trim().toLowerCase()) !== -1);
          },
          sorter: function (texts) {
            return texts.sort();
          },
          highlighter: function (text) {
            var regex = new RegExp( '(' + this.query + ')', 'gi' );
            return text.replace( regex, "$1" );
          }
        });
      }

      self.$container.on('click', $.proxy(function(event) {
        self.$input.focus();
      }, self));

      self.$container.on('keydown', 'input', $.proxy(function(event) {
        var $input = $(event.target),
            $inputWrapper = self.findInputWrapper();

        switch (event.which) {
          // BACKSPACE
          case 8:
            if (doGetCaretPosition($input[0]) === 0) {
              var prev = $inputWrapper.prev();
              if (prev) {
                self.remove(prev.data('item'));
              }
            }
            break;

          // DELETE
          case 46:
            if (doGetCaretPosition($input[0]) === 0) {
              var next = $inputWrapper.next();
              if (next) {
                self.remove(next.data('item'));
              }
            }
            break;

          // LEFT ARROW
          case 37:
            // Try to move the input before the previous tag
            var $prevTag = $inputWrapper.prev();
            if ($input.val().length === 0 && $prevTag[0]) {
              $prevTag.before($inputWrapper);
              $input.focus();
            }
            break;
          // RIGHT ARROW
          case 39:
            // Try to move the input after the next tag
            var $nextTag = $inputWrapper.next();
            if ($input.val().length === 0 && $nextTag[0]) {
              $nextTag.after($inputWrapper);
              $input.focus();
            }
            break;
         default:
            // When key corresponds one of the confirmKeys, add current input
            // as a new tag
            if (self.options.freeInput && $.inArray(event.which, self.options.confirmKeys) >= 0) {
              self.add($input.val());
              $input.val('');
              event.preventDefault();
            }
        }

        // Reset internal input's size
        $input.attr('size', Math.max(this.inputSize, $input.val().length));
      }, self));

      // Remove icon clicked
      self.$container.on('click', '[data-role=remove]', $.proxy(function(event) {
        self.remove($(event.target).closest('.tag').data('item'));
      }, self));

      // Only add existing value as tags when using strings as tags
      if (self.options.itemValue === defaultOptions.itemValue) {
        if (self.$element[0].tagName === 'INPUT') {
            self.add(self.$element.val());
        } else {
          $('option', self.$element).each(function() {
            self.add($(this).attr('value'), true);
          });
        }
      }
    },

    /**
     * Removes all tagsinput behaviour and unregsiter all event handlers
     */
    destroy: function() {
      var self = this;

      // Unbind events
      self.$container.off('keypress', 'input');
      self.$container.off('click', '[role=remove]');

      self.$container.remove();
      self.$element.removeData('tagsinput');
      self.$element.show();
    },

    /**
     * Sets focus on the tagsinput
     */
    focus: function() {
      this.$input.focus();
    },

    /**
     * Returns the internal input element
     */
    input: function() {
      return this.$input;
    },

    /**
     * Returns the element which is wrapped around the internal input. This
     * is normally the $container, but typeahead.js moves the $input element.
     */
    findInputWrapper: function() {
      var elt = this.$input[0],
          container = this.$container[0];
      while(elt && elt.parentNode !== container)
        elt = elt.parentNode;

      return $(elt);
    }
  };

  /**
   * Register JQuery plugin
   */
  $.fn.tagsinput = function(arg1, arg2) {
    var results = [];

    this.each(function() {
      var tagsinput = $(this).data('tagsinput');

      // Initialize a new tags input
      if (!tagsinput) {
        tagsinput = new TagsInput(this, arg1);
        $(this).data('tagsinput', tagsinput);
        results.push(tagsinput);

        if (this.tagName === 'SELECT') {
          $('option', $(this)).attr('selected', 'selected');
        }

        // Init tags from $(this).val()
        $(this).val($(this).val());
      } else {
        // Invoke function on existing tags input
        var retVal = tagsinput[arg1](arg2);
        if (retVal !== undefined)
          results.push(retVal);
      }
    });

    if ( typeof arg1 == 'string') {
      // Return the results from the invoked function calls
      return results.length > 1 ? results : results[0];
    } else {
      return results;
    }
  };

  $.fn.tagsinput.Constructor = TagsInput;

  /**
   * Most options support both a string or number as well as a function as
   * option value. This function makes sure that the option with the given
   * key in the given options is wrapped in a function
   */
  function makeOptionItemFunction(options, key) {
    if (typeof options[key] !== 'function') {
      var propertyName = options[key];
      options[key] = function(item) { return item[propertyName]; };
    }
  }
  function makeOptionFunction(options, key) {
    if (typeof options[key] !== 'function') {
      var value = options[key];
      options[key] = function() { return value; };
    }
  }
  /**
   * HtmlEncodes the given value
   */
  var htmlEncodeContainer = $('
');
  function htmlEncode(value) {
    if (value) {
      return htmlEncodeContainer.text(value).html();
    } else {
      return '';
    }
  }

  /**
   * Returns the position of the caret in the given input field
   * http://flightschool.acylt.com/devnotes/caret-position-woes/
   */
  function doGetCaretPosition(oField) {
    var iCaretPos = 0;
    if (document.selection) {
      oField.focus ();
      var oSel = document.selection.createRange();
      oSel.moveStart ('character', -oField.value.length);
      iCaretPos = oSel.text.length;
    } else if (oField.selectionStart || oField.selectionStart == '0') {
      iCaretPos = oField.selectionStart;
    }
    return (iCaretPos);
  }

  /**
   * Initialize tagsinput behaviour on inputs and selects which have
   * data-role=tagsinput
   */
  $(function() {
    $("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();
  });
})(window.jQuery);
<commit_msg>remove auto apply to be able manually initialized<commit_after>(function ($) {
  "use strict";

  var defaultOptions = {
    tagClass: function(item) {
      return 'label label-info';
    },
    itemValue: function(item) {
      return item ? item.toString() : item;
    },
    itemText: function(item) {
      return this.itemValue(item);
    },
    freeInput: true,
    maxTags: undefined,
    confirmKeys: [13],
    onTagExists: function(item, $tag) {
      $tag.hide().fadeIn();
    }
  };

  /**
   * Constructor function
   */
  function TagsInput(element, options) {
    this.itemsArray = [];

    this.$element = $(element);
    this.$element.hide();

    this.isSelect = (element.tagName === 'SELECT');
    this.multiple = (this.isSelect && element.hasAttribute('multiple'));
    this.objectItems = options && options.itemValue;
    this.placeholderText = element.hasAttribute('placeholder') ? this.$element.attr('placeholder') : '';
    this.inputSize = Math.max(1, this.placeholderText.length);

    this.$container = $('

');
    this.$input = $('<input size="' + this.inputSize + '" type="text" placeholder="' + this.placeholderText + '"/>').appendTo(this.$container);

    this.$element.after(this.$container);

    this.build(options);
  }

  TagsInput.prototype = {
    constructor: TagsInput,

    /**
     * Adds the given item as a new tag. Pass true to dontPushVal to prevent
     * updating the elements val()
     */
    add: function(item, dontPushVal) {
      var self = this;

      if (self.options.maxTags && self.itemsArray.length >= self.options.maxTags)
        return;

      // Ignore falsey values, except false
      if (item !== false && !item)
        return;

      // Throw an error when trying to add an object while the itemValue option was not set
      if (typeof item === "object" && !self.objectItems)
        throw("Can't add objects when itemValue option is not set");

      // Ignore strings only containg whitespace
      if (item.toString().match(/^\s*$/))
        return;

      // If SELECT but not multiple, remove current tag
      if (self.isSelect && !self.multiple && self.itemsArray.length > 0)
        self.remove(self.itemsArray[0]);

      if (typeof item === "string" && this.$element[0].tagName === 'INPUT') {
        var items = item.split(',');
        if (items.length > 1) {
          for (var i = 0; i < items.length; i++) {
            this.add(items[i], true);
          }

          if (!dontPushVal)
            self.pushVal();
          return;
        }
      }

      var itemValue = self.options.itemValue(item),
          itemText = self.options.itemText(item),
          tagClass = self.options.tagClass(item);

      // Ignore items allready added
      var existing = $.grep(self.itemsArray, function(item) { return self.options.itemValue(item) === itemValue; } )[0];
      if (existing) {
        // Invoke onTagExists
        if (self.options.onTagExists) {
          var $existingTag = $(".tag", self.$container).filter(function() { return $(this).data("item") === existing; });
          self.options.onTagExists(item, $existingTag);
        }
        return;
      }

      // register item in internal array and map
      self.itemsArray.push(item);

      // add a tag element
      var $tag = $('' + htmlEncode(itemText) + '');
      $tag.data('item', item);
      self.findInputWrapper().before($tag);
      $tag.after(' ');

      // add <option /> if item represents a value not present in one of the <select />'s options
      if (self.isSelect && !$('option[value="' + escape(itemValue) + '"]',self.$element)[0]) {
        var $option = $('<option selected>' + htmlEncode(itemText) + '</option>');
        $option.data('item', item);
        $option.attr('value', itemValue);
        self.$element.append($option);
      }

      if (!dontPushVal)
        self.pushVal();

      // Add class when reached maxTags
      if (self.options.maxTags === self.itemsArray.length)
        self.$container.addClass('bootstrap-tagsinput-max');

      self.$element.trigger($.Event('itemAdded', { item: item }));
    },

    /**
     * Removes the given item. Pass true to dontPushVal to prevent updating the
     * elements val()
     */
    remove: function(item, dontPushVal) {
      var self = this;

      if (self.objectItems) {
        if (typeof item === "object")
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  self.options.itemValue(item); } )[0];
        else
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  item; } )[0];
      }

      if (item) {
        $('.tag', self.$container).filter(function() { return $(this).data('item') === item; }).remove();
        $('option', self.$element).filter(function() { return $(this).data('item') === item; }).remove();
        self.itemsArray.splice($.inArray(item, self.itemsArray), 1);
      }

      if (!dontPushVal)
        self.pushVal();

      // Remove class when reached maxTags
      if (self.options.maxTags > self.itemsArray.length)
        self.$container.removeClass('bootstrap-tagsinput-max');

      self.$element.trigger($.Event('itemRemoved',  { item: item }));
    },

    /**
     * Removes all items
     */
    removeAll: function() {
      var self = this;

      $('.tag', self.$container).remove();
      $('option', self.$element).remove();

      while(self.itemsArray.length > 0)
        self.itemsArray.pop();

      self.pushVal();

      if (self.options.maxTags && !this.isEnabled())
        this.enable();
    },

    /**
     * Refreshes the tags so they match the text/value of their corresponding
     * item.
     */
    refresh: function() {
      var self = this;
      $('.tag', self.$container).each(function() {
        var $tag = $(this),
            item = $tag.data('item'),
            itemValue = self.options.itemValue(item),
            itemText = self.options.itemText(item),
            tagClass = self.options.tagClass(item);

          // Update tag's class and inner text
          $tag.attr('class', null);
          $tag.addClass('tag ' + htmlEncode(tagClass));
          $tag.contents().filter(function() {
            return this.nodeType == 3;
          })[0].nodeValue = htmlEncode(itemText);

          if (self.isSelect) {
            var option = $('option', self.$element).filter(function() { return $(this).data('item') === item; });
            option.attr('value', itemValue);
          }
      });
    },

    /**
     * Returns the items added as tags
     */
    items: function() {
      return this.itemsArray;
    },

    /**
     * Assembly value by retrieving the value of each item, and set it on the
     * element.
     */
    pushVal: function() {
      var self = this,
          val = $.map(self.items(), function(item) {
            return self.options.itemValue(item).toString();
          });

      self.$element.val(val, true).trigger('change');
    },

    /**
     * Initializes the tags input behaviour on the element
     */
    build: function(options) {
      var self = this;

      self.options = $.extend({}, defaultOptions, options);
      var typeahead = self.options.typeahead || {};

      // When itemValue is set, freeInput should always be false
      if (self.objectItems)
        self.options.freeInput = false;

      makeOptionItemFunction(self.options, 'itemValue');
      makeOptionItemFunction(self.options, 'itemText');
      makeOptionItemFunction(self.options, 'tagClass');

      // for backwards compatibility, self.options.source is deprecated
      if (self.options.source)
        typeahead.source = self.options.source;

      if (typeahead.source && $.fn.typeahead) {
        makeOptionFunction(typeahead, 'source');

        self.$input.typeahead({
          source: function (query, process) {
            function processItems(items) {
              var texts = [];

              for (var i = 0; i < items.length; i++) {
                var text = self.options.itemText(items[i]);
                map[text] = items[i];
                texts.push(text);
              }
              process(texts);
            }

            this.map = {};
            var map = this.map,
                data = typeahead.source(query);

            if ($.isFunction(data.success)) {
              // support for Angular promises
              data.success(processItems);
            } else {
              // support for functions and jquery promises
              $.when(data)
               .then(processItems);
            }
          },
          updater: function (text) {
            self.add(this.map[text]);
          },
          matcher: function (text) {
            return (text.toLowerCase().indexOf(this.query.trim().toLowerCase()) !== -1);
          },
          sorter: function (texts) {
            return texts.sort();
          },
          highlighter: function (text) {
            var regex = new RegExp( '(' + this.query + ')', 'gi' );
            return text.replace( regex, "$1" );
          }
        });
      }

      self.$container.on('click', $.proxy(function(event) {
        self.$input.focus();
      }, self));

      self.$container.on('keydown', 'input', $.proxy(function(event) {
        var $input = $(event.target),
            $inputWrapper = self.findInputWrapper();

        switch (event.which) {
          // BACKSPACE
          case 8:
            if (doGetCaretPosition($input[0]) === 0) {
              var prev = $inputWrapper.prev();
              if (prev) {
                self.remove(prev.data('item'));
              }
            }
            break;

          // DELETE
          case 46:
            if (doGetCaretPosition($input[0]) === 0) {
              var next = $inputWrapper.next();
              if (next) {
                self.remove(next.data('item'));
              }
            }
            break;

          // LEFT ARROW
          case 37:
            // Try to move the input before the previous tag
            var $prevTag = $inputWrapper.prev();
            if ($input.val().length === 0 && $prevTag[0]) {
              $prevTag.before($inputWrapper);
              $input.focus();
            }
            break;
          // RIGHT ARROW
          case 39:
            // Try to move the input after the next tag
            var $nextTag = $inputWrapper.next();
            if ($input.val().length === 0 && $nextTag[0]) {
              $nextTag.after($inputWrapper);
              $input.focus();
            }
            break;
         default:
            // When key corresponds one of the confirmKeys, add current input
            // as a new tag
            if (self.options.freeInput && $.inArray(event.which, self.options.confirmKeys) >= 0) {
              self.add($input.val());
              $input.val('');
              event.preventDefault();
            }
        }

        // Reset internal input's size
        $input.attr('size', Math.max(this.inputSize, $input.val().length));
      }, self));

      // Remove icon clicked
      self.$container.on('click', '[data-role=remove]', $.proxy(function(event) {
        self.remove($(event.target).closest('.tag').data('item'));
      }, self));

      // Only add existing value as tags when using strings as tags
      if (self.options.itemValue === defaultOptions.itemValue) {
        if (self.$element[0].tagName === 'INPUT') {
            self.add(self.$element.val());
        } else {
          $('option', self.$element).each(function() {
            self.add($(this).attr('value'), true);
          });
        }
      }
    },

    /**
     * Removes all tagsinput behaviour and unregsiter all event handlers
     */
    destroy: function() {
      var self = this;

      // Unbind events
      self.$container.off('keypress', 'input');
      self.$container.off('click', '[role=remove]');

      self.$container.remove();
      self.$element.removeData('tagsinput');
      self.$element.show();
    },

    /**
     * Sets focus on the tagsinput
     */
    focus: function() {
      this.$input.focus();
    },

    /**
     * Returns the internal input element
     */
    input: function() {
      return this.$input;
    },

    /**
     * Returns the element which is wrapped around the internal input. This
     * is normally the $container, but typeahead.js moves the $input element.
     */
    findInputWrapper: function() {
      var elt = this.$input[0],
          container = this.$container[0];
      while(elt && elt.parentNode !== container)
        elt = elt.parentNode;

      return $(elt);
    }
  };

  /**
   * Register JQuery plugin
   */
  $.fn.tagsinput = function(arg1, arg2) {
    var results = [];

    this.each(function() {
      var tagsinput = $(this).data('tagsinput');

      // Initialize a new tags input
      if (!tagsinput) {
        tagsinput = new TagsInput(this, arg1);
        $(this).data('tagsinput', tagsinput);
        results.push(tagsinput);

        if (this.tagName === 'SELECT') {
          $('option', $(this)).attr('selected', 'selected');
        }

        // Init tags from $(this).val()
        $(this).val($(this).val());
      } else {
        // Invoke function on existing tags input
        var retVal = tagsinput[arg1](arg2);
        if (retVal !== undefined)
          results.push(retVal);
      }
    });

    if ( typeof arg1 == 'string') {
      // Return the results from the invoked function calls
      return results.length > 1 ? results : results[0];
    } else {
      return results;
    }
  };

  $.fn.tagsinput.Constructor = TagsInput;

  /**
   * Most options support both a string or number as well as a function as
   * option value. This function makes sure that the option with the given
   * key in the given options is wrapped in a function
   */
  function makeOptionItemFunction(options, key) {
    if (typeof options[key] !== 'function') {
      var propertyName = options[key];
      options[key] = function(item) { return item[propertyName]; };
    }
  }
  function makeOptionFunction(options, key) {
    if (typeof options[key] !== 'function') {
      var value = options[key];
      options[key] = function() { return value; };
    }
  }
  /**
   * HtmlEncodes the given value
   */
  var htmlEncodeContainer = $('
');
  function htmlEncode(value) {
    if (value) {
      return htmlEncodeContainer.text(value).html();
    } else {
      return '';
    }
  }

  /**
   * Returns the position of the caret in the given input field
   * http://flightschool.acylt.com/devnotes/caret-position-woes/
   */
  function doGetCaretPosition(oField) {
    var iCaretPos = 0;
    if (document.selection) {
      oField.focus ();
      var oSel = document.selection.createRange();
      oSel.moveStart ('character', -oField.value.length);
      iCaretPos = oSel.text.length;
    } else if (oField.selectionStart || oField.selectionStart == '0') {
      iCaretPos = oField.selectionStart;
    }
    return (iCaretPos);
  }

  /**
   * Initialize tagsinput behaviour on inputs and selects which have
   * data-role=tagsinput
   */
  $(function() {
    /*$("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();*/
  });
})(window.jQuery);
<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');

var mongoNb = process.env.SOAJS_MONGO_NB || 1;
mongoNb = parseInt(mongoNb);
var mongoRsName = process.env.SOAJS_MONGO_RSNAME || "rs_soajs";

var profileLocation = process.env.SOAJS_PROFILE_LOC || "/opt/soajs/FILES/profiles/";

var lib = {
    "writeSingle": function (param, cb) {
        console.log("writing single profile @" + param.loc);
        var wstream = fs.createWriteStream(param.loc + param.profileFileName);

        wstream.write('\'use strict\';\n');
        wstream.write('module.exports = {\n');
        wstream.write('    "name": "core_provision",\n');
        wstream.write('    "prefix": "",\n');
        wstream.write('    "servers": [\n');

        for (var i = 1; i <= param.count; i++) {
            if (process.env[param.ipEnvName + i]) {
                wstream.write('        {\n');
                wstream.write('                 "host": "' + process.env[param.ipEnvName + i] + '",\n');
                wstream.write('                 "port": ' + (process.env[param.portEnvName + i] || param.portDefault) + '\n');
                if (i === param.count)
                    wstream.write('        }\n');
                else
                    wstream.write('        },\n');
            }
            else
                console.log("ERROR: Unable to find environment variable " + param.ipEnvName + i);
        }

        wstream.write('    ],\n');

        if (process.env.SOAJS_MONGO_USERNAME && process.env.SOAJS_MONGO_PASSWORD) {
            wstream.write('    "credentials": {\n');
            wstream.write('        "username": "' + process.env.SOAJS_MONGO_USERNAME + '",\n');
            wstream.write('        "password": "' + process.env.SOAJS_MONGO_PASSWORD + '"\n');
            wstream.write('    },\n');
        }
        else
            wstream.write('    "credentials": null,\n');

        wstream.write('    "URLParam": {\n');
        wstream.write('        "connectTimeoutMS": 0,\n');
        wstream.write('        "socketTimeoutMS": 0,\n');
        wstream.write('        "maxPoolSize": 5,\n');
        wstream.write('        "wtimeoutMS": 0,\n');
        wstream.write('        "slaveOk": true\n');
        wstream.write('    },\n');
        wstream.write('    "extraParam": {\n');
        wstream.write('        "db": {\n');
        wstream.write('            "native_parser": true\n');
        wstream.write('       },\n');
        wstream.write('       "server": {\n');
        wstream.write('            "auto_reconnect": true\n');
        wstream.write('        }\n');
        wstream.write('    }\n');
        wstream.write('};\n');

        wstream.end();
        return cb(null);
    },
    "writeReplica": function (param, cb) {
        console.log("writing replica profile @" + param.loc);
        var wstream = fs.createWriteStream(param.loc + param.profileFileName);

        wstream.write('\'use strict\';\n');
        wstream.write('module.exports = {\n');
        wstream.write('    "name": "core_provision",\n');
        wstream.write('    "prefix": "",\n');
        wstream.write('    "servers": [\n');

        for (var i = 1; i <= param.count; i++) {
            if (process.env[param.ipEnvName + i]) {
                wstream.write('        {\n');
                wstream.write('                 "host": "' + process.env[param.ipEnvName + i] + '",\n');
                wstream.write('                 "port": ' + (process.env[param.portEnvName + i] || param.portDefault) + '\n');
                if (i === param.count)
                    wstream.write('        }\n');
                else
                    wstream.write('        },\n');
            }
            else
                console.log("ERROR: Unable to find environment variable " + param.ipEnvName + i);
        }

        wstream.write('    ],\n');

        if (process.env.SOAJS_MONGO_USERNAME && process.env.SOAJS_MONGO_PASSWORD) {
            wstream.write('    "credentials": {\n');
            wstream.write('        "username": "' + process.env.SOAJS_MONGO_USERNAME + '",\n');
            wstream.write('        "password": "' + process.env.SOAJS_MONGO_PASSWORD + '"\n');
            wstream.write('    },\n');
        }
        else
            wstream.write('    "credentials": null,\n');

        wstream.write('    "URLParam": {\n');
        wstream.write('        "connectTimeoutMS": 0,\n');
        wstream.write('        "socketTimeoutMS": 0,\n');
        wstream.write('        "maxPoolSize": 5,\n');
        wstream.write('        "wtimeoutMS": 0,\n');
        wstream.write('        "slaveOk": true\n');
        wstream.write('    },\n');
        wstream.write('    "extraParam": {\n');
        wstream.write('        "db": {\n');
        wstream.write('            "native_parser": true,\n');
        wstream.write('            "w": "majority"\n');
        wstream.write('       },\n');
        wstream.write('       "server": {\n');
        wstream.write('            "ha": true,\n');
        wstream.write('            "readPreference": "secondaryPreferred",\n');
        wstream.write('            "rs_name": "' + param.rsName + '"\n');
        wstream.write('        }\n');
        wstream.write('    }\n');
        wstream.write('};\n');

        wstream.end();
        return cb(null);
    }
};

if (mongoNb === 1) {
    lib.writeSingle({
        "profileFileName": 'profile.js',
        "loc": profileLocation,
        "count": mongoNb,
        "ipEnvName": "SOAJS_MONGO_IP_",
        "portEnvName": "SOAJS_MONGO_PORT_",
        "portDefault": 27017
    }, function (err) {
        console.log("PROFILE SINGLE DONE.");
    });
} else if (mongoNb > 1) {
    lib.writeReplica({
        "profileFileName": 'profile.js',
        "loc": profileLocation,
        "count": mongoNb,
        "ipEnvName": "SOAJS_MONGO_IP_",
        "portEnvName": "SOAJS_MONGO_PORT_",
        "portDefault": 27017,
        "rsName": mongoRsName
    }, function (err) {
        console.log("PROFILE REPLICA DONE.");
    });
} else {
    console.log("ERROR: PROFILE CREATION FAILED. Environment variable SOAJS_MONGO_NB must be integer [" + mongoNb + "]");
}
<commit_msg>profile for mongo supports ssl<commit_after>'use strict';
var fs = require('fs');

var mongoNb = process.env.SOAJS_MONGO_NB || 1;
mongoNb = parseInt(mongoNb);
var mongoRsName = process.env.SOAJS_MONGO_RSNAME || "rs_soajs";

var profileLocation = process.env.SOAJS_PROFILE_LOC || "/opt/soajs/FILES/profiles/";

var lib = {
    "writeSingle": function (param, cb) {
        console.log("writing single profile @" + param.loc);
        var wstream = fs.createWriteStream(param.loc + param.profileFileName);

        wstream.write('\'use strict\';\n');
        wstream.write('module.exports = {\n');
        wstream.write('    "name": "core_provision",\n');
        wstream.write('    "prefix": "",\n');
        wstream.write('    "servers": [\n');

        for (var i = 1; i <= param.count; i++) {
            if (process.env[param.ipEnvName + i]) {
                wstream.write('        {\n');
                wstream.write('                 "host": "' + process.env[param.ipEnvName + i] + '",\n');
                wstream.write('                 "port": ' + (process.env[param.portEnvName + i] || param.portDefault) + '\n');
                if (i === param.count)
                    wstream.write('        }\n');
                else
                    wstream.write('        },\n');
            }
            else
                console.log("ERROR: Unable to find environment variable " + param.ipEnvName + i);
        }

        wstream.write('    ],\n');

        if (process.env.SOAJS_MONGO_USERNAME && process.env.SOAJS_MONGO_PASSWORD) {
            wstream.write('    "credentials": {\n');
            wstream.write('        "username": "' + process.env.SOAJS_MONGO_USERNAME + '",\n');
            wstream.write('        "password": "' + process.env.SOAJS_MONGO_PASSWORD + '"\n');
            wstream.write('    },\n');
        }
        else
            wstream.write('    "credentials": null,\n');

        wstream.write('    "URLParam": {\n');
        wstream.write('        "connectTimeoutMS": 0,\n');
        wstream.write('        "socketTimeoutMS": 0,\n');
        wstream.write('        "maxPoolSize": 5,\n');
        wstream.write('        "wtimeoutMS": 0,\n');
        wstream.write('        "slaveOk": true\n');
        wstream.write('    },\n');
        wstream.write('    "extraParam": {\n');
        wstream.write('        "db": {\n');
        wstream.write('            "native_parser": true\n');
        wstream.write('       },\n');
        wstream.write('       "server": {\n');
        wstream.write('            "auto_reconnect": true,\n');
        wstream.write('            "ssl": prefer\n');
        wstream.write('        }\n');
        wstream.write('    }\n');
        wstream.write('};\n');

        wstream.end();
        return cb(null);
    },
    "writeReplica": function (param, cb) {
        console.log("writing replica profile @" + param.loc);
        var wstream = fs.createWriteStream(param.loc + param.profileFileName);

        wstream.write('\'use strict\';\n');
        wstream.write('module.exports = {\n');
        wstream.write('    "name": "core_provision",\n');
        wstream.write('    "prefix": "",\n');
        wstream.write('    "servers": [\n');

        for (var i = 1; i <= param.count; i++) {
            if (process.env[param.ipEnvName + i]) {
                wstream.write('        {\n');
                wstream.write('                 "host": "' + process.env[param.ipEnvName + i] + '",\n');
                wstream.write('                 "port": ' + (process.env[param.portEnvName + i] || param.portDefault) + '\n');
                if (i === param.count)
                    wstream.write('        }\n');
                else
                    wstream.write('        },\n');
            }
            else
                console.log("ERROR: Unable to find environment variable " + param.ipEnvName + i);
        }

        wstream.write('    ],\n');

        if (process.env.SOAJS_MONGO_USERNAME && process.env.SOAJS_MONGO_PASSWORD) {
            wstream.write('    "credentials": {\n');
            wstream.write('        "username": "' + process.env.SOAJS_MONGO_USERNAME + '",\n');
            wstream.write('        "password": "' + process.env.SOAJS_MONGO_PASSWORD + '"\n');
            wstream.write('    },\n');
        }
        else
            wstream.write('    "credentials": null,\n');

        wstream.write('    "URLParam": {\n');
        wstream.write('        "connectTimeoutMS": 0,\n');
        wstream.write('        "socketTimeoutMS": 0,\n');
        wstream.write('        "maxPoolSize": 5,\n');
        wstream.write('        "wtimeoutMS": 0,\n');
        wstream.write('        "slaveOk": true\n');
        wstream.write('    },\n');
        wstream.write('    "extraParam": {\n');
        wstream.write('        "db": {\n');
        wstream.write('            "native_parser": true,\n');
        wstream.write('            "w": "majority"\n');
        wstream.write('       },\n');
        wstream.write('       "server": {\n');
        wstream.write('            "ha": true,\n');
        wstream.write('            "ssl": prefer,\n');
        wstream.write('            "readPreference": "secondaryPreferred",\n');
        wstream.write('            "rs_name": "' + param.rsName + '"\n');
        wstream.write('        }\n');
        wstream.write('    }\n');
        wstream.write('};\n');

        wstream.end();
        return cb(null);
    }
};

if (mongoNb === 1) {
    lib.writeSingle({
        "profileFileName": 'profile.js',
        "loc": profileLocation,
        "count": mongoNb,
        "ipEnvName": "SOAJS_MONGO_IP_",
        "portEnvName": "SOAJS_MONGO_PORT_",
        "portDefault": 27017
    }, function (err) {
        console.log("PROFILE SINGLE DONE.");
    });
} else if (mongoNb > 1) {
    lib.writeReplica({
        "profileFileName": 'profile.js',
        "loc": profileLocation,
        "count": mongoNb,
        "ipEnvName": "SOAJS_MONGO_IP_",
        "portEnvName": "SOAJS_MONGO_PORT_",
        "portDefault": 27017,
        "rsName": mongoRsName
    }, function (err) {
        console.log("PROFILE REPLICA DONE.");
    });
} else {
    console.log("ERROR: PROFILE CREATION FAILED. Environment variable SOAJS_MONGO_NB must be integer [" + mongoNb + "]");
}
<|endoftext|>


<commit_before>/*
 * jQuery UI Button @VERSION
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Button
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function( $ ) {

var lastActive,
	baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
	otherClasses = "ui-state-hover ui-state-active " +
		"ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon ui-button-text-only",
	formResetHandler = function( event ) {
		$( ":ui-button", event.target.form ).each(function() {
			var inst = $( this ).data( "button" );
			setTimeout(function() {
				inst.refresh();
			}, 1 );
		});
	},
	radioGroup = function( radio ) {
		var name = radio.name,
			form = radio.form,
			radios = $( [] );
		if ( name ) {
			if ( form ) {
				radios = $( form ).find( "[name='" + name + "']" );
			} else {
				radios = $( "[name='" + name + "']", radio.ownerDocument )
					.filter(function() {
						return !this.form;
					});
			}
		}
		return radios;
	};

$.widget( "ui.button", {
	options: {
		text: true,
		label: null,
		icons: {
			primary: null,
			secondary: null
		}
	},
	_create: function() {
		this.element.closest( "form" )
			.unbind( "reset.button" )
			.bind( "reset.button", formResetHandler );

		this._determineButtonType();
		this.hasTitle = !!this.buttonElement.attr( "title" );

		var self = this,
			options = this.options,
			toggleButton = this.type === "checkbox" || this.type === "radio",
			hoverClass = "ui-state-hover" + ( !toggleButton ? " ui-state-active" : "" ),
			focusClass = "ui-state-focus";

		if ( options.label === null ) {
			options.label = this.buttonElement.html();
		}

		this.buttonElement
			.addClass( baseClasses )
			.attr( "role", "button" )
			.bind( "mouseenter.button", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).addClass( "ui-state-hover" );
				if ( this === lastActive ) {
					$( this ).addClass( "ui-state-active" );
				}
			})
			.bind( "mouseleave.button", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).removeClass( hoverClass );
			})
			.bind( "focus.button", function() {
				// no need to check disabled, focus won't be triggered anyway
				$( this ).addClass( focusClass );
			})
			.bind( "blur.button", function() {
				$( this ).removeClass( focusClass );
			});

		if ( toggleButton ) {
			this.element.bind( "change.button", function() {
				self.refresh();
			});
		}

		if ( this.type === "checkbox") {
			this.buttonElement.bind( "click.button", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).toggleClass( "ui-state-active" );
				self.buttonElement.attr( "aria-pressed", self.element[0].checked );
			});
		} else if ( this.type === "radio") {
			this.buttonElement.bind( "click.button", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).addClass( "ui-state-active" );
				self.buttonElement.attr( "aria-pressed", true );

				var radio = self.element[ 0 ];
				radioGroup( radio )
					.not( radio )
					.map(function() {
						return $( this ).button( "widget" )[ 0 ];
					})
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", false );
			});
		} else {
			this.buttonElement
				.bind( "mousedown.button", function() {
					if ( options.disabled ) {
						return;
					}
					$( this ).addClass( "ui-state-active" );
					lastActive = this;
					$( document ).one( "mouseup", function() {
						lastActive = null;
					});
				})
				.bind( "mouseup.button", function() {
					if ( options.disabled ) {
						return;
					}
					$( this ).removeClass( "ui-state-active" );
				})
				.bind( "keydown.button", function(event) {
					if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
						$( this ).addClass( "ui-state-active" );
					}
				})
				.bind( "keyup.button", function() {
					$( this ).removeClass( "ui-state-active" );
				});

			if ( this.buttonElement.is("a") ) {
				this.buttonElement.keyup(function(event) {
					if ( event.keyCode === $.ui.keyCode.SPACE ) {
						// TODO pass through original event correctly (just as 2nd argument doesn't work)
						$( this ).click();
					}
				});
			}
		}

		// TODO: pull out $.Widget's handling for the disabled option into
		// $.Widget.prototype._setOptionDisabled so it's easy to proxy and can
		// be overridden by individual plugins
		$.Widget.prototype._setOption.call( this, "disabled", options.disabled );
		this._resetButton();
	},

	_determineButtonType: function() {

		if ( this.element.is(":checkbox") ) {
			this.type = "checkbox";
		} else {
			if ( this.element.is(":radio") ) {
				this.type = "radio";
			} else {
				if (this.element.is("input") ) {
					this.type = "input";
				} else {
					this.type = "button";
				}
			}
		}

		if ( this.type === "checkbox" || this.type === "radio" ) {
			// we don't search against the document in case the element
			// is disconnected from the DOM
			this.buttonElement = this.element.parents().last()
				.find( "[for=" + this.element.attr("id") + "]" );
			this.element.addClass('ui-helper-hidden-accessible');

			var checked = this.element.is( ":checked" );
			if ( checked ) {
				this.buttonElement.addClass( "ui-state-active" );
			}
			this.buttonElement.attr( "aria-pressed", checked );
		} else {
			this.buttonElement = this.element;
		}
	},

	widget: function() {
		return this.buttonElement;
	},

	destroy: function() {
		this.buttonElement
			.removeClass( baseClasses + " ui-helper-hidden-accessible " + otherClasses )
			.removeAttr( "role" )
			.removeAttr( "aria-pressed" )
			.html( this.buttonElement.find(".ui-button-text").html() );

		if ( !this.hasTitle ) {
			this.buttonElement.removeAttr( "title" );
		}

		$.Widget.prototype.destroy.call( this );
	},

	_setOption: function( key, value ) {
		$.Widget.prototype._setOption.apply( this, arguments );
		this._resetButton();
	},

	refresh: function() {
		if ( this.type === "radio" ) {
			radioGroup( this.element[0] ).each(function() {
				if ( $( this ).is( ":checked" ) ) {
					$( this ).button( "widget" )
						.addClass( "ui-state-active" )
						.attr( "aria-pressed", true );
				} else {
					$( this ).button( "widget" )
						.removeClass( "ui-state-active" )
						.attr( "aria-pressed", false );
				}
			});
		} else if ( this.type === "checkbox" ) {
			if ( this.element.is( ":checked" ) ) {
				this.buttonElement
					.addClass( "ui-state-active" )
					.attr( "aria-pressed", true );
			} else {
				this.buttonElement
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", false );
			}
		}
	},

	_resetButton: function() {
		if ( this.type === "input" ) {
			if ( this.options.label ) {
				this.element.val( this.options.label );
			}
			return;
		}
		var buttonElement = this.buttonElement,
			buttonText = $( "" )
				.addClass( "ui-button-text" )
				.html( this.options.label )
				.appendTo( buttonElement.empty() )
				.text(),
			icons = this.options.icons,
			multipleIcons = icons.primary && icons.secondary;
		if ( icons.primary || icons.secondary ) {
			buttonElement.addClass( "ui-button-text-icon" +
				( multipleIcons ? "s" : "" ) );
			if ( icons.primary ) {
				buttonElement.prepend( "" );
			}
			if ( icons.secondary ) {
				buttonElement.append( "" );
			}
			if ( !this.options.text ) {
				buttonElement
					.addClass( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" )
					.removeClass( "ui-button-text-icons ui-button-text-icon" );
				if ( !this.hasTitle ) {
					buttonElement.attr( "title", buttonText );
				}
			}
		} else {
			buttonElement.addClass( "ui-button-text-only" );
		}
	}
});

$.widget( "ui.buttonset", {
	_create: function() {
		this.element.addClass( "ui-button-set" );
		this.buttons = this.element.find( ":button, :submit, :reset, :checkbox, :radio, a, :data(button)" )
			.button()
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "ui-corner-all" )
				.filter( ":first" )
					.addClass( "ui-corner-left" )
				.end()
				.filter( ":last" )
					.addClass( "ui-corner-right" )
				.end()
			.end();
	},

	_setOption: function( key, value ) {
		if ( key === "disabled" ) {
			this.buttons.button( "option", key, value );
		}

		$.Widget.prototype._setOption.apply( this, arguments );
	},

	destroy: function() {
		this.element.removeClass( "ui-button-set" );
		this.buttons
			.button( "destroy" )
			.removeClass( "ui-corner-left ui-corner-right" );

		$.Widget.prototype.destroy.call( this );
	}
});

}( jQuery ));
<commit_msg>Button: Don't react to keydown when disabled.<commit_after>/*
 * jQuery UI Button @VERSION
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Button
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function( $ ) {

var lastActive,
	baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
	otherClasses = "ui-state-hover ui-state-active " +
		"ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon ui-button-text-only",
	formResetHandler = function( event ) {
		$( ":ui-button", event.target.form ).each(function() {
			var inst = $( this ).data( "button" );
			setTimeout(function() {
				inst.refresh();
			}, 1 );
		});
	},
	radioGroup = function( radio ) {
		var name = radio.name,
			form = radio.form,
			radios = $( [] );
		if ( name ) {
			if ( form ) {
				radios = $( form ).find( "[name='" + name + "']" );
			} else {
				radios = $( "[name='" + name + "']", radio.ownerDocument )
					.filter(function() {
						return !this.form;
					});
			}
		}
		return radios;
	};

$.widget( "ui.button", {
	options: {
		text: true,
		label: null,
		icons: {
			primary: null,
			secondary: null
		}
	},
	_create: function() {
		this.element.closest( "form" )
			.unbind( "reset.button" )
			.bind( "reset.button", formResetHandler );

		this._determineButtonType();
		this.hasTitle = !!this.buttonElement.attr( "title" );

		var self = this,
			options = this.options,
			toggleButton = this.type === "checkbox" || this.type === "radio",
			hoverClass = "ui-state-hover" + ( !toggleButton ? " ui-state-active" : "" ),
			focusClass = "ui-state-focus";

		if ( options.label === null ) {
			options.label = this.buttonElement.html();
		}

		this.buttonElement
			.addClass( baseClasses )
			.attr( "role", "button" )
			.bind( "mouseenter.button", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).addClass( "ui-state-hover" );
				if ( this === lastActive ) {
					$( this ).addClass( "ui-state-active" );
				}
			})
			.bind( "mouseleave.button", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).removeClass( hoverClass );
			})
			.bind( "focus.button", function() {
				// no need to check disabled, focus won't be triggered anyway
				$( this ).addClass( focusClass );
			})
			.bind( "blur.button", function() {
				$( this ).removeClass( focusClass );
			});

		if ( toggleButton ) {
			this.element.bind( "change.button", function() {
				self.refresh();
			});
		}

		if ( this.type === "checkbox" ) {
			this.buttonElement.bind( "click.button", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).toggleClass( "ui-state-active" );
				self.buttonElement.attr( "aria-pressed", self.element[0].checked );
			});
		} else if ( this.type === "radio" ) {
			this.buttonElement.bind( "click.button", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).addClass( "ui-state-active" );
				self.buttonElement.attr( "aria-pressed", true );

				var radio = self.element[ 0 ];
				radioGroup( radio )
					.not( radio )
					.map(function() {
						return $( this ).button( "widget" )[ 0 ];
					})
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", false );
			});
		} else {
			this.buttonElement
				.bind( "mousedown.button", function() {
					if ( options.disabled ) {
						return;
					}
					$( this ).addClass( "ui-state-active" );
					lastActive = this;
					$( document ).one( "mouseup", function() {
						lastActive = null;
					});
				})
				.bind( "mouseup.button", function() {
					if ( options.disabled ) {
						return;
					}
					$( this ).removeClass( "ui-state-active" );
				})
				.bind( "keydown.button", function(event) {
					if ( options.disabled ) {
						return;
					}
					if ( event.keyCode == $.ui.keyCode.SPACE || event.keyCode == $.ui.keyCode.ENTER ) {
						$( this ).addClass( "ui-state-active" );
					}
				})
				.bind( "keyup.button", function() {
					$( this ).removeClass( "ui-state-active" );
				});

			if ( this.buttonElement.is("a") ) {
				this.buttonElement.keyup(function(event) {
					if ( event.keyCode === $.ui.keyCode.SPACE ) {
						// TODO pass through original event correctly (just as 2nd argument doesn't work)
						$( this ).click();
					}
				});
			}
		}

		// TODO: pull out $.Widget's handling for the disabled option into
		// $.Widget.prototype._setOptionDisabled so it's easy to proxy and can
		// be overridden by individual plugins
		this._setOption( "disabled", options.disabled );
	},

	_determineButtonType: function() {

		if ( this.element.is(":checkbox") ) {
			this.type = "checkbox";
		} else {
			if ( this.element.is(":radio") ) {
				this.type = "radio";
			} else {
				if (this.element.is("input") ) {
					this.type = "input";
				} else {
					this.type = "button";
				}
			}
		}

		if ( this.type === "checkbox" || this.type === "radio" ) {
			// we don't search against the document in case the element
			// is disconnected from the DOM
			this.buttonElement = this.element.parents().last()
				.find( "[for=" + this.element.attr("id") + "]" );
			this.element.addClass('ui-helper-hidden-accessible');

			var checked = this.element.is( ":checked" );
			if ( checked ) {
				this.buttonElement.addClass( "ui-state-active" );
			}
			this.buttonElement.attr( "aria-pressed", checked );
		} else {
			this.buttonElement = this.element;
		}
	},

	widget: function() {
		return this.buttonElement;
	},

	destroy: function() {
		this.buttonElement
			.removeClass( baseClasses + " ui-helper-hidden-accessible " + otherClasses )
			.removeAttr( "role" )
			.removeAttr( "aria-pressed" )
			.html( this.buttonElement.find(".ui-button-text").html() );

		if ( !this.hasTitle ) {
			this.buttonElement.removeAttr( "title" );
		}

		$.Widget.prototype.destroy.call( this );
	},

	_setOption: function( key, value ) {
		$.Widget.prototype._setOption.apply( this, arguments );
		this._resetButton();
	},

	refresh: function() {
		if ( this.type === "radio" ) {
			radioGroup( this.element[0] ).each(function() {
				if ( $( this ).is( ":checked" ) ) {
					$( this ).button( "widget" )
						.addClass( "ui-state-active" )
						.attr( "aria-pressed", true );
				} else {
					$( this ).button( "widget" )
						.removeClass( "ui-state-active" )
						.attr( "aria-pressed", false );
				}
			});
		} else if ( this.type === "checkbox" ) {
			if ( this.element.is( ":checked" ) ) {
				this.buttonElement
					.addClass( "ui-state-active" )
					.attr( "aria-pressed", true );
			} else {
				this.buttonElement
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", false );
			}
		}
	},

	_resetButton: function() {
		if ( this.type === "input" ) {
			if ( this.options.label ) {
				this.element.val( this.options.label );
			}
			return;
		}
		var buttonElement = this.buttonElement,
			buttonText = $( "" )
				.addClass( "ui-button-text" )
				.html( this.options.label )
				.appendTo( buttonElement.empty() )
				.text(),
			icons = this.options.icons,
			multipleIcons = icons.primary && icons.secondary;
		if ( icons.primary || icons.secondary ) {
			buttonElement.addClass( "ui-button-text-icon" +
				( multipleIcons ? "s" : "" ) );
			if ( icons.primary ) {
				buttonElement.prepend( "" );
			}
			if ( icons.secondary ) {
				buttonElement.append( "" );
			}
			if ( !this.options.text ) {
				buttonElement
					.addClass( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" )
					.removeClass( "ui-button-text-icons ui-button-text-icon" );
				if ( !this.hasTitle ) {
					buttonElement.attr( "title", buttonText );
				}
			}
		} else {
			buttonElement.addClass( "ui-button-text-only" );
		}
	}
});

$.widget( "ui.buttonset", {
	_create: function() {
		this.element.addClass( "ui-button-set" );
		this.buttons = this.element.find( ":button, :submit, :reset, :checkbox, :radio, a, :data(button)" )
			.button()
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "ui-corner-all" )
				.filter( ":first" )
					.addClass( "ui-corner-left" )
				.end()
				.filter( ":last" )
					.addClass( "ui-corner-right" )
				.end()
			.end();
	},

	_setOption: function( key, value ) {
		if ( key === "disabled" ) {
			this.buttons.button( "option", key, value );
		}

		$.Widget.prototype._setOption.apply( this, arguments );
	},

	destroy: function() {
		this.element.removeClass( "ui-button-set" );
		this.buttons
			.button( "destroy" )
			.removeClass( "ui-corner-left ui-corner-right" );

		$.Widget.prototype.destroy.call( this );
	}
});

}( jQuery ) );
<|endoftext|>