#### Limitless - Form Plugins

##### Textarea autosize

Extension autosize.min.js

###### Overview

Autosize is a small, stand-alone script to automatically adjust textarea height to fit text. Use CSS to specify a `min-height` and `max-height` for the textarea element. Once the height exceeds the `max-height`, autosize will re-enable the vertical scrollbar.
The rows attribute can also be used to specify a minimum height. The rows attribute has a default value of 2, so to make the textarea smaller than that you'll need to set the value to 1. Example: `<textarea rows='1'></textarea>`.

###### Usage

The autosize function accepts a single textarea element, or an array or array-like object (such as a NodeList or jQuery collection) of textarea elements:

    // From a NodeList
    autosize(document.querySelectorAll('textarea'));

    // from a single Node
    autosize(document.querySelector('textarea'));

    // from a jQuery collection
    autosize($('textarea'));

###### Life-cycle events

Event | Description
--- | ---
`autosize:update` | Once you've assigned autosize to an element, you can manually trigger the resize event by using the 'autosize:update' event. Autosize has no way of knowing when a script has changed the value of a textarea element, or when the textarea element styles have changed, so this event would be used instruct autosize to resize the textarea
    // 'Update' event
    var ta = document.querySelector('textarea');

    autosize(ta);

    ta.value = "Some new value";

    // Dispatch a 'autosize:update' event to trigger a resize:
    var evt = document.createEvent('Event');
    evt.initEvent('autosize:update', true, false);
    ta.dispatchEvent(evt);
`autosize:autosize:destroy` |
    // 'Destroy' event
    var ta = document.querySelector('textarea');

    // assign autosize to ta
    autosize(ta);

    // remove autosize from ta
    var evt = document.createEvent('Event');
    evt.initEvent('autosize:destroy', true, false);
    ta.dispatchEvent(evt);
`autosize:resized` | This event is fired every time autosize adjusts the textarea height.
    // 'Resized' event
    var ta = document.querySelector('textarea');

    ta.addEventListener('autosize:resized', function(){
        console.log('textarea height updated');
    });
If you are using jQuery, you can use the on/off methods to listen to this event:
    // 'Resized' event
    $('textarea').each(function(){
        autosize(this);
    }).on('autosize:resized', function(){
        console.log('textarea height updated');
    });

###### Methods

These methods are provided as an alternative to using the life-cycle events

Method | Description
--- | ---
`autosize.update(elements)` | For manually recalculating the height for a textarea element, array, or array-like object
    // 'Update' method
    var ta = document.querySelector('textarea');

    autosize(ta);

    ta.value = "Some new value";

    autosize.update(ta);
`autosize.destroy(elements)` | Removes autosize and reverts it's changes from a textarea element, array, or array-like object
    // 'Destroy' method
    autosize.destroy(document.querySelectorAll('textarea'));

###### Plugin info

Property | Description
--- | ---
File name | autosize.min.js
Location | global_assets/js/plugins/forms/inputs/
Links | Official plugin website Github project page

##### Dual listbox

Extension duallistbox.min.js

###### Overview

Bootstrap Dual Listbox is a responsive dual listbox widget optimized for Twitter Bootstrap. It works on all modern browsers and on touch devices. The dual listbox is created from a select multiple by calling `.bootstrapDualListbox(settings);` on a selector. The selector can be any element, not just selects. When the method is called on a selector other than a select, then all select childrens are converted into dual list boxes.

###### Usage

First you need to load jQuery library as Dual listbox plugin is jQuery dependent. Then add a path to the plugin file:

    <!-- Load plugin -->
    <script src="../../../../global_assets/js/plugins/forms/inputs/duallistbox/duallistbox.min.js"></script>

Then initialize via JavaScript:

    // Multiple selection
    $('.listbox-no-selection').bootstrapDualListbox({
        preserveSelectionOnMove: 'moved',
        moveOnSelect: false
    });

###### Options

When calling `$("#element").bootstrapDualListbox()` you can pass a parameters object with zero or more of the following:

Option | Default | Description
--- | --- | ---
`bootstrap2Compatible` | false | Set this to `true` if you want graphic compatibility with Bootstrap 2
`filterTextClear` | 'show all' | The text for the "Show All" button
`filterPlaceHolder` | 'Filter' | The placeholder for the `input` element for filtering elements
`moveSelectedLabel` | 'Move selected' | The label for the "Move Selected" button
`moveAllLabel` | 'Move all' | The label for the "Move All" button
`removeSelectedLabel` | 'Remove selected' | The label for the "Remove Selected" button
`removeAllLabel` | 'Remove all' | The label for the "Remove All" button
`moveOnSelect` | true | Determines whether to move options upon selection. This option is forced to `true` on the Android browser
`preserveSelectionOnMove` | false | Can be `'all'` (for selecting both moved elements and the already selected ones in the target list) or `'moved'` (for selecting moved elements only)
`selectedListLabel` | false | Can be a string specifying the name of the selected list
`nonSelectedListLabel` | false | Can be a string specifying the name of the non selected list
`helperSelectNamePostfix` | '_helper' | The added selects will have the same name as the original one, concatenated with this string and 1 (for the non selected list, e.g. element_helper1) or 2 (for the selected list, e.g. element_helper2)
`selectorMinimalHeight` | 100 | Represents the minimal height of the generated dual listbox
`showFilterInputs` | true | Whether to show filter inputs
`nonSelectedFilter` | '' | Initializes the dual listbox with a filter for the non selected elements. This is applied only if `showFilterInputs` is set to `true`
`selectedFilter` | '' | Initializes the dual listbox with a filter for the selected elements. This is applied only if `showFilterInputs` is set to `true`
`infoText` | 'Showing all {0}' | Determines which string format to use when all options are visible. Set this to `false` to hide this information. Remember to insert the `{0}` placeholder.
`infoTextFiltered` | '<span class="badge badge-warning">Filtered</span> {0} from {1}' | Determines which element format to use when some element is filtered. Remember to insert the `{0}` and `{1}` placeholders
`infoTextEmpty` | 'Empty list' | Determines the string to use when there are no options in the list
`filterOnValues` | false | Set this to `true` to filter the options according to their values and not their HTML contents

###### Methods

You can modify the behavior and aspect of the dual listbox by calling its methods, all of which accept a `value` and a `refresh` option. The `value` determines the new parameter value, while `refresh` (optional, defaults to `false`) tells whether to update the plugin UI or not.

Note: when making multiple chained calls to the plugin, set `refresh` to `true` to the last call only, in order to make a unique UI change; alternatively, you can also call the `refresh` method as your last one.

To call methods on the dual listbox instance, use the following syntax:

    // Syntax
    $(selector).bootstrapDualListbox(methodName, parameter);

Here are the available methods:

Method | Description
--- | ---
`refresh()` | Update the plugin element UI
`destroy()` | Restore the original `select` element and delete the plugin element
`getContainer()` | Get the container element
`setBootstrap2Compatible(value, refresh)` | Change the `bootstrap2Compatible` parameter
`setFilterTextClear(value, refresh)` | Change the `filterTextClear` parameter
`setFilterPlaceHolder(value, refresh)` | Change the `filterPlaceHolder` parameter
`setMoveSelectedLabel(value, refresh)` | Change the `moveSelectedLabel` parameter
`setMoveAllLabel(value, refresh)` | Change the `moveAllLabel` parameter
`setRemoveSelectedLabel(value, refresh)` | Change the `removeSelectedLabel` parameter
`setRemoveAllLabel(value, refresh)` | Change the `removeAllLabel` parameter
`setMoveOnSelect(value, refresh)` | Change the `moveOnSelect` parameter
`setPreserveSelectionOnMove(value, refresh)` | Change the `preserveSelectionOnMove` parameter
`setSelectedListLabel(value, refresh)` | Change the `selectedListLabel` parameter
`setNonSelectedListLabel(value, refresh)` | Change the `nonSelectedListLabel` parameter
`setHelperSelectNamePostfix(value, refresh)` | Change the `helperSelectNamePostfix` parameter
`setSelectOrMinimalHeight(value, refresh)` | Change the `selectOrMinimalHeight` parameter
`setShowFilterInputs(value, refresh)` | Change the `showFilterInputs` parameter
`setNonSelectedFilter(value, refresh)` | Change the `nonSelectedFilter` parameter
`setSelectedFilter(value, refresh)` | Change the `selectedFilter` parameter
`setInfoText(value, refresh)` | Change the `infoText` parameter
`setInfoTextFiltered(value, refresh)` | Change the `infoTextFiltered` parameter
`setInfoTextEmpty(value, refresh)` | Change the `infoTextEmpty` parameter
`setFilterOnValues(value, refresh)` | Change the `filterOnValues` parameter

###### Plugin info

Property | Description
--- | ---
File name | duallistbox.min.js
Location | global_assets/js/plugins/forms/inputs/duallistbox/
Links | Official plugin website Github project page

##### Input formatter

Extension formatter.min.js

###### Overview

Sometimes it is useful to format user input as they type. Existing libraries lacked proper functionality / flexibility. Formatter was built from the ground up with no dependencies. There is however a jquery wrapper version for quick use.

###### Usage

First you need to load jQuery library as Input formatter plugin is jQuery dependent. Then add a path to the plugin file:

    <!-- Load plugin -->
    <script src="../../../../global_assets/js/plugins/forms/inputs/formatter.min.js"></script>

Then initialize via JavaScript:

    // Initialize
    $('#credit-input').formatter({
    	'pattern': '{{999}}-{{999}}-{{999}}-{{9999}}',
    	'persistent': true
    });

###### Options

Option | Value | Description
--- | --- | ---
`pattern` | '' | Required. String representing the pattern of your formatted input. User input areas begin with `{{` and end with `}}`. For example, a phone number may be represented: `({{999}}) {{999}}-{{999}}`. You can specify numbers, letters, or numbers and letters: 9: [0-9] a: [A-Za-z] *: [A-Za-z0-9]
`persistent` | false | Boolean representing if the formatted characters are always visible (persistent), or if they appear as you type
`patterns` | 'Filter' | The placeholder for the `input` element for filtering elements
`moveSelectedLabel` | '' | Optional, replaces `pattern`. Array representing a priority ordered set of patterns that may apply dynamically based on the current input value. Each value in the array is an object, whose key is a regular expression string and value is a pattern (see above). The regular expression is tested against the unformatted input value. You may use the special key `'*'` to catch all input values:
    // Syntax
    [
    	{ '^\d{5}$': 'zip: {{99999}}' },
    	{ '^.{6,8}$: 'postal code: {{********}}' },
    	{ '*': 'unknown: {{**********}}' }
    ]

###### Methods

Method | Description
--- | ---
Class methods
`addInptType(char, regexp)` | Add regular expressions for different input types.
    // Class methods
    $.fn.formatter.addInptType('L', /[A-Z]/);
Instance methods
`resetPattern(pattern)` | Fairly self explanatory here :) reset the pattern on an existing Formatter instance. Assuming you already initiated formatter on `#selector`
    // Instance methods
    $('#selector').formatter().resetPattern();

###### Plugin info

Property | Description
--- | ---
File name | formatter.min.js
Location | global_assets/js/plugins/forms/inputs/
Links | Official plugin website Github project page

##### Bootstrap maxlength

Extension maxlength.min.js

###### Overview

This plugin integrates by default with Twitter bootstrap using badges to display the maximum length of the field where the user is inserting text. This plugin uses the HTML5 attribute `maxlength` to work. The indicator badge shows up on focusing on the element, and disappears when the focus is lost.

###### Usage

First you need to load jQuery library as Bootstrap maxlength plugin is jQuery dependent. Then add a path to the plugin file:

    <!-- Load plugin -->
    <script src="../../../../global_assets/js/plugins/forms/inputs/maxlength.min.js"></script>

Then initialize via JavaScript:

    // Initialize
    $('input[maxlength]').maxlength({
    	// options
    });

###### Options

Option | Default | Description
--- | --- | ---
`alwaysShow` | false | If `true` the threshold will be ignored and the remaining length indication will be always showing up while typing or on focus on the input
`threshold` | 10 | This is a number indicating how many chars are left to start displaying the indications
`warningClass` | badge badge-success | It's the class of the element with the indicator. By default is the bootstrap `badge badge-success` but can be changed to anything you'd like
`limitReachedClass` | badge badge-danger | It's the class the element gets when the limit is reached
`separator` | '/' | Represents the separator between the number of typed chars and total number of available chars
`preText` | '' | String of text that can be outputted in front of the indicator
`postText` | '' | String outputted after the indicator
`showMaxLength` | true | If `false`, will display just the number of typed characters, e.g. will not display the max length
`showCharsTyped` | true | If `false`, will display just the remaining length, e.g. will display remaining lenght instead of number of typed characters
`placement` | 'bottom' | String, define where to output the counter. Possible values are: bottom, left, top, right, bottom-right, top-right, top-left, bottom-left and centered-right
`appendToParent` | '' | Appends the maxlength indicator badge to the parent of the input rather than to the body
`message` | '' | An alternative way to provide the message text, i.e. 'You have typed %charsTyped% chars, %charsRemaining% of %charsTotal% remaining'. %charsTyped%, %charsRemaining% and %charsTotal% will be replaced by the actual values. This overrides the options `separator`, `preText`, `postText` and `showMaxLength`. Alternatively you may supply a function that the current text and max length and returns the string to be displayed
`utf8` | false | If `true` the input will count using utf8 bytesize/encoding. For example: the `'£'` character is counted as two characters
`twoCharLinebreak` | '' | Count linebreak as 2 characters to match IE/Chrome textarea validation
`customMaxAttribute` | '' | Allows a custom attribute to display indicator without triggering native maxlength behaviour. Ignored if value greater than a native maxlength attribute. `'overmax'` class gets added when exceeded to allow user to implement form validation
`placement` | this | String, object, or function, to define where to output the counter. Possible `string` values are: bottom (default option), left, top, right, bottom-right, top-right, top-left, bottom-left and centered-right. Custom placements can be passed as an `object`, with keys top, right, bottom, left, and position. These are passed to `$.fn.css` A custom `function` may also be passed. This method is invoked with the `{$element}` Current Input, the `{$element}` MaxLength Indicator, and the Current Input's Position {bottom height left right top width}

###### Events

Event | Description
--- | ---
`maxlength.reposition` | On an input element triggers re-placing of its indicator. Useful if textareas are resized by an external trigger
`maxlength.shown` | Triggered when the indicator is displayed
`maxlength.hidden` | Triggered when the indicator is removed from view

###### Plugin info

Property | Description
--- | ---
File name | maxlength.min.js
Location | global_assets/js/plugins/forms/inputs/
Links | Official plugin website Github project page

##### Passy

Extension passy.js

###### Overview

You cant emphasize the importance of good passwords. Passy plugin was created to make it easier for developers to give good feedback on a password. Passy is a jQuery plugin to rate and generate passwords.

###### Usage

First you need to load jQuery library as Passy plugin is jQuery dependent. Then add a path to the plugin file:

    <!-- Load plugin -->
    <script src="../../../../global_assets/js/plugins/forms/inputs/passy.js"></script>

Then initialize via JavaScript:

    // Initialization example
    $('input').passy(function( strength, valid ) {

    	// Set color based on validness and strength
    	if(valid) {
    		if( strength < $.passy.strength.HIGH) {
    			color = 'orange';
    		} else {
    			color = 'green';
    		}
    	} else {
    		color = 'red';
    	}

    	$(this).css('background-color', color);
    });

###### Configuration

Before calling .passy(), you can alter these settings:

    // Requirements a inserted password should meet
    $.passy.requirements = {

    	// Character types a password should contain
    	characters: [
    		$.passy.character.DIGIT,
    		$.passy.character.LOWERCASE,
    		$.passy.character.UPPERCASE,
    		$.passy.character.PUNCTUATION
    	],

    	// A minimum and maximum length
    	length: {
    		min: 8,
    		max: Infinity
    	}
    };

    // Thresholds are numeric values representing
    // the estimated amount of days for a single computer
    // to brute force the password, assuming it processes
    // about 1,000,000 passwords per second

    $.passy.threshold = {
    	medium: 365,
    	high: Math.pow( 365, 2 ),
    	extreme: Math.pow( 365, 5 )
    };

###### Methods

Generate a password of a specific length:

    // 'Generate method'
    $('input').passy('generate', 16);

Check if a field’s content is valid:

    // 'Valid' method
    if (
    	$('input').passy('valid')
    )
    { ... }

###### Plugin info

Property | Description
--- | ---
File name | passy.js
Location | global_assets/js/plugins/forms/inputs/
Links | Official plugin website Github project page

##### Touchspin spinners

Extension touchspin.min.js

###### Overview

A mobile and touch friendly input spinner component for Bootstrap 3. It supports the mousewheel and the up/down keys.

###### Usage

First you need to load jQuery library as Touchspin plugin is jQuery dependent. Then add a path to the plugin file:

    <!-- Load plugin -->
    <script src="../../../../global_assets/js/plugins/forms/inputs/touchspin.min.js"></script>

Create element:

    <!-- Touchspin element -->
    <input id="demo1" type="text" value="55" name="demo1">

Then initialize via JavaScript:

    // Initialization example
    $("input[name='demo1']").TouchSpin({
        min: 0,
        max: 100,
        step: 0.1,
        decimals: 2,
        boostat: 5,
        maxboostedstep: 10,
        postfix: '%'
    });

###### Touchspin options

Option | Default | Description
--- | --- | ---
`initval` | "" | Applied when no explicit value is set on the input with the `value` attribute. Empty string means that the value remains empty on initialization.
`min` | 0 | Minimum value.
`max` | 100 | Maximum value.
`step` | 1 | Incremental/decremental step on up/down change.
`forcestepdivisibility` | 'round' | How to force the value to be divisible by step value: `'none'` | `'round'` | `'floor'` | `'ceil'`
`decimals` | 0 | Number of decimal points.
`stepinterval` | 100 | Refresh rate of the spinner in milliseconds.
`stepintervaldelay` | 500 | Time in milliseconds before the spinner starts to spin.
`verticalbuttons` | false | Enables the traditional up/down buttons.
`verticalupclass` | 'glyphicon glyphicon-chevron-up' | Class of the up button with vertical buttons mode enabled.
`verticaldownclass` | 'glyphicon glyphicon-chevron-down' | Class of the down button with vertical buttons mode enabled.
`prefix` | "" | Text before the input.
`postfix` | "" | Text after the input.
`prefix_extraclass` | "" | Extra class(es) for prefix.
`postfix_extraclass` | "" | Extra class(es) for postfix.
`booster` | true | If enabled, the the spinner is continually becoming faster as holding the button.
`boostat` | 10 | Boost at every nth step.
`maxboostedstep` | false | Maximum step when boosted.
`mousewheel` | true | Enables the mouse wheel to change the value of the input.
`buttondown_class` | 'btn btn-default' | Class(es) of down button.
`buttonup_class` | 'btn btn-default' | Class(es) of up button.

###### Touchspin events

Triggered events

The following events are triggered on the original input by the plugin and can be listened on.

Event | Description
--- | ---
`change` | Triggered when the value is changed with one of the buttons (but not triggered when the spinner hits the limit set by `settings.min` or `settings.max`.
`touchspin.on.startspin` | Triggered when the spinner starts spinning upwards or downwards.
`touchspin.on.startupspin` | Triggered when the spinner starts spinning upwards.
`touchspin.on.startdownspin` | Triggered when the spinner starts spinning downwards.
`touchspin.on.stopspin` | Triggered when the spinner stops spinning.
`touchspin.on.stopupspin` | Triggered when the spinner stops upspinning.
`touchspin.on.stopdownspin` | Triggered when the spinner stops downspinning.
`touchspin.on.min` | Triggered when the spinner hits the limit set by `settings.min`.
`touchspin.on.max` | Triggered when the spinner hits the limit set by `settings.max`.

Callable events

The following events can be triggered on the original input. Example usage:

    // 'upOnce' event
    $("input").trigger("touchspin.uponce");

    // 'updateSettings' event
    $("input").trigger("touchspin.updatesettings", {
    	max: 1000
    });

Event | Description
--- | ---
`change` | Triggered when the value is changed with one of the buttons (but not triggered when the spinner hits the limit set by `settings.min` or `settings.max`.
`touchspin.on.startspin` | Triggered when the spinner starts spinning upwards or downwards.
`touchspin.on.startupspin` | Triggered when the spinner starts spinning upwards.
`touchspin.on.startdownspin` | Triggered when the spinner starts spinning downwards.
`touchspin.on.stopspin` | Triggered when the spinner stops spinning.
`touchspin.on.stopupspin` | Triggered when the spinner stops upspinning.
`touchspin.on.stopdownspin` | Triggered when the spinner stops downspinning.
`touchspin.on.min` | Triggered when the spinner hits the limit set by `settings.min`.
`touchspin.on.max` | Triggered when the spinner hits the limit set by `settings.max`.

###### Plugin info

Property | Description
--- | ---
File name | touchspin.min.js
Location | global_assets/js/plugins/forms/inputs/
Links | Official plugin website Github project page

##### Twitter typeahead

Extension /forms/inputs/typeahead/

###### Overview

Typeahead is a flexible JavaScript library that provides a strong foundation for building robust typeaheads. The `typeahead.js` library consists of 2 components: the suggestion engine - Bloodhound, and the UI view - Typeahead. The suggestion engine is responsible for computing suggestions for a given query. The UI view is responsible for rendering suggestions and handling DOM interactions. Both components can be used separately, but when used together, they can provide a rich typeahead experience.

Main Typeahead features:

- Displays suggestions to end-users as they type
- Shows top suggestion as a hint (i.e. background text)
- Supports custom templates to allow for UI flexibility
- Works well with RTL languages and input method editors
- Highlights query matches within the suggestion
- Triggers custom events to encourage extensibility

###### Usage

Load library itself, Bloodhound engine is already integrated to the main file:

    <!-- Load library -->
    <script src="../../../../global_assets/js/plugins/forms/inputs/typeahead/typeahead.bundle.min.js"></script>

Create element:

    <!-- Typeahead element -->
    <div id="the-basics">
      <input class="typeahead" type="text" placeholder="States of USA">
    </div>

Then initialize via JavaScript:

    // Initialization example
    $('.typeahead').typeahead({
    	minLength: 3,
    	highlight: true
    },
    {
    	name: 'my-dataset',
    	source: mySource
    });

###### Typeahead options

Option | Default | Description
--- | --- | ---
`highlight` | false | If `true`, when suggestions are rendered, pattern matches for the current query in text nodes will be wrapped in a strong element with its class set to `{{classNames.highlight}}`
`hint` | true | If `false`, the typeahead will not show a hint
`minLength` | 1 | The minimum character length needed before suggestions start getting rendered
`classNames` | '' | For overriding the default class names used

###### Typeahead datasets

A typeahead is composed of one or more datasets. When an end-user modifies the value of a typeahead, each dataset will attempt to render suggestions for the new value.

For most use cases, one dataset should suffice. It's only in the scenario where you want rendered suggestions to be grouped based on some sort of categorical relationship that you'd need to use multiple datasets. For example, on twitter.com, the search typeahead groups results into recent searches, trends, and accounts – that would be a great use case for using multiple datasets.

Datasets can be configured using the following options:

Option | Description
--- | ---
`source` | [Required]. The backing data source for suggestions. Expected to be a function with the signature (`query`, `syncResults`, `asyncResults`). `syncResults` should be called with suggestions computed synchronously and asyncResults should be called with suggestions computed asynchronously (e.g. suggestions that come for an AJAX request). `source` can also be a Bloodhound instance
`async` | Lets the dataset know if async suggestions should be expected. If not set, this information is inferred from the signature of `source` i.e. if the `source` function expects 3 arguments, `async` will be set to `true`
`name` | The name of the dataset. This will be appended to `{{classNames.dataset}}` - to form the class name of the containing DOM element. Must only consist of underscores, dashes, letters (`a-z`), and numbers. Defaults to a random number
`limit` | The max number of suggestions to be displayed. Defaults to `5`
`display` | For a given suggestion, determines the string representation of it. This will be used when setting the value of the input control after a suggestion is selected. Can be either a key string or a function that transforms a suggestion object into a string. Defaults to stringifying the suggestion
`templates` | A hash of templates to be used when rendering the dataset. Note a precompiled template is a function that takes a JavaScript object as its first argument and returns a HTML string
`[templates] notFound` | Rendered when `0` suggestions are available for the given query. Can be either a HTML string or a precompiled template. If it's a precompiled template, the passed in context will contain `query`
`[template] pending` | Rendered when 0 synchronous suggestions are available but asynchronous suggestions are expected. Can be either a HTML string or a precompiled template. If it's a precompiled template, the passed in context will contain `query`
`[template] header` | Rendered at the top of the dataset when suggestions are present. Can be either a HTML string or a precompiled template. If it's a precompiled template, the passed in context will contain `query` and `suggestions`
`[template] footer` | Rendered at the bottom of the dataset when suggestions are present. Can be either a HTML string or a precompiled template. If it's a precompiled template, the passed in context will contain `query` and `suggestions`
`[template] suggestion` | Used to render a single suggestion. If set, this has to be a precompiled template. The associated suggestion object will serve as the context. Defaults to the value of `display` wrapped in a div tag i.e. `<div>{{value}}</div>`

###### Custom events

The following events get triggered on the input element during the life-cycle of a typeahead. Note: Every event does not supply the same arguments. See the event descriptions below for details on each event's argument list.

Event | Description
--- | ---
`typeahead:active` | Fired when the typeahead moves to active state
`typeahead:idle` | Fired when the typeahead moves to idle state
`typeahead:open` | Fired when the results container is opened
`typeahead:close` | Fired when the results container is closed
`typeahead:change` | Normalized version of the native `change` event. Fired when input loses focus and the value has changed since it originally received focus
`typeahead:render` | Fired when suggestions are rendered for a dataset. The event handler will be invoked with 4 arguments: the jQuery event object, the suggestions that were rendered, a flag indicating whether the suggestions were fetched asynchronously, and the name of the dataset the rendering occurred in
`typeahead:select` | Fired when a suggestion is selected. The event handler will be invoked with 2 arguments: the jQuery event object and the suggestion object that was selected
`typeahead:autocomplete` | Fired when a autocompletion occurs. The event handler will be invoked with 2 arguments: the jQuery event object and the suggestion object that was used for autocompletion
`typeahead:cursorchange` | Fired when the results container cursor moves. The event handler will be invoked with 2 arguments: the jQuery event object and the suggestion object that was moved to
`typeahead:asyncrequest` | Fired when an async request for suggestions is sent. The event handler will be invoked with 3 arguments: the jQuery event object, the current query, and the name of the dataset the async request belongs to
`typeahead:asynccancel` | Fired when an async request is cancelled. The event handler will be invoked with 3 arguments: the jQuery event object, the current query, and the name of the dataset the async request belonged to
`typeahead:asyncreceive` | Fired when an async request completes. The event handler will be invoked with 3 arguments: the jQuery event object, the current query, and the name of the dataset the async request belongs to

Example usage:

    // Events usage
    $('.typeahead').bind('typeahead:select', function(ev, suggestion) {
    	console.log('Selection: ' + suggestion);
    });

###### Class Names

Class | Defaults | Description
--- | --- | ---
`input` | .tt-input | Added to input that's initialized into a typeahead
`hint` | .tt-hint | Added to hint input
`menu` | .tt-menu | Added to menu element
`dataset` | tt-dataset | Added to dataset elements
`suggestion` | tt-suggestion | Added to suggestion elements
`empty` | .tt-empty | Added to menu element when it contains no content
`open` | .tt-open | Added to menu element when it is opened
`cursor` | .tt-cursor | Added to suggestion element when menu cursor moves to said suggestion
`highlight` | .tt-highlight | Added to the element that wraps highlighted text

To override any of these defaults, you can use the `classNames` option:

    // Override class names
    $('.typeahead').typeahead({
    	classNames: {
    		input: 'Typeahead-input',
    		hint: 'Typeahead-hint',
    		selectable: 'Typeahead-selectable'
    	}
    });

###### Plugin info

Property | Description
--- | ---
File name | typeahead.bundle.min.js, handlebars.js
Location | global_assets/js/plugins/forms/inputs/typeahead/
Links | Official plugin website Typeahead documentation Bloodhound documentation Github project page

##### Form validation

Validation /forms/validation/

###### Overview

This jQuery plugin makes simple clientside form validation easy, whilst still offering plenty of customization options. It makes a good choice if you’re building something new from scratch, but also when you’re trying to integrate something into an existing application with lots of existing markup.

The plugin comes bundled with a useful set of validation methods, including URL and email validation, while providing an API to write your own methods. All bundled methods come with default error messages in english and translations into 37 other languages

###### Usage

Include the following lines of code in the `<head>` section of your HTML:

    <!-- Load jQuery -->
    <script src="../../../../global_assets/js/main/jquery.min.js"></script>

    <!-- Load plugin -->
    <script src="../../../../global_assets/js/plugins/forms/validation/validate.min.js"></script>

Select a form to validate and call the validate method:

    <!-- Create form -->
    <form class="validate" id="commentForm" method="get" action="">
    	<fieldset>
    		<legend>Please provide your name, email address (won't be published) and a comment</legend>
    		<p>
    			<label for="cname">Name (required, at least 2 characters)</label>
    			<input id="cname" name="name" minlength="2" type="text" required="required'">
    		</p>
    	</fieldset>
    </form>

Finally call the plugin via JavaScript:

    // Basic initialization
    $("#commentForm").validate({
    	// options
    });

###### Validate options

Name | Default | Description
--- | --- | ---
`debug` | false | Enables debug mode. If true, the form is not submitted and certain errors are displayed on the console (will check if a `window.console` property exists). Try to enable when a form is just submitted instead of validation stopping the submit
`submitHandler` | native form submit | Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated
`invalidHandler` | {} | Callback for custom code when an invalid form is submitted. Called with an event object as the first argument, and the validator as the second
`ignore` | ":hidden" | Elements to ignore when validating, simply filtering them out. jQuery's not-method is used, therefore everything that is accepted by `not()` can be passed as this option. Inputs of type submit and reset are always ignored, so are disabled elements
`rules` | read from markup (classes, attributes, data) | Key/value pairs defining custom rules. Key is the name of an element (or a group of checkboxes/radio buttons), value is an `object` consisting of rule/parameter pairs or a plain `String`. Can be combined with class/attribute/data rules. Each rule can be specified as having a depends-property to apply the rule only in certain conditions
`messages` | Default message for the method used | Key/value pairs defining custom messages. Key is the name of an element, value the message to display for that element. Instead of a plain message, another map with specific messages for each rule can be used. Overrides the title attribute of an element or the default message for the method (in that order). Each message can be a `String` or a `Callback`. The `callback` is called in the scope of the validator, with the rule's parameters as the first argument and the element as the second, and must return a `String` to display as the message
`groups` | [] | Specify grouping of error messages. A group consists of an arbitrary group name as the key and a space separated list of element names as the value. Use `errorPlacement` to control where the group message is placed
`onsubmit` | true | Validate the form on submit. Set to `false` to use only other events for validation. Set to a `Function` to decide for yourself when to run validation. A boolean `true` is not a valid value
`onfocusout` | {} | Validate elements (except checkboxes/radio buttons) on `blur`. If nothing is entered, all rules are skipped, except when the field was already marked as invalid. Set to a `Function` to decide for yourself when to run validation. A boolean `true` is not a valid value
`onkeyup` | {} | Validate elements on `keyup`. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Set to `false` to disable. Set to a `Function` to decide for yourself when to run validation. A boolean `true` is not a valid value
`onclick` | {} | Validate checkboxes and radio buttons on `click`. Set to `false` to disable. Set to a `Function` to decide for yourself when to run validation. A boolean `true` is not a valid value
`focusInvalid` | true | Focus the last active or first invalid element on submit via `validator.focusInvalid()`. The last active element is the one that had focus when the form was submitted, avoiding stealing its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off
`focusCleanup` | false | If enabled, removes the `errorClass` from the invalid elements and hides all error messages whenever the element is focused. Avoid combination with `focusInvalid`
`errorClass` | 'error' | Use this class to create error labels, to look for existing error labels and to add it to invalid elements
`validClass` | 'valid' | This class is added to an element after it was validated and considered valid
`errorElement` | 'label' | Use this element type to create error messages and to look for existing error messages. The default, `"label"`, has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, regardless of element type)
`wrapper` | 'window' | Wrap error labels with the specified element. Useful in combination with `errorLabelContainer` to create a list of error messages
`errorLabelContainer` | - | Hide and show this container when validating
`errorContainer` | - | Hide and show this container when validating
`showErrors` | {} | A custom message display handler. Gets the map of errors as the first argument and an array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling `this.defaultShowErrors()`
`errorPlacement` | After the invalid element | Customize placement of created error labels. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object
`success` | - | If specified, the error label is displayed to show a valid element. If a `String` is given, it is added as a class to the label. If a `Function` is given, it is called with the label (as a jQuery object) and the validated input (as a DOM element). The label can be used to add a text like `"ok!"`
`highlight` | Adds errorClass to the element | How to highlight invalid fields. Override to decide which fields and how to highlight
`unhighlight` | Removes the errorClass | Called to revert changes made by option `highlight`, same arguments as highlight
`ignoreTitle` | false | Set to skip reading messages from the `title` attribute, helps to avoid issues with Google Toolbar; default is `false` for compability, the message-from-title is likely to be completely removed in a future release

###### Plugin methods

This library adds three jQuery plugin methods, the main entry point being the `validate` method:

Method | Description
--- | ---
`validate()` | Validates the selected form
`valid()` | Checks whether the selected form or selected elements are valid
`rules()` | Read, add and remove rules for an element

###### Custom selectors

This library also extends jQuery with three custom selectors:

Method | Description
--- | ---
`:blank` | Selects all elements with a blank value
`:filled` | Selects all elements with a filled value
`:unchecked` | Selects all elements that are unchecked

###### Validator

The validate method returns a Validator object that has a few public methods that you can use to trigger validation programmatically or change the contents of the form. The validator object has more methods, but only those documented here are intended for usage.

Method | Description
--- | ---
`Validator.form()` | Validates the form
`Validator.element()` | Validates a single element
`Validator.resetForm()` | Resets the controlled form
`Validator.showErrors()` | Show the specified messages
`Validator.numberOfInvalids()` | Returns the number of invalid fields
`jQuery.validator.addMethod()` | Add a custom validation method
`jQuery.validator.format()` | Replaces {n} placeholders with arguments
`jQuery.validator.setDefaults()` | Modify default settings for validation
`jQuery.validator.addClassRules()` | Add a compound class method

###### Built-in Validation methods

A set of standard validation methods is provided:

Method | Description
--- | ---
`required` | Makes the element required
`remote` | Requests a resource to check the element for validity
`minlength` | Makes the element require a given minimum length
`maxlength` | Makes the element require a given maxmimum length
`rangelength` | Makes the element require a given value range
`min` | Makes the element require a given minimum
`max` | Makes the element require a given maximum
`range` | Makes the element require a given value range
`email` | Makes the element require a valid email
`url` | Makes the element require a valid url
`date` | Makes the element require a date
`dateISO` | Makes the element require an ISO date
`number` | Makes the element require a decimal number
`digits` | Makes the element require digits only
`creditcard` | Makes the element require a credit card number
`equalTo` | Requires the element to be the same as another one

Some more methods are provided as add-ons, and are currently included in additional-methods.js in the download package. Not all of them are documented here:

Method | Description
--- | ---
`accept` | Makes a file upload accept only specified mime-types
`extension` | Makes the element require a certain file extension
`phoneUS` | Validate for valid US phone number
`require_from_group` | Ensures a given number of fields in a group are complete

###### Plugin info

Property | Description
--- | ---
File name | validate.min.js
Location | global_assets/js/plugins/forms/validation/
Links | Official plugin website Full documentation Demonstration Github project page

##### Bootstrap tagsinput

Tags tagsinput.min.js

###### Overview

Bootstrap Tags Input is a jQuery plugin providing a Twitter Bootstrap user interface for managing tags. Integrates with Twitter Bootstraps' 2.3.2 typeahead, or use custom typeahead when using Bootstrap 3.

Main features:

- Objects as tags
- True multi value
- Typeahead
- Designed for Bootstrap 2.3.2 and 3

###### Usage

The plugin is jQuery and Bootstrap dependent. Include the following lines of code in the `<head>` section of your HTML:

    <!-- Load jQuery -->
    <script src="../../../../global_assets/js/main/jquery.min.js"></script>

    <!-- Load Bootstrap -->
    <script src="../../../../global_assets/js/main/bootstrap.min.js"></script>

    <!-- Load plugin -->
    <script src="../../../../global_assets/js/plugins/forms/tags/tagsinput.min.js"></script>

Create an HTML element with `id`, `class`, or `name` attributes:

    <!-- Create element -->
    <input type="text" value="Amsterdam, Washington, Sydney, Beijing" class="tags-input">

Finally call the plugin via JavaScript:

    // Basic initialization
    $('.tags-input').tagsinput({
    	// options
    });

###### Plugin options

Name | Description
--- | ---
`tagClass` | Classname for the tags, or a function returning a classname
`itemValue` | When adding objects as tags, `itemValue` must be set to the name of the property containing the item's value, or a function returning an item's value
`itemText` | When adding objects as tags, you can set `itemText` to the name of the property of item to use for a its tag's text. You may also provide a function which returns an item's value. When this options is not set, the value of `itemValue` will be used
`confirmKeys` | Array of keycodes which will add a tag when typing in the input. (default: `[13, 188]`, which are `ENTER` and comma)
`maxTags` | When set, no more than the given number of tags are allowed to add (default: `undefined`). When `maxTags` is reached, a class `'bootstrap-tagsinput-max'` is placed on the tagsinput element
`maxChars` | Defines the maximum length of a single tag. (default: `undefined`)
`trimValue` | When `true`, automatically removes all whitespace around tags. (default: `false`)
`allowDuplicates` | When `true`, the same tag can be added multiple times. (default: `false`)
`freeInput` | Allow creating tags which are not returned by typeahead's source (default: `true`). This is only possible when using string as tags. When itemValue option is set, this option will be ignored
`typeahead` | Object containing typeahead specific options
`[typeahead] source` | An array (or function returning a promise or array), which will be used as source for a typeahead
`onTagExists` | Function invoked when trying to add an item which allready exists. By default, the existing tag hides and fades in

###### Plugin methods

Example usage:

    // Method usage example
    $('input').tagsinput('add', 'some tag');

Available methods

Method | Description
--- | ---
`add` | Adds a tag
`remove` | Removes a tag
`removeAll` | Removes all tags
`focus` | Sets focus in the tagsinput
`input` | Returns the tagsinput's internal `<input />`, which is used for adding tags. You could use this to add your own typeahead behaviour for example
`refresh` | Refreshes the tags input UI. This might be usefull when you're adding objects as tags. When an object's text changes, you'll have to refresh to update the matching tag's text
`destroy` | Removes tagsinput behaviour

###### Plugin events

Example usage:

    // Event usage example
    $('input').on('beforeItemAdd', function(event) {
    	// event.item: contains the item
    	// event.cancel: set to true to prevent the item getting added
    });

Available events

Method | Description
--- | ---
`beforeItemAdd` | Triggered just before an item gets added
`itemAdded` | Triggered just after an item got added
`beforeItemRemove` | Triggered just before an item gets removed
`itemRemoved` | Triggered just after an item got removed

###### Plugin info

Property | Description
--- | ---
File name | tagsinput.min.js
Location | global_assets/js/plugins/forms/tags/
Links | Official plugin website Github project page

##### Tokenfield

Tags tokenfield.min.js

###### Overview

Advanced tagging/tokenizing plugin for jQuery and Twitter Bootstrap with a focus on keyboard and copy-paste support. Also supports validation states, typeahead implementation, different sizes and states, form layouts, directions, copy and paste, width options and other features.

Core features:

- Copy & paste tokens with `Ctrl+C` and `Ctrl+V`
- Keyboard navigation, delete tokens with keyboard (`arrow` keys, `Shift + arrow` keys)
- Select specific tokens with `Ctrl + click` and `Shift + click`
- Twitter Typeahead and jQuery UI Autocomplete support

###### Usage

The plugin is jQuery and Bootstrap (CSS only) dependent. Include the following lines of code in the `<head>` section of your HTML:

    <!-- Load jQuery -->
    <script src="../../../../global_assets/js/main/jquery.min.js"></script>

    <!-- Load plugin -->
    <script src="../../../../global_assets/js/plugins/forms/tags/tagsinput.min.js"></script>

Create an HTML element:

    <!-- Create element -->
    <input type="text" class="form-control" id="tokenfield-typeahead" value="red,green,blue">

Finally call the plugin via JavaScript:

    // Basic initialization
    $('.tokenfield').tokenfield({
    	// options
    });

###### Plugin options

Options for individual tokenfields can alternatively be specified through the use of data attributes, as explained below:

Name | Default | Description
--- | --- | ---
`tokens` | [] | Tokens (or tags). Can be a string with comma-separated values, an array of strings or an array of objects
`limit` | 0 | Maximum number of tokens allowed. 0 = unlimited
`minLength` | 0 | Minimum length required for token value
`minWidth` | 60 | Minimum input field width. In pixels
`autocomplete` | {} | jQuery UI Autocomplete options
`showAutocompleteOnFocus` | false | Whether to show autocomplete suggestions menu on focus or not. Works only for jQuery UI Autocomplete, as Typeahead has no support for this kind of behavior
`typeahead` | [] | Arguments for Twitter Typeahead. The first argument should be an `options` hash (or null if you want to use the defaults). The second argument should be a `dataset`. Multiple datasets are also supported
`createTokensOnBlur` | false | Whether to turn input into tokens when tokenfield loses focus or not
`delimiter` | ',' | A character or an array of characters that will trigger token creation on keypress event. Defaults to `','` (comma). Note - this does not affect `Enter` or `Tab` keys, as they are handled in the keydown event. The first delimiter will be used as a separator when getting the list of tokens or copy-pasting tokens
`beautify` | true | Whether to insert spaces after each token when getting a comma-separated list of tokens
`inputType` | 'text' | HTML type attribute for the token input. This is useful for specifying an HTML5 input type like `'email'`, `'url'` or `'tel'` which allows mobile browsers to show a specialized virtual keyboard optimized for different types of input. This only sets the type of the visible token input, but does not touch the original input field. So you may set the original input to have `type="text"` but set this inputType option to `'email'` if you only want to take advantage of the email style keyboard on mobile, but don't want to enable HTML5 native email validation on the original hidden input

###### Plugin methods

Example usage:

    // Method usage example
    $('#myField').tokenfield('createToken', {
    	value: 'violet',
    	label: 'Violet'
    });

Available methods

Method | Description
--- | ---
`.tokenfield(options)` | Initializes an input with a tokenfield
`.tokenfield('setTokens', tokens)` | Manually set the tokenfield content (replacing the old content)
`.tokenfield('createToken', token)` | Manually create a token and append it to the input
`.tokenfield('getTokens', active)` | Get an array of tokens from the input. Set `active` to `true` to return only selected tokens
`.tokenfield('getTokensList', delimiter, beautify, active)` | Get a comma-separated list of the tokens from the input. You can use an alternative separator by supplying also a `delimiter` argument. Setting `beautify` to `false` will prevent adding a space after each token. Set `active` to `true` to return only selected tokens
`.tokenfield('disable')` | Disable tokenfield (just like a normal input field)
`.tokenfield('enable')` | Enable tokenfield (just like a normal input field)
`.tokenfield('readonly')` | Make tokenfield a readonly field (just like a normal input field)
`.tokenfield('writeable')` | Make tokenfield writeable (just like a normal input field)
`.tokenfield('destroy')` | Destroy tokenfield and restore original input

###### Plugin events

Tokenfield exposes a few events for hooking into it's functionality. Example usage:

    // Event usage example
    $('#tokenfield').on('tokenfield:createtoken', function (e) {
    	var data = e.attrs.value.split('|')
    	e.attrs.value = data[1] || data[0]
    	e.attrs.label = data[1] ? data[0] + ' (' + data[1] + ')' : data[0]
    });

Available events

Method | Description
--- | ---
`tokenfield:initialize` | Fires after Tokenfield has been initialized
`tokenfield:createtoken` | This event fires when a token is all set up to be created, but before it is inserted into the DOM and event listeners are attached. You can use this event to manipulate token value and label by changing the appropriate values of `attrs` property of the event. Calling `event.preventDefault()` or doing `return false` in the event handler will prevent the token from being created
`tokenfield:createdtoken` | This event is fired after the token has been created. Here, `attrs` property of the event is also available, but is basically read-only. You can also get a direct reference to the token DOM object via e.relatedTarget
`tokenfield:edittoken` | This event is fired just before a token is about to be edited. This allows you to manipluate the input field value before it is created. Again, to do this, manipluate the `attrs` property of the event. Here you can also access the token DOM object with `e.relatedTarget`. Calling `event.preventDefault()` or doing `return false` in the event handler will prevent the token from being edited
`tokenfield:editedtoken` | This event is fired when a token is ready for being edited. It means that the token has been replaced by an input field
`tokenfield:removetoken` | This event is fired right before a token is removed. Here you can also access the token DOM object with `e.relatedTarget`. Calling `event.preventDefault()` or doing return false in the event handler will prevent the token from being removed. You can access token label and value by checking the `attrs` property of the event. Also, `e.relatedTarget` is a reference to the token DOM object
`tokenfield:removedtoken` | This event is fired right after a token is removed from the DOM. You can access token label and value by checking the `attrs` property of the event

###### Plugin info

Property | Description
--- | ---
File name | tokenfield.min.js
Location | global_assets/js/plugins/forms/tags/
Links | Official plugin website Github project page

##### Alpaca forms

Extensions alpaca.min.js

###### Overview

Alpaca provides the easiest way to generate interactive HTML5 forms for web and mobile applications. It uses JSON Schema and simple Handlebars templates to generate great looking user interfaces on top of Twitter Bootstrap, jQuery UI, jQuery Mobile and HTML5.

Everything you need is provided out of the box. Alpaca comes pre-stocked with a large library of controls, templates, layouts and features to make rendering JSON-driven forms easy. It is designed around an extensible object-oriented pattern, allowing you to implement new controls, templates, I18N bundles and custom data persistence for your projects.

lpaca is open-source and provided to you under the Apache 2.0 license. It is supported by Cloud CMS and is in use by organizations and within projects all around the world.

###### Usage

The plugin is jQuery and Bootstrap (CSS only) dependent. Include the following lines of code in the `<head>` section of your HTML:

    <!-- dependencies (jquery, handlebars and bootstrap) -->
    <script src="../../../../global_assets/js/main/jquery.min.js"></script>
    <script src="../../../../global_assets/js/main/bootstrap.min.js"></script>

    <script src="../../../../global_assets/js/plugins/forms/inputs/alpaca/alpaca.min.js"></script>

Create an HTML element:

    <!-- Create element -->
    <div id="form1"></div>

Finally call `$.alpaca()` with your form schema and any configuration:

    // Basic initialization
    $("#form1").alpaca({
        "schema": {
            "title": "What do you think of Alpaca?",
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "title": "Name"
                },
                "ranking": {
                    "type": "string",
                    "title": "Ranking",
                    "enum": ['excellent', 'not too shabby', 'alpaca built my hotrod']
                }
            }
        }
    });

###### Alpaca documentation

Full Alpaca documentation can be found online on Official library website. It's quite big, with a lot of options, examples, events and methods. I find it useless to copy them all and paste to the Limitless documentation, nobody can represent and describe library features better than its creators. Below you can find additional links related to Alpaca library.

###### Plugin info

Property | Description
--- | ---
File name | alpaca.min.js
Location | global_assets/js/plugins/forms/inputs/alpaca/
Links | Official plugin website Full documentation Github project page