"):e.append("");g.rowFragment.appendChild(e.get(0)),g.statusClassPropName="tr",g.ariaPropName="tr",this.nodeContainerAttrName="tr",this._super(b),a(g.rootNode.ul).remove(),g.rootNode.ul=null,g.$container=h,this.$container.attr("tabindex",this.options.tabbable?"0":"-1"),this.options.aria&&g.$container.attr("role","treegrid").attr("aria-readonly",!0)},nodeRemoveChildMarkup:function(b){var c=b.node;c.visit(function(b){b.tr&&(a(b.tr).remove(),b.tr=null)})},nodeRemoveMarkup:function(b){var c=b.node;c.tr&&(a(c.tr).remove(),c.tr=null),this.nodeRemoveChildMarkup(b)},nodeRender:function(b,c,f,h,i){var j,k,l,m,n,o,p,q,r=b.tree,s=b.node,t=b.options,u=!s.parent;if(i||(b.hasCollapsedParents=s.parent&&!s.parent.expanded),u||(s.tr?this.nodeRenderTitle(b):(n=r.rowFragment.firstChild.cloneNode(!0),o=g(s),d(o),h===!0&&i?n.style.display="none":f&&b.hasCollapsedParents&&(n.style.display="none"),o.tr?e(o.tr,n):(d(!o.parent,"prev. row must have a tr, or is system root"),r.tbody.appendChild(n)),s.tr=n,s.key&&t.generateIds&&(s.tr.id=t.idPrefix+s.key),s.tr.ftnode=s,t.aria&&a(s.tr).attr("aria-labelledby","ftal_"+s.key),s.span=a("span.fancytree-node",s.tr).get(0),this.nodeRenderTitle(b),t.createNode&&t.createNode.call(r,{type:"createNode"},b))),t.renderNode&&t.renderNode.call(r,{type:"renderNode"},b),j=s.children,j&&(u||f||s.expanded))for(l=0,m=j.length;m>l;l++)q=a.extend({},b,{node:j[l]}),q.hasCollapsedParents=q.hasCollapsedParents||!s.expanded,this.nodeRender(q,c,f,h,!0);j&&!i&&(p=s.tr||null,k=r.tbody.firstChild,s.visit(function(a){if(a.tr){if(s.expanded||u||"none"===a.tr.style.display||(a.tr.style.display="none"),a.tr.previousSibling!==p){s.debug("_fixOrder: mismatch at node: "+a);var b=p?p.nextSibling:k;r.tbody.insertBefore(a.tr,b)}p=a.tr}})),u||this.nodeRenderStatus(b)},nodeRenderTitle:function(b){var c,d=b.node,e=b.options;this._super(b),e.checkbox&&null!=e.table.checkboxColumnIdx&&(c=a("span.fancytree-checkbox",d.span).detach(),a(d.tr).find("td:first").html(c)),e.renderColumns&&e.renderColumns.call(b.tree,{type:"renderColumns"},b)},nodeRenderStatus:function(b){var c,d=b.node,e=b.options;this._super(b),a(d.tr).removeClass("fancytree-node"),c=(d.getLevel()-1)*e.table.indentation,c&&a(d.span).css({marginLeft:c+"px"})},nodeSetExpanded:function(a,b){return this._super(a,b).always(function(){b=b!==!1,f(a.node,b)})},nodeSetStatus:function(b,c,d,e){if("ok"===c){var f=b.node,g=f.children?f.children[0]:null;g&&g.isStatusNode&&a(g.tr).remove()}this._super(b,c,d,e)}})}(jQuery,window,document),function(a){"use strict";a.ui.fancytree.registerExtension("themeroller",{version:"0.0.1",options:{activeClass:"ui-state-active",foccusClass:"ui-state-focus",hoverClass:"ui-state-hover",selectedClass:"ui-state-highlight"},treeInit:function(b){this._super(b);var c=b.widget.element;"TABLE"===c[0].nodeName?(c.addClass("ui-widget ui-corner-all"),c.find(">thead tr").addClass("ui-widget-header"),c.find(">tbody").addClass("ui-widget-conent")):c.addClass("ui-widget ui-widget-content ui-corner-all"),c.delegate(".fancytree-node","mouseenter mouseleave",function(b){var c=a.ui.fancytree.getNode(b.target),d="mouseenter"===b.type;c.debug("hover: "+d),a(c.span).toggleClass("ui-state-hover ui-corner-all",d)})},treeDestroy:function(a){this._super(a),a.widget.element.removeClass("ui-widget ui-widget-content ui-corner-all")},nodeRenderStatus:function(b){var c=b.node,d=a(c.span);this._super(b),d.toggleClass("ui-state-active",c.isActive()),d.toggleClass("ui-state-focus",c.hasFocus()),d.toggleClass("ui-state-highlight",c.isSelected())}})}(jQuery,window,document);
//# sourceMappingURL=jquery.fancytree-all.min.js.map
;
/*!
* jquery.fancytree.gridnav.js
*
* Support keyboard navigation for trees with embedded input controls.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* Copyright (c) 2013, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version DEVELOPMENT
* @date DEVELOPMENT
*/
;(function($, window, document, undefined) {
"use strict";
/*******************************************************************************
* Private functions and variables
*/
// Allow these navigation keys even when input controls are focused
var KC = $.ui.keyCode,
// which keys are *not* handled by embedded control, but passed to tree
// navigation handler:
NAV_KEYS = {
"text": [KC.UP, KC.DOWN],
"checkbox": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"radiobutton": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
"select-one": [KC.LEFT, KC.RIGHT],
"select-multiple": [KC.LEFT, KC.RIGHT]
};
function findNeighbourTd($target, keyCode){
var $td = $target.closest("td");
switch( keyCode ){
case KC.LEFT:
return $td.prev();
case KC.RIGHT:
return $td.next();
case KC.UP:
return $td.parent().prevAll(":visible").first().find("td").eq($td.index());
case KC.DOWN:
return $td.parent().nextAll(":visible").first().find("td").eq($td.index());
}
return null;
}
/*******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension("gridnav", {
version: "0.0.1",
// Default options for this extension.
options: {
autofocusInput: false, // Focus first embedded input if node gets activated
handleCursorKeys: true, // Allow UP/DOWN in inputs to move to prev/next node
titlesTabbable: true // Add node title to TAB chain
},
treeInit: function(ctx){
this._super(ctx);
this.$container.addClass("fancytree-ext-gridnav");
// Activate node if embedded input gets focus (due to a click)
// this.$container.on("focusin", "input", function(event){
this.$container.on("focusin", function(event){
var ctx2,
node = $.ui.fancytree.getNode(event.target);
// node.debug("INPUT focusin", event.target, event);
if( node && !node.isActive() ){
// Call node.setActive(), but also pass the event
ctx2 = ctx.tree._makeHookContext(node, event);
ctx.tree._callHook("nodeSetActive", ctx2, true);
}
});
},
nodeRender: function(ctx) {
this._super(ctx);
// Add every node title to the tab sequence
if( ctx.options.gridnav.titlesTabbable === true ){
$(ctx.node.span).find("span.fancytree-title").attr("tabindex", "0");
}
},
// nodeRenderStatus: function(ctx) {
// var opts = ctx.options.gridnav,
// node = ctx.node;
// this._super(ctx);
// // Note: Setting 'tabbable' only to the active node wouldn't help,
// // because the first row contains a tabbable input element anyway.
// if( opts.titlesTabbable === "active" ){
// if( node.isActive() ){
// $(node.span) .find("span.fancytree-title") .attr("tabindex", "0");
// }else{
// $(node.span) .find("span.fancytree-title") .removeAttr("tabindex");
// }
// }
// },
nodeSetActive: function(ctx, flag) {
var $outer,
opts = ctx.options.gridnav,
node = ctx.node,
event = ctx.originalEvent || {},
triggeredByInput = $(event.target).is(":input");
flag = (flag !== false);
this._super(ctx, flag);
if( flag ){
if( opts.titlesTabbable ){
if( !triggeredByInput ) {
$(node.span).find("span.fancytree-title").focus();
node.setFocus();
}
// If one node is tabbable, the container no longer needs to be
ctx.tree.$container.attr("tabindex", "-1");
// ctx.tree.$container.removeAttr("tabindex");
} else if( opts.autofocusInput && !triggeredByInput ){
// Set focus to input sub input (if node was clicked, but not
// when TAB was pressed )
$outer = $(node.tr || node.span);
$outer.find(":input:enabled:first").focus();
}
}
},
nodeKeydown: function(ctx) {
var inputType, handleKeys, $td,
opts = ctx.options.gridnav,
event = ctx.originalEvent,
$target = $(event.target);
// jQuery
inputType = $target.is(":input:enabled") ? $target.prop("type") : null;
ctx.node.debug("input", event, inputType);
if( inputType && opts.handleCursorKeys ){
handleKeys = NAV_KEYS[inputType];
if( handleKeys && $.inArray(event.which, handleKeys) >= 0 ){
$td = findNeighbourTd($target, event.which);
// ctx.node.debug("ignore keydown in input", event.which, handleKeys);
if( $td && $td.length ) {
$td.find(":input:enabled").focus();
// Prevent Fancytree default navigation
return false;
}
}
return true;
}
this._super(ctx);
}
});
}(jQuery, window, document));
(function($) {
window.NestedFormEvents = function() {
this.addFields = $.proxy(this.addFields, this);
this.removeFields = $.proxy(this.removeFields, this);
};
NestedFormEvents.prototype = {
addFields: function(e) {
// Setup
var link = e.currentTarget;
var assoc = $(link).data('association'); // Name of child
var blueprint = $('#' + $(link).data('blueprint-id'));
var content = blueprint.data('blueprint'); // Fields template
// Make the context correct by replacing with the generated ID
// of each of the parent objects
var context = ($(link).closest('.fields').closestChild('input, textarea, select').eq(0).attr('name') || '').replace(new RegExp('\[[a-z_]+\]$'), '');
// context will be something like this for a brand new form:
// project[tasks_attributes][1255929127459][assignments_attributes][1255929128105]
// or for an edit form:
// project[tasks_attributes][0][assignments_attributes][1]
if (context) {
var parentNames = context.match(/[a-z_]+_attributes(?=\]\[(new_)?\d+\])/g) || [];
var parentIds = context.match(/[0-9]+/g) || [];
for(var i = 0; i < parentNames.length; i++) {
if(parentIds[i]) {
content = content.replace(
new RegExp('(_' + parentNames[i] + ')_.+?_', 'g'),
'$1_' + parentIds[i] + '_');
content = content.replace(
new RegExp('(\\[' + parentNames[i] + '\\])\\[.+?\\]', 'g'),
'$1[' + parentIds[i] + ']');
}
}
}
// Make a unique ID for the new child
var regexp = new RegExp('new_' + assoc, 'g');
var new_id = this.newId();
content = $.trim(content.replace(regexp, new_id));
var field = this.insertFields(content, assoc, link);
// bubble up event upto document (through form)
field
.trigger({ type: 'nested:fieldAdded', field: field })
.trigger({ type: 'nested:fieldAdded:' + assoc, field: field });
return false;
},
newId: function() {
return new Date().getTime();
},
insertFields: function(content, assoc, link) {
var target = $(link).data('target');
if (target) {
return $(content).appendTo($(target));
} else {
return $(content).insertBefore(link);
}
},
removeFields: function(e) {
var $link = $(e.currentTarget),
assoc = $link.data('association'); // Name of child to be removed
var hiddenField = $link.prev('input[type=hidden]');
hiddenField.val('1');
var field = $link.closest('.fields');
field.hide();
field
.trigger({ type: 'nested:fieldRemoved', field: field })
.trigger({ type: 'nested:fieldRemoved:' + assoc, field: field });
return false;
}
};
window.nestedFormEvents = new NestedFormEvents();
$(document)
.delegate('form a.add_nested_fields', 'click', nestedFormEvents.addFields)
.delegate('form a.remove_nested_fields', 'click', nestedFormEvents.removeFields);
})(jQuery);
// http://plugins.jquery.com/project/closestChild
/*
* Copyright 2011, Tobias Lindig
*
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
*/
(function($) {
$.fn.closestChild = function(selector) {
// breadth first search for the first matched node
if (selector && selector != '') {
var queue = [];
queue.push(this);
while(queue.length > 0) {
var node = queue.shift();
var children = node.children();
for(var i = 0; i < children.length; ++i) {
var child = $(children[i]);
if (child.is(selector)) {
return child; //well, we found one
}
queue.push(child);
}
}
}
return $();//nothing found
};
})(jQuery);
/*
* jQuery UI Timepicker
*
* Copyright 2010-2013, Francois Gelinas
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://fgelinas.com/code/timepicker
*
* Depends:
* jquery.ui.core.js
* jquery.ui.position.js (only if position settngs are used)
*
* Change version 0.1.0 - moved the t-rex up here
*
____
___ .-~. /_"-._
`-._~-. / /_ "~o\ :Y
\ \ / : \~x. ` ')
] Y / | Y< ~-.__j
/ ! _.--~T : l l< /.-~
/ / ____.--~ . ` l /~\ \<|Y
/ / .-~~" /| . ',-~\ \L|
/ / / .^ \ Y~Y \.^>/l_ "--'
/ Y .-"( . l__ j_j l_/ /~_.-~ .
Y l / \ ) ~~~." / `/"~ / \.__/l_
| \ _.-" ~-{__ l : l._Z~-.___.--~
| ~---~ / ~~"---\_ ' __[>
l . _.^ ___ _>-y~
\ \ . .-~ .-~ ~>--" /
\ ~---" / ./ _.-'
"-.,_____.,_ _.--~\ _.-~
~~ ( _} -Row
`. ~(
) \
/,`--'~\--'~\
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
->T-Rex<-
*/
(function ($) {
$.extend($.ui, { timepicker: { version: "0.3.2"} });
var PROP_NAME = 'timepicker',
tpuuid = new Date().getTime();
/* Time picker manager.
Use the singleton instance of this class, $.timepicker, to interact with the time picker.
Settings for (groups of) time pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Timepicker() {
this.debug = true; // Change this to true to start debugging
this._curInst = null; // The current instance in use
this._disabledInputs = []; // List of time picker inputs that have been disabled
this._timepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._dialogClass = 'ui-timepicker-dialog'; // The name of the dialog marker class
this._mainDivId = 'ui-timepicker-div'; // The ID of the main timepicker division
this._inlineClass = 'ui-timepicker-inline'; // The name of the inline marker class
this._currentClass = 'ui-timepicker-current'; // The name of the current hour / minutes marker class
this._dayOverClass = 'ui-timepicker-days-cell-over'; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[''] = { // Default regional settings
hourText: 'Hour', // Display text for hours section
minuteText: 'Minute', // Display text for minutes link
amPmText: ['AM', 'PM'], // Display text for AM PM
closeButtonText: 'Done', // Text for the confirmation button (ok button)
nowButtonText: 'Now', // Text for the now button
deselectButtonText: 'Deselect' // Text for the deselect button
};
this._defaults = { // Global defaults for all the time picker instances
showOn: 'focus', // 'focus' for popup on focus,
// 'button' for trigger button, or 'both' for either (not yet implemented)
button: null, // 'button' element that will trigger the timepicker
showAnim: 'fadeIn', // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
appendText: '', // Display text following the input box, e.g. showing the format
beforeShow: null, // Define a callback function executed before the timepicker is shown
onSelect: null, // Define a callback function when a hour / minutes is selected
onClose: null, // Define a callback function when the timepicker is closed
timeSeparator: ':', // The character to use to separate hours and minutes.
periodSeparator: ' ', // The character to use to separate the time from the time period.
showPeriod: false, // Define whether or not to show AM/PM with selected time
showPeriodLabels: true, // Show the AM/PM labels on the left of the time picker
showLeadingZero: true, // Define whether or not to show a leading zero for hours < 10. [true/false]
showMinutesLeadingZero: true, // Define whether or not to show a leading zero for minutes < 10.
altField: '', // Selector for an alternate field to store selected time into
defaultTime: 'now', // Used as default time when input field is empty or for inline timePicker
// (set to 'now' for the current time, '' for no highlighted time)
myPosition: 'left top', // Position of the dialog relative to the input.
// see the position utility for more info : http://jqueryui.com/demos/position/
atPosition: 'left bottom', // Position of the input element to match
// Note : if the position utility is not loaded, the timepicker will attach left top to left bottom
//NEW: 2011-02-03
onHourShow: null, // callback for enabling / disabling on selectable hours ex : function(hour) { return true; }
onMinuteShow: null, // callback for enabling / disabling on time selection ex : function(hour,minute) { return true; }
hours: {
starts: 0, // first displayed hour
ends: 23 // last displayed hour
},
minutes: {
starts: 0, // first displayed minute
ends: 55, // last displayed minute
interval: 5 // interval of displayed minutes
},
rows: 4, // number of rows for the input tables, minimum 2, makes more sense if you use multiple of 2
// 2011-08-05 0.2.4
showHours: true, // display the hours section of the dialog
showMinutes: true, // display the minute section of the dialog
optionalMinutes: false, // optionally parse inputs of whole hours with minutes omitted
// buttons
showCloseButton: false, // shows an OK button to confirm the edit
showNowButton: false, // Shows the 'now' button
showDeselectButton: false // Shows the deselect time button
};
$.extend(this._defaults, this.regional['']);
this.tpDiv = $('
');
}
$.extend(Timepicker.prototype, {
/* Class name added to elements to indicate already configured with a time picker. */
markerClassName: 'hasTimepicker',
/* Debug logging (if enabled). */
log: function () {
if (this.debug)
console.log.apply('', arguments);
},
_widgetTimepicker: function () {
return this.tpDiv;
},
/* Override the default settings for all instances of the time picker.
@param settings object - the new settings to use as defaults (anonymous object)
@return the manager object */
setDefaults: function (settings) {
extendRemove(this._defaults, settings || {});
return this;
},
/* Attach the time picker to a jQuery selection.
@param target element - the target input field or division or span
@param settings object - the new settings to use for this time picker instance (anonymous) */
_attachTimepicker: function (target, settings) {
// check for settings on the control itself - in namespace 'time:'
var inlineSettings = null;
for (var attrName in this._defaults) {
var attrValue = target.getAttribute('time:' + attrName);
if (attrValue) {
inlineSettings = inlineSettings || {};
try {
inlineSettings[attrName] = eval(attrValue);
} catch (err) {
inlineSettings[attrName] = attrValue;
}
}
}
var nodeName = target.nodeName.toLowerCase();
var inline = (nodeName == 'div' || nodeName == 'span');
if (!target.id) {
this.uuid += 1;
target.id = 'tp' + this.uuid;
}
var inst = this._newInst($(target), inline);
inst.settings = $.extend({}, settings || {}, inlineSettings || {});
if (nodeName == 'input') {
this._connectTimepicker(target, inst);
// init inst.hours and inst.minutes from the input value
this._setTimeFromField(inst);
} else if (inline) {
this._inlineTimepicker(target, inst);
}
},
/* Create a new instance object. */
_newInst: function (target, inline) {
var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars
return {
id: id, input: target, // associated target
inline: inline, // is timepicker inline or not :
tpDiv: (!inline ? this.tpDiv : // presentation div
$('
'))
};
},
/* Attach the time picker to an input field. */
_connectTimepicker: function (target, inst) {
var input = $(target);
inst.append = $([]);
inst.trigger = $([]);
if (input.hasClass(this.markerClassName)) { return; }
this._attachments(input, inst);
input.addClass(this.markerClassName).
keydown(this._doKeyDown).
keyup(this._doKeyUp).
bind("setData.timepicker", function (event, key, value) {
inst.settings[key] = value;
}).
bind("getData.timepicker", function (event, key) {
return this._get(inst, key);
});
$.data(target, PROP_NAME, inst);
},
/* Handle keystrokes. */
_doKeyDown: function (event) {
var inst = $.timepicker._getInst(event.target);
var handled = true;
inst._keyEvent = true;
if ($.timepicker._timepickerShowing) {
switch (event.keyCode) {
case 9: $.timepicker._hideTimepicker();
handled = false;
break; // hide on tab out
case 13:
$.timepicker._updateSelectedValue(inst);
$.timepicker._hideTimepicker();
return false; // don't submit the form
break; // select the value on enter
case 27: $.timepicker._hideTimepicker();
break; // hide on escape
default: handled = false;
}
}
else if (event.keyCode == 36 && event.ctrlKey) { // display the time picker on ctrl+home
$.timepicker._showTimepicker(this);
}
else {
handled = false;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
},
/* Update selected time on keyUp */
/* Added verion 0.0.5 */
_doKeyUp: function (event) {
var inst = $.timepicker._getInst(event.target);
$.timepicker._setTimeFromField(inst);
$.timepicker._updateTimepicker(inst);
},
/* Make attachments based on settings. */
_attachments: function (input, inst) {
var appendText = this._get(inst, 'appendText');
var isRTL = this._get(inst, 'isRTL');
if (inst.append) { inst.append.remove(); }
if (appendText) {
inst.append = $('' + appendText + ' ');
input[isRTL ? 'before' : 'after'](inst.append);
}
input.unbind('focus.timepicker', this._showTimepicker);
input.unbind('click.timepicker', this._adjustZIndex);
if (inst.trigger) { inst.trigger.remove(); }
var showOn = this._get(inst, 'showOn');
if (showOn == 'focus' || showOn == 'both') { // pop-up time picker when in the marked field
input.bind("focus.timepicker", this._showTimepicker);
input.bind("click.timepicker", this._adjustZIndex);
}
if (showOn == 'button' || showOn == 'both') { // pop-up time picker when 'button' element is clicked
var button = this._get(inst, 'button');
$(button).bind("click.timepicker", function () {
if ($.timepicker._timepickerShowing && $.timepicker._lastInput == input[0]) {
$.timepicker._hideTimepicker();
} else if (!inst.input.is(':disabled')) {
$.timepicker._showTimepicker(input[0]);
}
return false;
});
}
},
/* Attach an inline time picker to a div. */
_inlineTimepicker: function(target, inst) {
var divSpan = $(target);
if (divSpan.hasClass(this.markerClassName))
return;
divSpan.addClass(this.markerClassName).append(inst.tpDiv).
bind("setData.timepicker", function(event, key, value){
inst.settings[key] = value;
}).bind("getData.timepicker", function(event, key){
return this._get(inst, key);
});
$.data(target, PROP_NAME, inst);
this._setTimeFromField(inst);
this._updateTimepicker(inst);
inst.tpDiv.show();
},
_adjustZIndex: function(input) {
input = input.target || input;
var inst = $.timepicker._getInst(input);
inst.tpDiv.css('zIndex', $.timepicker._getZIndex(input) +1);
},
/* Pop-up the time picker for a given input field.
@param input element - the input field attached to the time picker or
event - if triggered by focus */
_showTimepicker: function (input) {
input = input.target || input;
if (input.nodeName.toLowerCase() != 'input') { input = $('input', input.parentNode)[0]; } // find from button/image trigger
if ($.timepicker._isDisabledTimepicker(input) || $.timepicker._lastInput == input) { return; } // already here
// fix v 0.0.8 - close current timepicker before showing another one
$.timepicker._hideTimepicker();
var inst = $.timepicker._getInst(input);
if ($.timepicker._curInst && $.timepicker._curInst != inst) {
$.timepicker._curInst.tpDiv.stop(true, true);
}
var beforeShow = $.timepicker._get(inst, 'beforeShow');
extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
inst.lastVal = null;
$.timepicker._lastInput = input;
$.timepicker._setTimeFromField(inst);
// calculate default position
if ($.timepicker._inDialog) { input.value = ''; } // hide cursor
if (!$.timepicker._pos) { // position below input
$.timepicker._pos = $.timepicker._findPos(input);
$.timepicker._pos[1] += input.offsetHeight; // add the height
}
var isFixed = false;
$(input).parents().each(function () {
isFixed |= $(this).css('position') == 'fixed';
return !isFixed;
});
var offset = { left: $.timepicker._pos[0], top: $.timepicker._pos[1] };
$.timepicker._pos = null;
// determine sizing offscreen
inst.tpDiv.css({ position: 'absolute', display: 'block', top: '-1000px' });
$.timepicker._updateTimepicker(inst);
// position with the ui position utility, if loaded
if ( ( ! inst.inline ) && ( typeof $.ui.position == 'object' ) ) {
inst.tpDiv.position({
of: inst.input,
my: $.timepicker._get( inst, 'myPosition' ),
at: $.timepicker._get( inst, 'atPosition' ),
// offset: $( "#offset" ).val(),
// using: using,
collision: 'flip'
});
var offset = inst.tpDiv.offset();
$.timepicker._pos = [offset.top, offset.left];
}
// reset clicked state
inst._hoursClicked = false;
inst._minutesClicked = false;
// fix width for dynamic number of time pickers
// and adjust position before showing
offset = $.timepicker._checkOffset(inst, offset, isFixed);
inst.tpDiv.css({ position: ($.timepicker._inDialog && $.blockUI ?
'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
left: offset.left + 'px', top: offset.top + 'px'
});
if ( ! inst.inline ) {
var showAnim = $.timepicker._get(inst, 'showAnim');
var duration = $.timepicker._get(inst, 'duration');
var postProcess = function () {
$.timepicker._timepickerShowing = true;
var borders = $.timepicker._getBorders(inst.tpDiv);
inst.tpDiv.find('iframe.ui-timepicker-cover'). // IE6- only
css({ left: -borders[0], top: -borders[1],
width: inst.tpDiv.outerWidth(), height: inst.tpDiv.outerHeight()
});
};
// Fixed the zIndex problem for real (I hope) - FG - v 0.2.9
$.timepicker._adjustZIndex(input);
//inst.tpDiv.css('zIndex', $.timepicker._getZIndex(input) +1);
if ($.effects && $.effects[showAnim]) {
inst.tpDiv.show(showAnim, $.timepicker._get(inst, 'showOptions'), duration, postProcess);
}
else {
inst.tpDiv.show((showAnim ? duration : null), postProcess);
}
if (!showAnim || !duration) { postProcess(); }
if (inst.input.is(':visible') && !inst.input.is(':disabled')) { inst.input.focus(); }
$.timepicker._curInst = inst;
}
},
// This is an enhanced copy of the zIndex function of UI core 1.8.?? For backward compatibility.
// Enhancement returns maximum zindex value discovered while traversing parent elements,
// rather than the first zindex value found. Ensures the timepicker popup will be in front,
// even in funky scenarios like non-jq dialog containers with large fixed zindex values and
// nested zindex-influenced elements of their own.
_getZIndex: function (target) {
var elem = $(target);
var maxValue = 0;
var position, value;
while (elem.length && elem[0] !== document) {
position = elem.css("position");
if (position === "absolute" || position === "relative" || position === "fixed") {
value = parseInt(elem.css("zIndex"), 10);
if (!isNaN(value) && value !== 0) {
if (value > maxValue) { maxValue = value; }
}
}
elem = elem.parent();
}
return maxValue;
},
/* Refresh the time picker
@param target element - The target input field or inline container element. */
_refreshTimepicker: function(target) {
var inst = this._getInst(target);
if (inst) {
this._updateTimepicker(inst);
}
},
/* Generate the time picker content. */
_updateTimepicker: function (inst) {
inst.tpDiv.empty().append(this._generateHTML(inst));
this._rebindDialogEvents(inst);
},
_rebindDialogEvents: function (inst) {
var borders = $.timepicker._getBorders(inst.tpDiv),
self = this;
inst.tpDiv
.find('iframe.ui-timepicker-cover') // IE6- only
.css({ left: -borders[0], top: -borders[1],
width: inst.tpDiv.outerWidth(), height: inst.tpDiv.outerHeight()
})
.end()
// after the picker html is appended bind the click & double click events (faster in IE this way
// then letting the browser interpret the inline events)
// the binding for the minute cells also exists in _updateMinuteDisplay
.find('.ui-timepicker-minute-cell')
.unbind()
.bind("click", { fromDoubleClick:false }, $.proxy($.timepicker.selectMinutes, this))
.bind("dblclick", { fromDoubleClick:true }, $.proxy($.timepicker.selectMinutes, this))
.end()
.find('.ui-timepicker-hour-cell')
.unbind()
.bind("click", { fromDoubleClick:false }, $.proxy($.timepicker.selectHours, this))
.bind("dblclick", { fromDoubleClick:true }, $.proxy($.timepicker.selectHours, this))
.end()
.find('.ui-timepicker td a')
.unbind()
.bind('mouseout', function () {
$(this).removeClass('ui-state-hover');
if (this.className.indexOf('ui-timepicker-prev') != -1) $(this).removeClass('ui-timepicker-prev-hover');
if (this.className.indexOf('ui-timepicker-next') != -1) $(this).removeClass('ui-timepicker-next-hover');
})
.bind('mouseover', function () {
if ( ! self._isDisabledTimepicker(inst.inline ? inst.tpDiv.parent()[0] : inst.input[0])) {
$(this).parents('.ui-timepicker-calendar').find('a').removeClass('ui-state-hover');
$(this).addClass('ui-state-hover');
if (this.className.indexOf('ui-timepicker-prev') != -1) $(this).addClass('ui-timepicker-prev-hover');
if (this.className.indexOf('ui-timepicker-next') != -1) $(this).addClass('ui-timepicker-next-hover');
}
})
.end()
.find('.' + this._dayOverClass + ' a')
.trigger('mouseover')
.end()
.find('.ui-timepicker-now').bind("click", function(e) {
$.timepicker.selectNow(e);
}).end()
.find('.ui-timepicker-deselect').bind("click",function(e) {
$.timepicker.deselectTime(e);
}).end()
.find('.ui-timepicker-close').bind("click",function(e) {
$.timepicker._hideTimepicker();
}).end();
},
/* Generate the HTML for the current state of the time picker. */
_generateHTML: function (inst) {
var h, m, row, col, html, hoursHtml, minutesHtml = '',
showPeriod = (this._get(inst, 'showPeriod') == true),
showPeriodLabels = (this._get(inst, 'showPeriodLabels') == true),
showLeadingZero = (this._get(inst, 'showLeadingZero') == true),
showHours = (this._get(inst, 'showHours') == true),
showMinutes = (this._get(inst, 'showMinutes') == true),
amPmText = this._get(inst, 'amPmText'),
rows = this._get(inst, 'rows'),
amRows = 0,
pmRows = 0,
amItems = 0,
pmItems = 0,
amFirstRow = 0,
pmFirstRow = 0,
hours = Array(),
hours_options = this._get(inst, 'hours'),
hoursPerRow = null,
hourCounter = 0,
hourLabel = this._get(inst, 'hourText'),
showCloseButton = this._get(inst, 'showCloseButton'),
closeButtonText = this._get(inst, 'closeButtonText'),
showNowButton = this._get(inst, 'showNowButton'),
nowButtonText = this._get(inst, 'nowButtonText'),
showDeselectButton = this._get(inst, 'showDeselectButton'),
deselectButtonText = this._get(inst, 'deselectButtonText'),
showButtonPanel = showCloseButton || showNowButton || showDeselectButton;
// prepare all hours and minutes, makes it easier to distribute by rows
for (h = hours_options.starts; h <= hours_options.ends; h++) {
hours.push (h);
}
hoursPerRow = Math.ceil(hours.length / rows); // always round up
if (showPeriodLabels) {
for (hourCounter = 0; hourCounter < hours.length; hourCounter++) {
if (hours[hourCounter] < 12) {
amItems++;
}
else {
pmItems++;
}
}
hourCounter = 0;
amRows = Math.floor(amItems / hours.length * rows);
pmRows = Math.floor(pmItems / hours.length * rows);
// assign the extra row to the period that is more densely populated
if (rows != amRows + pmRows) {
// Make sure: AM Has Items and either PM Does Not, AM has no rows yet, or AM is more dense
if (amItems && (!pmItems || !amRows || (pmRows && amItems / amRows >= pmItems / pmRows))) {
amRows++;
} else {
pmRows++;
}
}
amFirstRow = Math.min(amRows, 1);
pmFirstRow = amRows + 1;
if (amRows == 0) {
hoursPerRow = Math.ceil(pmItems / pmRows);
} else if (pmRows == 0) {
hoursPerRow = Math.ceil(amItems / amRows);
} else {
hoursPerRow = Math.ceil(Math.max(amItems / amRows, pmItems / pmRows));
}
}
html = '';
if (showHours) {
html += '' +
'' +
'';
for (row = 1; row <= rows; row++) {
html += '';
// AM
if (row == amFirstRow && showPeriodLabels) {
html += '' + amPmText[0] + ' ';
}
// PM
if (row == pmFirstRow && showPeriodLabels) {
html += '' + amPmText[1] + ' ';
}
for (col = 1; col <= hoursPerRow; col++) {
if (showPeriodLabels && row < pmFirstRow && hours[hourCounter] >= 12) {
html += this._generateHTMLHourCell(inst, undefined, showPeriod, showLeadingZero);
} else {
html += this._generateHTMLHourCell(inst, hours[hourCounter], showPeriod, showLeadingZero);
hourCounter++;
}
}
html += ' ';
}
html += '
' + // Close the hours cells table
' '; // Close the Hour td
}
if (showMinutes) {
html += '';
html += this._generateHTMLMinutes(inst);
html += ' ';
}
html += ' ';
if (showButtonPanel) {
var buttonPanel = '';
if (showNowButton) {
buttonPanel += ''
+ nowButtonText + ' ';
}
if (showDeselectButton) {
buttonPanel += ''
+ deselectButtonText + ' ';
}
if (showCloseButton) {
buttonPanel += ''
+ closeButtonText + ' ';
}
html += buttonPanel + '
';
}
html += '
';
return html;
},
/* Special function that update the minutes selection in currently visible timepicker
* called on hour selection when onMinuteShow is defined */
_updateMinuteDisplay: function (inst) {
var newHtml = this._generateHTMLMinutes(inst);
inst.tpDiv.find('td.ui-timepicker-minutes').html(newHtml);
this._rebindDialogEvents(inst);
// after the picker html is appended bind the click & double click events (faster in IE this way
// then letting the browser interpret the inline events)
// yes I know, duplicate code, sorry
/* .find('.ui-timepicker-minute-cell')
.bind("click", { fromDoubleClick:false }, $.proxy($.timepicker.selectMinutes, this))
.bind("dblclick", { fromDoubleClick:true }, $.proxy($.timepicker.selectMinutes, this));
*/
},
/*
* Generate the minutes table
* This is separated from the _generateHTML function because is can be called separately (when hours changes)
*/
_generateHTMLMinutes: function (inst) {
var m, row, html = '',
rows = this._get(inst, 'rows'),
minutes = Array(),
minutes_options = this._get(inst, 'minutes'),
minutesPerRow = null,
minuteCounter = 0,
showMinutesLeadingZero = (this._get(inst, 'showMinutesLeadingZero') == true),
onMinuteShow = this._get(inst, 'onMinuteShow'),
minuteLabel = this._get(inst, 'minuteText');
if ( ! minutes_options.starts) {
minutes_options.starts = 0;
}
if ( ! minutes_options.ends) {
minutes_options.ends = 59;
}
for (m = minutes_options.starts; m <= minutes_options.ends; m += minutes_options.interval) {
minutes.push(m);
}
minutesPerRow = Math.round(minutes.length / rows + 0.49); // always round up
/*
* The minutes table
*/
// if currently selected minute is not enabled, we have a problem and need to select a new minute.
if (onMinuteShow &&
(onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours , inst.minutes]) == false) ) {
// loop minutes and select first available
for (minuteCounter = 0; minuteCounter < minutes.length; minuteCounter += 1) {
m = minutes[minuteCounter];
if (onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours, m])) {
inst.minutes = m;
break;
}
}
}
html += '' +
'';
minuteCounter = 0;
for (row = 1; row <= rows; row++) {
html += '';
while (minuteCounter < row * minutesPerRow) {
var m = minutes[minuteCounter];
var displayText = '';
if (m !== undefined ) {
displayText = (m < 10) && showMinutesLeadingZero ? "0" + m.toString() : m.toString();
}
html += this._generateHTMLMinuteCell(inst, m, displayText);
minuteCounter++;
}
html += ' ';
}
html += '
';
return html;
},
/* Generate the content of a "Hour" cell */
_generateHTMLHourCell: function (inst, hour, showPeriod, showLeadingZero) {
var displayHour = hour;
if ((hour > 12) && showPeriod) {
displayHour = hour - 12;
}
if ((displayHour == 0) && showPeriod) {
displayHour = 12;
}
if ((displayHour < 10) && showLeadingZero) {
displayHour = '0' + displayHour;
}
var html = "";
var enabled = true;
var onHourShow = this._get(inst, 'onHourShow'); //custom callback
if (hour == undefined) {
html = ' ';
return html;
}
if (onHourShow) {
enabled = onHourShow.apply((inst.input ? inst.input[0] : null), [hour]);
}
if (enabled) {
html = '' +
'' +
displayHour.toString() +
' ';
}
else {
html =
'' +
'' +
displayHour.toString() +
' ' +
' ';
}
return html;
},
/* Generate the content of a "Hour" cell */
_generateHTMLMinuteCell: function (inst, minute, displayText) {
var html = "";
var enabled = true;
var onMinuteShow = this._get(inst, 'onMinuteShow'); //custom callback
if (onMinuteShow) {
//NEW: 2011-02-03 we should give the hour as a parameter as well!
enabled = onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours,minute]); //trigger callback
}
if (minute == undefined) {
html = ' ';
return html;
}
if (enabled) {
html = '' +
'' +
displayText +
' ';
}
else {
html = '' +
'' +
displayText +
' ' +
' ';
}
return html;
},
/* Detach a timepicker from its control.
@param target element - the target input field or division or span */
_destroyTimepicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
$.removeData(target, PROP_NAME);
if (nodeName == 'input') {
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName)
.unbind('focus.timepicker', this._showTimepicker)
.unbind('click.timepicker', this._adjustZIndex);
} else if (nodeName == 'div' || nodeName == 'span')
$target.removeClass(this.markerClassName).empty();
},
/* Enable the date picker to a jQuery selection.
@param target element - the target input field or division or span */
_enableTimepicker: function(target) {
var $target = $(target),
target_id = $target.attr('id'),
inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
if (nodeName == 'input') {
target.disabled = false;
var button = this._get(inst, 'button');
$(button).removeClass('ui-state-disabled').disabled = false;
inst.trigger.filter('button').
each(function() { this.disabled = false; }).end();
}
else if (nodeName == 'div' || nodeName == 'span') {
var inline = $target.children('.' + this._inlineClass);
inline.children().removeClass('ui-state-disabled');
inline.find('button').each(
function() { this.disabled = false }
)
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value == target_id ? null : value); }); // delete entry
},
/* Disable the time picker to a jQuery selection.
@param target element - the target input field or division or span */
_disableTimepicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
if (nodeName == 'input') {
var button = this._get(inst, 'button');
$(button).addClass('ui-state-disabled').disabled = true;
target.disabled = true;
inst.trigger.filter('button').
each(function() { this.disabled = true; }).end();
}
else if (nodeName == 'div' || nodeName == 'span') {
var inline = $target.children('.' + this._inlineClass);
inline.children().addClass('ui-state-disabled');
inline.find('button').each(
function() { this.disabled = true }
)
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value == target ? null : value); }); // delete entry
this._disabledInputs[this._disabledInputs.length] = $target.attr('id');
},
/* Is the first field in a jQuery collection disabled as a timepicker?
@param target_id element - the target input field or division or span
@return boolean - true if disabled, false if enabled */
_isDisabledTimepicker: function (target_id) {
if ( ! target_id) { return false; }
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] == target_id) { return true; }
}
return false;
},
/* Check positioning to remain on screen. */
_checkOffset: function (inst, offset, isFixed) {
var tpWidth = inst.tpDiv.outerWidth();
var tpHeight = inst.tpDiv.outerHeight();
var inputWidth = inst.input ? inst.input.outerWidth() : 0;
var inputHeight = inst.input ? inst.input.outerHeight() : 0;
var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft();
var viewHeight = document.documentElement.clientHeight + $(document).scrollTop();
offset.left -= (this._get(inst, 'isRTL') ? (tpWidth - inputWidth) : 0);
offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
// now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min(offset.left, (offset.left + tpWidth > viewWidth && viewWidth > tpWidth) ?
Math.abs(offset.left + tpWidth - viewWidth) : 0);
offset.top -= Math.min(offset.top, (offset.top + tpHeight > viewHeight && viewHeight > tpHeight) ?
Math.abs(tpHeight + inputHeight) : 0);
return offset;
},
/* Find an object's position on the screen. */
_findPos: function (obj) {
var inst = this._getInst(obj);
var isRTL = this._get(inst, 'isRTL');
while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
obj = obj[isRTL ? 'previousSibling' : 'nextSibling'];
}
var position = $(obj).offset();
return [position.left, position.top];
},
/* Retrieve the size of left and top borders for an element.
@param elem (jQuery object) the element of interest
@return (number[2]) the left and top borders */
_getBorders: function (elem) {
var convert = function (value) {
return { thin: 1, medium: 2, thick: 3}[value] || value;
};
return [parseFloat(convert(elem.css('border-left-width'))),
parseFloat(convert(elem.css('border-top-width')))];
},
/* Close time picker if clicked elsewhere. */
_checkExternalClick: function (event) {
if (!$.timepicker._curInst) { return; }
var $target = $(event.target);
if ($target[0].id != $.timepicker._mainDivId &&
$target.parents('#' + $.timepicker._mainDivId).length == 0 &&
!$target.hasClass($.timepicker.markerClassName) &&
!$target.hasClass($.timepicker._triggerClass) &&
$.timepicker._timepickerShowing && !($.timepicker._inDialog && $.blockUI))
$.timepicker._hideTimepicker();
},
/* Hide the time picker from view.
@param input element - the input field attached to the time picker */
_hideTimepicker: function (input) {
var inst = this._curInst;
if (!inst || (input && inst != $.data(input, PROP_NAME))) { return; }
if (this._timepickerShowing) {
var showAnim = this._get(inst, 'showAnim');
var duration = this._get(inst, 'duration');
var postProcess = function () {
$.timepicker._tidyDialog(inst);
this._curInst = null;
};
if ($.effects && $.effects[showAnim]) {
inst.tpDiv.hide(showAnim, $.timepicker._get(inst, 'showOptions'), duration, postProcess);
}
else {
inst.tpDiv[(showAnim == 'slideDown' ? 'slideUp' :
(showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess);
}
if (!showAnim) { postProcess(); }
this._timepickerShowing = false;
this._lastInput = null;
if (this._inDialog) {
this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
if ($.blockUI) {
$.unblockUI();
$('body').append(this.tpDiv);
}
}
this._inDialog = false;
var onClose = this._get(inst, 'onClose');
if (onClose) {
onClose.apply(
(inst.input ? inst.input[0] : null),
[(inst.input ? inst.input.val() : ''), inst]); // trigger custom callback
}
}
},
/* Tidy up after a dialog display. */
_tidyDialog: function (inst) {
inst.tpDiv.removeClass(this._dialogClass).unbind('.ui-timepicker');
},
/* Retrieve the instance data for the target control.
@param target element - the target input field or division or span
@return object - the associated instance data
@throws error if a jQuery problem getting data */
_getInst: function (target) {
try {
return $.data(target, PROP_NAME);
}
catch (err) {
throw 'Missing instance data for this timepicker';
}
},
/* Get a setting value, defaulting if necessary. */
_get: function (inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Parse existing time and initialise time picker. */
_setTimeFromField: function (inst) {
if (inst.input.val() == inst.lastVal) { return; }
var defaultTime = this._get(inst, 'defaultTime');
var timeToParse = defaultTime == 'now' ? this._getCurrentTimeRounded(inst) : defaultTime;
if ((inst.inline == false) && (inst.input.val() != '')) { timeToParse = inst.input.val() }
if (timeToParse instanceof Date) {
inst.hours = timeToParse.getHours();
inst.minutes = timeToParse.getMinutes();
} else {
var timeVal = inst.lastVal = timeToParse;
if (timeToParse == '') {
inst.hours = -1;
inst.minutes = -1;
} else {
var time = this.parseTime(inst, timeVal);
inst.hours = time.hours;
inst.minutes = time.minutes;
}
}
$.timepicker._updateTimepicker(inst);
},
/* Update or retrieve the settings for an existing time picker.
@param target element - the target input field or division or span
@param name object - the new settings to update or
string - the name of the setting to change or retrieve,
when retrieving also 'all' for all instance settings or
'defaults' for all global defaults
@param value any - the new value for the setting
(omit if above is an object or to retrieve a value) */
_optionTimepicker: function(target, name, value) {
var inst = this._getInst(target);
if (arguments.length == 2 && typeof name == 'string') {
return (name == 'defaults' ? $.extend({}, $.timepicker._defaults) :
(inst ? (name == 'all' ? $.extend({}, inst.settings) :
this._get(inst, name)) : null));
}
var settings = name || {};
if (typeof name == 'string') {
settings = {};
settings[name] = value;
}
if (inst) {
if (this._curInst == inst) {
this._hideTimepicker();
}
extendRemove(inst.settings, settings);
this._updateTimepicker(inst);
}
},
/* Set the time for a jQuery selection.
@param target element - the target input field or division or span
@param time String - the new time */
_setTimeTimepicker: function(target, time) {
var inst = this._getInst(target);
if (inst) {
this._setTime(inst, time);
this._updateTimepicker(inst);
this._updateAlternate(inst, time);
}
},
/* Set the time directly. */
_setTime: function(inst, time, noChange) {
var origHours = inst.hours;
var origMinutes = inst.minutes;
if (time instanceof Date) {
inst.hours = time.getHours();
inst.minutes = time.getMinutes();
} else {
var time = this.parseTime(inst, time);
inst.hours = time.hours;
inst.minutes = time.minutes;
}
if ((origHours != inst.hours || origMinutes != inst.minutes) && !noChange) {
inst.input.trigger('change');
}
this._updateTimepicker(inst);
this._updateSelectedValue(inst);
},
/* Return the current time, ready to be parsed, rounded to the closest 5 minute */
_getCurrentTimeRounded: function (inst) {
var currentTime = new Date(),
currentMinutes = currentTime.getMinutes(),
// round to closest 5
adjustedMinutes = Math.round( currentMinutes / 5 ) * 5;
currentTime.setMinutes(adjustedMinutes);
return currentTime;
},
/*
* Parse a time string into hours and minutes
*/
parseTime: function (inst, timeVal) {
var retVal = new Object();
retVal.hours = -1;
retVal.minutes = -1;
if(!timeVal)
return '';
var timeSeparator = this._get(inst, 'timeSeparator'),
amPmText = this._get(inst, 'amPmText'),
showHours = this._get(inst, 'showHours'),
showMinutes = this._get(inst, 'showMinutes'),
optionalMinutes = this._get(inst, 'optionalMinutes'),
showPeriod = (this._get(inst, 'showPeriod') == true),
p = timeVal.indexOf(timeSeparator);
// check if time separator found
if (p != -1) {
retVal.hours = parseInt(timeVal.substr(0, p), 10);
retVal.minutes = parseInt(timeVal.substr(p + 1), 10);
}
// check for hours only
else if ( (showHours) && ( !showMinutes || optionalMinutes ) ) {
retVal.hours = parseInt(timeVal, 10);
}
// check for minutes only
else if ( ( ! showHours) && (showMinutes) ) {
retVal.minutes = parseInt(timeVal, 10);
}
if (showHours) {
var timeValUpper = timeVal.toUpperCase();
if ((retVal.hours < 12) && (showPeriod) && (timeValUpper.indexOf(amPmText[1].toUpperCase()) != -1)) {
retVal.hours += 12;
}
// fix for 12 AM
if ((retVal.hours == 12) && (showPeriod) && (timeValUpper.indexOf(amPmText[0].toUpperCase()) != -1)) {
retVal.hours = 0;
}
}
return retVal;
},
selectNow: function(event) {
var id = $(event.target).attr("data-timepicker-instance-id"),
$target = $(id),
inst = this._getInst($target[0]);
//if (!inst || (input && inst != $.data(input, PROP_NAME))) { return; }
var currentTime = new Date();
inst.hours = currentTime.getHours();
inst.minutes = currentTime.getMinutes();
this._updateSelectedValue(inst);
this._updateTimepicker(inst);
this._hideTimepicker();
},
deselectTime: function(event) {
var id = $(event.target).attr("data-timepicker-instance-id"),
$target = $(id),
inst = this._getInst($target[0]);
inst.hours = -1;
inst.minutes = -1;
this._updateSelectedValue(inst);
this._hideTimepicker();
},
selectHours: function (event) {
var $td = $(event.currentTarget),
id = $td.attr("data-timepicker-instance-id"),
newHours = parseInt($td.attr("data-hour")),
fromDoubleClick = event.data.fromDoubleClick,
$target = $(id),
inst = this._getInst($target[0]),
showMinutes = (this._get(inst, 'showMinutes') == true);
// don't select if disabled
if ( $.timepicker._isDisabledTimepicker($target.attr('id')) ) { return false }
$td.parents('.ui-timepicker-hours:first').find('a').removeClass('ui-state-active');
$td.children('a').addClass('ui-state-active');
inst.hours = newHours;
// added for onMinuteShow callback
var onMinuteShow = this._get(inst, 'onMinuteShow');
if (onMinuteShow) {
// this will trigger a callback on selected hour to make sure selected minute is allowed.
this._updateMinuteDisplay(inst);
}
this._updateSelectedValue(inst);
inst._hoursClicked = true;
if ((inst._minutesClicked) || (fromDoubleClick) || (showMinutes == false)) {
$.timepicker._hideTimepicker();
}
// return false because if used inline, prevent the url to change to a hashtag
return false;
},
selectMinutes: function (event) {
var $td = $(event.currentTarget),
id = $td.attr("data-timepicker-instance-id"),
newMinutes = parseInt($td.attr("data-minute")),
fromDoubleClick = event.data.fromDoubleClick,
$target = $(id),
inst = this._getInst($target[0]),
showHours = (this._get(inst, 'showHours') == true);
// don't select if disabled
if ( $.timepicker._isDisabledTimepicker($target.attr('id')) ) { return false }
$td.parents('.ui-timepicker-minutes:first').find('a').removeClass('ui-state-active');
$td.children('a').addClass('ui-state-active');
inst.minutes = newMinutes;
this._updateSelectedValue(inst);
inst._minutesClicked = true;
if ((inst._hoursClicked) || (fromDoubleClick) || (showHours == false)) {
$.timepicker._hideTimepicker();
// return false because if used inline, prevent the url to change to a hashtag
return false;
}
// return false because if used inline, prevent the url to change to a hashtag
return false;
},
_updateSelectedValue: function (inst) {
var newTime = this._getParsedTime(inst);
if (inst.input) {
inst.input.val(newTime);
inst.input.trigger('change');
}
var onSelect = this._get(inst, 'onSelect');
if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [newTime, inst]); } // trigger custom callback
this._updateAlternate(inst, newTime);
return newTime;
},
/* this function process selected time and return it parsed according to instance options */
_getParsedTime: function(inst) {
if (inst.hours == -1 && inst.minutes == -1) {
return '';
}
// default to 0 AM if hours is not valid
if ((inst.hours < inst.hours.starts) || (inst.hours > inst.hours.ends )) { inst.hours = 0; }
// default to 0 minutes if minute is not valid
if ((inst.minutes < inst.minutes.starts) || (inst.minutes > inst.minutes.ends)) { inst.minutes = 0; }
var period = "",
showPeriod = (this._get(inst, 'showPeriod') == true),
showLeadingZero = (this._get(inst, 'showLeadingZero') == true),
showHours = (this._get(inst, 'showHours') == true),
showMinutes = (this._get(inst, 'showMinutes') == true),
optionalMinutes = (this._get(inst, 'optionalMinutes') == true),
amPmText = this._get(inst, 'amPmText'),
selectedHours = inst.hours ? inst.hours : 0,
selectedMinutes = inst.minutes ? inst.minutes : 0,
displayHours = selectedHours ? selectedHours : 0,
parsedTime = '';
// fix some display problem when hours or minutes are not selected yet
if (displayHours == -1) { displayHours = 0 }
if (selectedMinutes == -1) { selectedMinutes = 0 }
if (showPeriod) {
if (inst.hours == 0) {
displayHours = 12;
}
if (inst.hours < 12) {
period = amPmText[0];
}
else {
period = amPmText[1];
if (displayHours > 12) {
displayHours -= 12;
}
}
}
var h = displayHours.toString();
if (showLeadingZero && (displayHours < 10)) { h = '0' + h; }
var m = selectedMinutes.toString();
if (selectedMinutes < 10) { m = '0' + m; }
if (showHours) {
parsedTime += h;
}
if (showHours && showMinutes && (!optionalMinutes || m != 0)) {
parsedTime += this._get(inst, 'timeSeparator');
}
if (showMinutes && (!optionalMinutes || m != 0)) {
parsedTime += m;
}
if (showHours) {
if (period.length > 0) { parsedTime += this._get(inst, 'periodSeparator') + period; }
}
return parsedTime;
},
/* Update any alternate field to synchronise with the main field. */
_updateAlternate: function(inst, newTime) {
var altField = this._get(inst, 'altField');
if (altField) { // update alternate field too
$(altField).each(function(i,e) {
$(e).val(newTime);
});
}
},
_getTimeAsDateTimepicker: function(input) {
var inst = this._getInst(input);
if (inst.hours == -1 && inst.minutes == -1) {
return '';
}
// default to 0 AM if hours is not valid
if ((inst.hours < inst.hours.starts) || (inst.hours > inst.hours.ends )) { inst.hours = 0; }
// default to 0 minutes if minute is not valid
if ((inst.minutes < inst.minutes.starts) || (inst.minutes > inst.minutes.ends)) { inst.minutes = 0; }
return new Date(0, 0, 0, inst.hours, inst.minutes, 0);
},
/* This might look unused but it's called by the $.fn.timepicker function with param getTime */
/* added v 0.2.3 - gitHub issue #5 - Thanks edanuff */
_getTimeTimepicker : function(input) {
var inst = this._getInst(input);
return this._getParsedTime(inst);
},
_getHourTimepicker: function(input) {
var inst = this._getInst(input);
if ( inst == undefined) { return -1; }
return inst.hours;
},
_getMinuteTimepicker: function(input) {
var inst= this._getInst(input);
if ( inst == undefined) { return -1; }
return inst.minutes;
}
});
/* Invoke the timepicker functionality.
@param options string - a command, optionally followed by additional parameters or
Object - settings for attaching new timepicker functionality
@return jQuery object */
$.fn.timepicker = function (options) {
/* Initialise the time picker. */
if (!$.timepicker.initialized) {
$(document).mousedown($.timepicker._checkExternalClick).
find('body').append($.timepicker.tpDiv);
$.timepicker.initialized = true;
}
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (typeof options == 'string' && (options == 'getTime' || options == 'getTimeAsDate' || options == 'getHour' || options == 'getMinute' ))
return $.timepicker['_' + options + 'Timepicker'].
apply($.timepicker, [this[0]].concat(otherArgs));
if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string')
return $.timepicker['_' + options + 'Timepicker'].
apply($.timepicker, [this[0]].concat(otherArgs));
return this.each(function () {
typeof options == 'string' ?
$.timepicker['_' + options + 'Timepicker'].
apply($.timepicker, [this].concat(otherArgs)) :
$.timepicker._attachTimepicker(this, options);
});
};
/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
$.extend(target, props);
for (var name in props)
if (props[name] == null || props[name] == undefined)
target[name] = props[name];
return target;
};
$.timepicker = new Timepicker(); // singleton instance
$.timepicker.initialized = false;
$.timepicker.uuid = new Date().getTime();
$.timepicker.version = "0.3.2";
// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window['TP_jQuery_' + tpuuid] = $;
})(jQuery);
/*
* RailsAdmin date/time picker @VERSION
*
* License
*
* http://www.railsadmin.org
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.datepicker.js
* jquery.ui.timepicker.js (http://plugins.jquery.com/project/timepicker-by-fgelinas)
*/
(function($) {
$.widget("ra.datetimepicker", {
options: {
showDate: true,
showTime: true,
datepicker: {},
timepicker: {}
},
_create: function() {
var widget = this;
this.element.hide();
if (this.options.showTime) {
this.timepicker = $(' ');
this.timepicker.css("width", "60px");
this.timepicker.insertAfter(this.element);
this.timepicker.bind("change", function() { widget._onChange(); });
this.timepicker.timepicker(this.options.timepicker);
}
if (this.options.showDate) {
this.datepicker = $(' ');
this.datepicker.css("margin-right", "10px");
this.datepicker.insertAfter(this.element);
this.datepicker.bind("change", function() { widget._onChange(); });
this.datepicker.datepicker(this.options.datepicker);
}
},
_onChange: function() {
var value = [];
if (this.options.showDate) {
value.push(this.datepicker.val());
}
if (this.options.showTime) {
value.push(this.timepicker.val());
}
this.element.val(value.join(" "));
}
});
})(jQuery);
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
* Dual licensed under the MIT and GPL licenses
*
*/
(function ($) {
var ColorPicker = function () {
var
ids = {},
inAction,
charMin = 65,
visible,
tpl = '',
defaults = {
eventName: 'click',
onShow: function () {},
onBeforeShow: function(){},
onHide: function () {},
onChange: function () {},
onSubmit: function () {},
color: 'ff0000',
livePreview: true,
flat: false
},
fillRGBFields = function (hsb, cal) {
var rgb = HSBToRGB(hsb);
$(cal).data('colorpicker').fields
.eq(1).val(rgb.r).end()
.eq(2).val(rgb.g).end()
.eq(3).val(rgb.b).end();
},
fillHSBFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(4).val(hsb.h).end()
.eq(5).val(hsb.s).end()
.eq(6).val(hsb.b).end();
},
fillHexFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(0).val(HSBToHex(hsb)).end();
},
setSelector = function (hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s/100, 10),
top: parseInt(150 * (100-hsb.b)/100, 10)
});
},
setHue = function (hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
},
setCurrentColor = function (hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
setNewColor = function (hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
keyDown = function (ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
},
change = function (ev) {
var cal = $(this).parent().parent(), col;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
},
blur = function (ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
},
focus = function () {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
},
downIncrement = function (ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
},
moveIncrement = function (ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
},
upIncrement = function (ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
},
downHue = function (ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
},
moveHue = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(4)
.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upHue = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
},
downSelector = function (ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
},
moveSelector = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(6)
.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
.end()
.eq(5)
.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upSelector = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
},
enterSubmit = function (ev) {
$(this).addClass('colorpicker_focus');
},
leaveSubmit = function (ev) {
$(this).removeClass('colorpicker_focus');
},
clickSubmit = function (ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
},
show = function (ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
cal.css({left: left + 'px', top: top + 'px'});
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
cal.show();
}
$(document).bind('mousedown', {cal: cal}, hide);
return false;
},
hide = function (ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
},
isChildOf = function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
getViewport = function () {
var m = document.compatMode == 'CSS1Compat';
return {
l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
},
fixHSB = function (hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
},
fixRGB = function (rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
},
fixHex = function (hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i=0; i -1) ? hex.substring(1) : hex), 16);
return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
},
HexToHSB = function (hex) {
return RGBToHSB(HexToRGB(hex));
},
RGBToHSB = function (rgb) {
var hsb = {
h: 0,
s: 0,
b: 0
};
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
if (max != 0) {
}
hsb.s = max != 0 ? 255 * delta / max : 0;
if (hsb.s != 0) {
if (rgb.r == max) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if (rgb.g == max) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if (hsb.h < 0) {
hsb.h += 360;
}
hsb.s *= 100/255;
hsb.b *= 100/255;
return hsb;
},
HSBToRGB = function (hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s*255/100);
var v = Math.round(hsb.b*255/100);
if(s == 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255-s)*v/255;
var t3 = (t1-t2)*(h%60)/60;
if(h==360) h = 0;
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
},
RGBToHex = function (rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function (nr, val) {
if (val.length == 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
},
HSBToHex = function (hsb) {
return RGBToHex(HSBToRGB(hsb));
},
restoreOriginal = function () {
var cal = $(this).parent();
var col = cal.data('colorpicker').origColor;
cal.data('colorpicker').color = col;
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
};
return {
init: function (opt) {
opt = $.extend({}, defaults, opt||{});
if (typeof opt.color == 'string') {
opt.color = HexToHSB(opt.color);
} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
opt.color = RGBToHSB(opt.color);
} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
opt.color = fixHSB(opt.color);
} else {
return this;
}
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var options = $.extend({}, opt);
options.origColor = opt.color;
var id = 'collorpicker_' + parseInt(Math.random() * 1000);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal
.find('input')
.bind('keyup', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal
.find('span').bind('mousedown', downIncrement).end()
.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.el = this;
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit')
.bind('mouseenter', enterSubmit)
.bind('mouseleave', leaveSubmit)
.bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function(col) {
if (typeof col == 'string') {
col = HexToHSB(col);
} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
col = RGBToHSB(col);
} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function(){
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hidePicker,
ColorPickerShow: ColorPicker.showPicker,
ColorPickerSetColor: ColorPicker.setColor
});
})(jQuery)
;
/*
Copyright 2012 Igor Vaynberg
Version: 3.4.8 Timestamp: Thu May 1 09:50:32 EDT 2014
This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
General Public License version 2 (the "GPL License"). You may choose either license to govern your
use of this software only upon the condition that you accept all of the terms of either the Apache
License or the GPL License.
You may obtain a copy of the Apache License and the GPL License at:
http://www.apache.org/licenses/LICENSE-2.0
http://www.gnu.org/licenses/gpl-2.0.html
Unless required by applicable law or agreed to in writing, software distributed under the
Apache License or the GPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the Apache License and the GPL License for
the specific language governing permissions and limitations under the Apache License and the GPL License.
*/
(function ($) {
if(typeof $.fn.each2 == "undefined") {
$.extend($.fn, {
/*
* 4-10 times faster .each replacement
* use it carefully, as it overrides jQuery context of element on each iteration
*/
each2 : function (c) {
var j = $([0]), i = -1, l = this.length;
while (
++i < l
&& (j.context = j[0] = this[i])
&& c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object
);
return this;
}
});
}
})(jQuery);
(function ($, undefined) {
"use strict";
/*global document, window, jQuery, console */
if (window.Select2 !== undefined) {
return;
}
var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer,
lastMousePosition={x:0,y:0}, $document, scrollBarDimensions,
KEY = {
TAB: 9,
ENTER: 13,
ESC: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
SHIFT: 16,
CTRL: 17,
ALT: 18,
PAGE_UP: 33,
PAGE_DOWN: 34,
HOME: 36,
END: 35,
BACKSPACE: 8,
DELETE: 46,
isArrow: function (k) {
k = k.which ? k.which : k;
switch (k) {
case KEY.LEFT:
case KEY.RIGHT:
case KEY.UP:
case KEY.DOWN:
return true;
}
return false;
},
isControl: function (e) {
var k = e.which;
switch (k) {
case KEY.SHIFT:
case KEY.CTRL:
case KEY.ALT:
return true;
}
if (e.metaKey) return true;
return false;
},
isFunctionKey: function (k) {
k = k.which ? k.which : k;
return k >= 112 && k <= 123;
}
},
MEASURE_SCROLLBAR_TEMPLATE = "
",
DIACRITICS = {"\u24B6":"A","\uFF21":"A","\u00C0":"A","\u00C1":"A","\u00C2":"A","\u1EA6":"A","\u1EA4":"A","\u1EAA":"A","\u1EA8":"A","\u00C3":"A","\u0100":"A","\u0102":"A","\u1EB0":"A","\u1EAE":"A","\u1EB4":"A","\u1EB2":"A","\u0226":"A","\u01E0":"A","\u00C4":"A","\u01DE":"A","\u1EA2":"A","\u00C5":"A","\u01FA":"A","\u01CD":"A","\u0200":"A","\u0202":"A","\u1EA0":"A","\u1EAC":"A","\u1EB6":"A","\u1E00":"A","\u0104":"A","\u023A":"A","\u2C6F":"A","\uA732":"AA","\u00C6":"AE","\u01FC":"AE","\u01E2":"AE","\uA734":"AO","\uA736":"AU","\uA738":"AV","\uA73A":"AV","\uA73C":"AY","\u24B7":"B","\uFF22":"B","\u1E02":"B","\u1E04":"B","\u1E06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24B8":"C","\uFF23":"C","\u0106":"C","\u0108":"C","\u010A":"C","\u010C":"C","\u00C7":"C","\u1E08":"C","\u0187":"C","\u023B":"C","\uA73E":"C","\u24B9":"D","\uFF24":"D","\u1E0A":"D","\u010E":"D","\u1E0C":"D","\u1E10":"D","\u1E12":"D","\u1E0E":"D","\u0110":"D","\u018B":"D","\u018A":"D","\u0189":"D","\uA779":"D","\u01F1":"DZ","\u01C4":"DZ","\u01F2":"Dz","\u01C5":"Dz","\u24BA":"E","\uFF25":"E","\u00C8":"E","\u00C9":"E","\u00CA":"E","\u1EC0":"E","\u1EBE":"E","\u1EC4":"E","\u1EC2":"E","\u1EBC":"E","\u0112":"E","\u1E14":"E","\u1E16":"E","\u0114":"E","\u0116":"E","\u00CB":"E","\u1EBA":"E","\u011A":"E","\u0204":"E","\u0206":"E","\u1EB8":"E","\u1EC6":"E","\u0228":"E","\u1E1C":"E","\u0118":"E","\u1E18":"E","\u1E1A":"E","\u0190":"E","\u018E":"E","\u24BB":"F","\uFF26":"F","\u1E1E":"F","\u0191":"F","\uA77B":"F","\u24BC":"G","\uFF27":"G","\u01F4":"G","\u011C":"G","\u1E20":"G","\u011E":"G","\u0120":"G","\u01E6":"G","\u0122":"G","\u01E4":"G","\u0193":"G","\uA7A0":"G","\uA77D":"G","\uA77E":"G","\u24BD":"H","\uFF28":"H","\u0124":"H","\u1E22":"H","\u1E26":"H","\u021E":"H","\u1E24":"H","\u1E28":"H","\u1E2A":"H","\u0126":"H","\u2C67":"H","\u2C75":"H","\uA78D":"H","\u24BE":"I","\uFF29":"I","\u00CC":"I","\u00CD":"I","\u00CE":"I","\u0128":"I","\u012A":"I","\u012C":"I","\u0130":"I","\u00CF":"I","\u1E2E":"I","\u1EC8":"I","\u01CF":"I","\u0208":"I","\u020A":"I","\u1ECA":"I","\u012E":"I","\u1E2C":"I","\u0197":"I","\u24BF":"J","\uFF2A":"J","\u0134":"J","\u0248":"J","\u24C0":"K","\uFF2B":"K","\u1E30":"K","\u01E8":"K","\u1E32":"K","\u0136":"K","\u1E34":"K","\u0198":"K","\u2C69":"K","\uA740":"K","\uA742":"K","\uA744":"K","\uA7A2":"K","\u24C1":"L","\uFF2C":"L","\u013F":"L","\u0139":"L","\u013D":"L","\u1E36":"L","\u1E38":"L","\u013B":"L","\u1E3C":"L","\u1E3A":"L","\u0141":"L","\u023D":"L","\u2C62":"L","\u2C60":"L","\uA748":"L","\uA746":"L","\uA780":"L","\u01C7":"LJ","\u01C8":"Lj","\u24C2":"M","\uFF2D":"M","\u1E3E":"M","\u1E40":"M","\u1E42":"M","\u2C6E":"M","\u019C":"M","\u24C3":"N","\uFF2E":"N","\u01F8":"N","\u0143":"N","\u00D1":"N","\u1E44":"N","\u0147":"N","\u1E46":"N","\u0145":"N","\u1E4A":"N","\u1E48":"N","\u0220":"N","\u019D":"N","\uA790":"N","\uA7A4":"N","\u01CA":"NJ","\u01CB":"Nj","\u24C4":"O","\uFF2F":"O","\u00D2":"O","\u00D3":"O","\u00D4":"O","\u1ED2":"O","\u1ED0":"O","\u1ED6":"O","\u1ED4":"O","\u00D5":"O","\u1E4C":"O","\u022C":"O","\u1E4E":"O","\u014C":"O","\u1E50":"O","\u1E52":"O","\u014E":"O","\u022E":"O","\u0230":"O","\u00D6":"O","\u022A":"O","\u1ECE":"O","\u0150":"O","\u01D1":"O","\u020C":"O","\u020E":"O","\u01A0":"O","\u1EDC":"O","\u1EDA":"O","\u1EE0":"O","\u1EDE":"O","\u1EE2":"O","\u1ECC":"O","\u1ED8":"O","\u01EA":"O","\u01EC":"O","\u00D8":"O","\u01FE":"O","\u0186":"O","\u019F":"O","\uA74A":"O","\uA74C":"O","\u01A2":"OI","\uA74E":"OO","\u0222":"OU","\u24C5":"P","\uFF30":"P","\u1E54":"P","\u1E56":"P","\u01A4":"P","\u2C63":"P","\uA750":"P","\uA752":"P","\uA754":"P","\u24C6":"Q","\uFF31":"Q","\uA756":"Q","\uA758":"Q","\u024A":"Q","\u24C7":"R","\uFF32":"R","\u0154":"R","\u1E58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1E5A":"R","\u1E5C":"R","\u0156":"R","\u1E5E":"R","\u024C":"R","\u2C64":"R","\uA75A":"R","\uA7A6":"R","\uA782":"R","\u24C8":"S","\uFF33":"S","\u1E9E":"S","\u015A":"S","\u1E64":"S","\u015C":"S","\u1E60":"S","\u0160":"S","\u1E66":"S","\u1E62":"S","\u1E68":"S","\u0218":"S","\u015E":"S","\u2C7E":"S","\uA7A8":"S","\uA784":"S","\u24C9":"T","\uFF34":"T","\u1E6A":"T","\u0164":"T","\u1E6C":"T","\u021A":"T","\u0162":"T","\u1E70":"T","\u1E6E":"T","\u0166":"T","\u01AC":"T","\u01AE":"T","\u023E":"T","\uA786":"T","\uA728":"TZ","\u24CA":"U","\uFF35":"U","\u00D9":"U","\u00DA":"U","\u00DB":"U","\u0168":"U","\u1E78":"U","\u016A":"U","\u1E7A":"U","\u016C":"U","\u00DC":"U","\u01DB":"U","\u01D7":"U","\u01D5":"U","\u01D9":"U","\u1EE6":"U","\u016E":"U","\u0170":"U","\u01D3":"U","\u0214":"U","\u0216":"U","\u01AF":"U","\u1EEA":"U","\u1EE8":"U","\u1EEE":"U","\u1EEC":"U","\u1EF0":"U","\u1EE4":"U","\u1E72":"U","\u0172":"U","\u1E76":"U","\u1E74":"U","\u0244":"U","\u24CB":"V","\uFF36":"V","\u1E7C":"V","\u1E7E":"V","\u01B2":"V","\uA75E":"V","\u0245":"V","\uA760":"VY","\u24CC":"W","\uFF37":"W","\u1E80":"W","\u1E82":"W","\u0174":"W","\u1E86":"W","\u1E84":"W","\u1E88":"W","\u2C72":"W","\u24CD":"X","\uFF38":"X","\u1E8A":"X","\u1E8C":"X","\u24CE":"Y","\uFF39":"Y","\u1EF2":"Y","\u00DD":"Y","\u0176":"Y","\u1EF8":"Y","\u0232":"Y","\u1E8E":"Y","\u0178":"Y","\u1EF6":"Y","\u1EF4":"Y","\u01B3":"Y","\u024E":"Y","\u1EFE":"Y","\u24CF":"Z","\uFF3A":"Z","\u0179":"Z","\u1E90":"Z","\u017B":"Z","\u017D":"Z","\u1E92":"Z","\u1E94":"Z","\u01B5":"Z","\u0224":"Z","\u2C7F":"Z","\u2C6B":"Z","\uA762":"Z","\u24D0":"a","\uFF41":"a","\u1E9A":"a","\u00E0":"a","\u00E1":"a","\u00E2":"a","\u1EA7":"a","\u1EA5":"a","\u1EAB":"a","\u1EA9":"a","\u00E3":"a","\u0101":"a","\u0103":"a","\u1EB1":"a","\u1EAF":"a","\u1EB5":"a","\u1EB3":"a","\u0227":"a","\u01E1":"a","\u00E4":"a","\u01DF":"a","\u1EA3":"a","\u00E5":"a","\u01FB":"a","\u01CE":"a","\u0201":"a","\u0203":"a","\u1EA1":"a","\u1EAD":"a","\u1EB7":"a","\u1E01":"a","\u0105":"a","\u2C65":"a","\u0250":"a","\uA733":"aa","\u00E6":"ae","\u01FD":"ae","\u01E3":"ae","\uA735":"ao","\uA737":"au","\uA739":"av","\uA73B":"av","\uA73D":"ay","\u24D1":"b","\uFF42":"b","\u1E03":"b","\u1E05":"b","\u1E07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24D2":"c","\uFF43":"c","\u0107":"c","\u0109":"c","\u010B":"c","\u010D":"c","\u00E7":"c","\u1E09":"c","\u0188":"c","\u023C":"c","\uA73F":"c","\u2184":"c","\u24D3":"d","\uFF44":"d","\u1E0B":"d","\u010F":"d","\u1E0D":"d","\u1E11":"d","\u1E13":"d","\u1E0F":"d","\u0111":"d","\u018C":"d","\u0256":"d","\u0257":"d","\uA77A":"d","\u01F3":"dz","\u01C6":"dz","\u24D4":"e","\uFF45":"e","\u00E8":"e","\u00E9":"e","\u00EA":"e","\u1EC1":"e","\u1EBF":"e","\u1EC5":"e","\u1EC3":"e","\u1EBD":"e","\u0113":"e","\u1E15":"e","\u1E17":"e","\u0115":"e","\u0117":"e","\u00EB":"e","\u1EBB":"e","\u011B":"e","\u0205":"e","\u0207":"e","\u1EB9":"e","\u1EC7":"e","\u0229":"e","\u1E1D":"e","\u0119":"e","\u1E19":"e","\u1E1B":"e","\u0247":"e","\u025B":"e","\u01DD":"e","\u24D5":"f","\uFF46":"f","\u1E1F":"f","\u0192":"f","\uA77C":"f","\u24D6":"g","\uFF47":"g","\u01F5":"g","\u011D":"g","\u1E21":"g","\u011F":"g","\u0121":"g","\u01E7":"g","\u0123":"g","\u01E5":"g","\u0260":"g","\uA7A1":"g","\u1D79":"g","\uA77F":"g","\u24D7":"h","\uFF48":"h","\u0125":"h","\u1E23":"h","\u1E27":"h","\u021F":"h","\u1E25":"h","\u1E29":"h","\u1E2B":"h","\u1E96":"h","\u0127":"h","\u2C68":"h","\u2C76":"h","\u0265":"h","\u0195":"hv","\u24D8":"i","\uFF49":"i","\u00EC":"i","\u00ED":"i","\u00EE":"i","\u0129":"i","\u012B":"i","\u012D":"i","\u00EF":"i","\u1E2F":"i","\u1EC9":"i","\u01D0":"i","\u0209":"i","\u020B":"i","\u1ECB":"i","\u012F":"i","\u1E2D":"i","\u0268":"i","\u0131":"i","\u24D9":"j","\uFF4A":"j","\u0135":"j","\u01F0":"j","\u0249":"j","\u24DA":"k","\uFF4B":"k","\u1E31":"k","\u01E9":"k","\u1E33":"k","\u0137":"k","\u1E35":"k","\u0199":"k","\u2C6A":"k","\uA741":"k","\uA743":"k","\uA745":"k","\uA7A3":"k","\u24DB":"l","\uFF4C":"l","\u0140":"l","\u013A":"l","\u013E":"l","\u1E37":"l","\u1E39":"l","\u013C":"l","\u1E3D":"l","\u1E3B":"l","\u017F":"l","\u0142":"l","\u019A":"l","\u026B":"l","\u2C61":"l","\uA749":"l","\uA781":"l","\uA747":"l","\u01C9":"lj","\u24DC":"m","\uFF4D":"m","\u1E3F":"m","\u1E41":"m","\u1E43":"m","\u0271":"m","\u026F":"m","\u24DD":"n","\uFF4E":"n","\u01F9":"n","\u0144":"n","\u00F1":"n","\u1E45":"n","\u0148":"n","\u1E47":"n","\u0146":"n","\u1E4B":"n","\u1E49":"n","\u019E":"n","\u0272":"n","\u0149":"n","\uA791":"n","\uA7A5":"n","\u01CC":"nj","\u24DE":"o","\uFF4F":"o","\u00F2":"o","\u00F3":"o","\u00F4":"o","\u1ED3":"o","\u1ED1":"o","\u1ED7":"o","\u1ED5":"o","\u00F5":"o","\u1E4D":"o","\u022D":"o","\u1E4F":"o","\u014D":"o","\u1E51":"o","\u1E53":"o","\u014F":"o","\u022F":"o","\u0231":"o","\u00F6":"o","\u022B":"o","\u1ECF":"o","\u0151":"o","\u01D2":"o","\u020D":"o","\u020F":"o","\u01A1":"o","\u1EDD":"o","\u1EDB":"o","\u1EE1":"o","\u1EDF":"o","\u1EE3":"o","\u1ECD":"o","\u1ED9":"o","\u01EB":"o","\u01ED":"o","\u00F8":"o","\u01FF":"o","\u0254":"o","\uA74B":"o","\uA74D":"o","\u0275":"o","\u01A3":"oi","\u0223":"ou","\uA74F":"oo","\u24DF":"p","\uFF50":"p","\u1E55":"p","\u1E57":"p","\u01A5":"p","\u1D7D":"p","\uA751":"p","\uA753":"p","\uA755":"p","\u24E0":"q","\uFF51":"q","\u024B":"q","\uA757":"q","\uA759":"q","\u24E1":"r","\uFF52":"r","\u0155":"r","\u1E59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1E5B":"r","\u1E5D":"r","\u0157":"r","\u1E5F":"r","\u024D":"r","\u027D":"r","\uA75B":"r","\uA7A7":"r","\uA783":"r","\u24E2":"s","\uFF53":"s","\u00DF":"s","\u015B":"s","\u1E65":"s","\u015D":"s","\u1E61":"s","\u0161":"s","\u1E67":"s","\u1E63":"s","\u1E69":"s","\u0219":"s","\u015F":"s","\u023F":"s","\uA7A9":"s","\uA785":"s","\u1E9B":"s","\u24E3":"t","\uFF54":"t","\u1E6B":"t","\u1E97":"t","\u0165":"t","\u1E6D":"t","\u021B":"t","\u0163":"t","\u1E71":"t","\u1E6F":"t","\u0167":"t","\u01AD":"t","\u0288":"t","\u2C66":"t","\uA787":"t","\uA729":"tz","\u24E4":"u","\uFF55":"u","\u00F9":"u","\u00FA":"u","\u00FB":"u","\u0169":"u","\u1E79":"u","\u016B":"u","\u1E7B":"u","\u016D":"u","\u00FC":"u","\u01DC":"u","\u01D8":"u","\u01D6":"u","\u01DA":"u","\u1EE7":"u","\u016F":"u","\u0171":"u","\u01D4":"u","\u0215":"u","\u0217":"u","\u01B0":"u","\u1EEB":"u","\u1EE9":"u","\u1EEF":"u","\u1EED":"u","\u1EF1":"u","\u1EE5":"u","\u1E73":"u","\u0173":"u","\u1E77":"u","\u1E75":"u","\u0289":"u","\u24E5":"v","\uFF56":"v","\u1E7D":"v","\u1E7F":"v","\u028B":"v","\uA75F":"v","\u028C":"v","\uA761":"vy","\u24E6":"w","\uFF57":"w","\u1E81":"w","\u1E83":"w","\u0175":"w","\u1E87":"w","\u1E85":"w","\u1E98":"w","\u1E89":"w","\u2C73":"w","\u24E7":"x","\uFF58":"x","\u1E8B":"x","\u1E8D":"x","\u24E8":"y","\uFF59":"y","\u1EF3":"y","\u00FD":"y","\u0177":"y","\u1EF9":"y","\u0233":"y","\u1E8F":"y","\u00FF":"y","\u1EF7":"y","\u1E99":"y","\u1EF5":"y","\u01B4":"y","\u024F":"y","\u1EFF":"y","\u24E9":"z","\uFF5A":"z","\u017A":"z","\u1E91":"z","\u017C":"z","\u017E":"z","\u1E93":"z","\u1E95":"z","\u01B6":"z","\u0225":"z","\u0240":"z","\u2C6C":"z","\uA763":"z"};
$document = $(document);
nextUid=(function() { var counter=1; return function() { return counter++; }; }());
function reinsertElement(element) {
var placeholder = $(document.createTextNode(''));
element.before(placeholder);
placeholder.before(element);
placeholder.remove();
}
function stripDiacritics(str) {
// Used 'uni range + named function' from http://jsperf.com/diacritics/18
function match(a) {
return DIACRITICS[a] || a;
}
return str.replace(/[^\u0000-\u007E]/g, match);
}
function indexOf(value, array) {
var i = 0, l = array.length;
for (; i < l; i = i + 1) {
if (equal(value, array[i])) return i;
}
return -1;
}
function measureScrollbar () {
var $template = $( MEASURE_SCROLLBAR_TEMPLATE );
$template.appendTo('body');
var dim = {
width: $template.width() - $template[0].clientWidth,
height: $template.height() - $template[0].clientHeight
};
$template.remove();
return dim;
}
/**
* Compares equality of a and b
* @param a
* @param b
*/
function equal(a, b) {
if (a === b) return true;
if (a === undefined || b === undefined) return false;
if (a === null || b === null) return false;
// Check whether 'a' or 'b' is a string (primitive or object).
// The concatenation of an empty string (+'') converts its argument to a string's primitive.
if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object
if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object
return false;
}
/**
* Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
* strings
* @param string
* @param separator
*/
function splitVal(string, separator) {
var val, i, l;
if (string === null || string.length < 1) return [];
val = string.split(separator);
for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
return val;
}
function getSideBorderPadding(element) {
return element.outerWidth(false) - element.width();
}
function installKeyUpChangeEvent(element) {
var key="keyup-change-value";
element.on("keydown", function () {
if ($.data(element, key) === undefined) {
$.data(element, key, element.val());
}
});
element.on("keyup", function () {
var val= $.data(element, key);
if (val !== undefined && element.val() !== val) {
$.removeData(element, key);
element.trigger("keyup-change");
}
});
}
$document.on("mousemove", function (e) {
lastMousePosition.x = e.pageX;
lastMousePosition.y = e.pageY;
});
/**
* filters mouse events so an event is fired only if the mouse moved.
*
* filters out mouse events that occur when mouse is stationary but
* the elements under the pointer are scrolled.
*/
function installFilteredMouseMove(element) {
element.on("mousemove", function (e) {
var lastpos = lastMousePosition;
if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
$(e.target).trigger("mousemove-filtered", e);
}
});
}
/**
* Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
* within the last quietMillis milliseconds.
*
* @param quietMillis number of milliseconds to wait before invoking fn
* @param fn function to be debounced
* @param ctx object to be used as this reference within fn
* @return debounced version of fn
*/
function debounce(quietMillis, fn, ctx) {
ctx = ctx || undefined;
var timeout;
return function () {
var args = arguments;
window.clearTimeout(timeout);
timeout = window.setTimeout(function() {
fn.apply(ctx, args);
}, quietMillis);
};
}
function installDebouncedScroll(threshold, element) {
var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
element.on("scroll", function (e) {
if (indexOf(e.target, element.get()) >= 0) notify(e);
});
}
function focus($el) {
if ($el[0] === document.activeElement) return;
/* set the focus in a 0 timeout - that way the focus is set after the processing
of the current event has finished - which seems like the only reliable way
to set focus */
window.setTimeout(function() {
var el=$el[0], pos=$el.val().length, range;
$el.focus();
/* make sure el received focus so we do not error out when trying to manipulate the caret.
sometimes modals or others listeners may steal it after its set */
var isVisible = (el.offsetWidth > 0 || el.offsetHeight > 0);
if (isVisible && el === document.activeElement) {
/* after the focus is set move the caret to the end, necessary when we val()
just before setting focus */
if(el.setSelectionRange)
{
el.setSelectionRange(pos, pos);
}
else if (el.createTextRange) {
range = el.createTextRange();
range.collapse(false);
range.select();
}
}
}, 0);
}
function getCursorInfo(el) {
el = $(el)[0];
var offset = 0;
var length = 0;
if ('selectionStart' in el) {
offset = el.selectionStart;
length = el.selectionEnd - offset;
} else if ('selection' in document) {
el.focus();
var sel = document.selection.createRange();
length = document.selection.createRange().text.length;
sel.moveStart('character', -el.value.length);
offset = sel.text.length - length;
}
return { offset: offset, length: length };
}
function killEvent(event) {
event.preventDefault();
event.stopPropagation();
}
function killEventImmediately(event) {
event.preventDefault();
event.stopImmediatePropagation();
}
function measureTextWidth(e) {
if (!sizer){
var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
sizer = $(document.createElement("div")).css({
position: "absolute",
left: "-10000px",
top: "-10000px",
display: "none",
fontSize: style.fontSize,
fontFamily: style.fontFamily,
fontStyle: style.fontStyle,
fontWeight: style.fontWeight,
letterSpacing: style.letterSpacing,
textTransform: style.textTransform,
whiteSpace: "nowrap"
});
sizer.attr("class","select2-sizer");
$("body").append(sizer);
}
sizer.text(e.val());
return sizer.width();
}
function syncCssClasses(dest, src, adapter) {
var classes, replacements = [], adapted;
classes = dest.attr("class");
if (classes) {
classes = '' + classes; // for IE which returns object
$(classes.split(" ")).each2(function() {
if (this.indexOf("select2-") === 0) {
replacements.push(this);
}
});
}
classes = src.attr("class");
if (classes) {
classes = '' + classes; // for IE which returns object
$(classes.split(" ")).each2(function() {
if (this.indexOf("select2-") !== 0) {
adapted = adapter(this);
if (adapted) {
replacements.push(adapted);
}
}
});
}
dest.attr("class", replacements.join(" "));
}
function markMatch(text, term, markup, escapeMarkup) {
var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())),
tl=term.length;
if (match<0) {
markup.push(escapeMarkup(text));
return;
}
markup.push(escapeMarkup(text.substring(0, match)));
markup.push("");
markup.push(escapeMarkup(text.substring(match, match + tl)));
markup.push(" ");
markup.push(escapeMarkup(text.substring(match + tl, text.length)));
}
function defaultEscapeMarkup(markup) {
var replace_map = {
'\\': '\',
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
"/": '/'
};
return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
return replace_map[match];
});
}
/**
* Produces an ajax-based query function
*
* @param options object containing configuration parameters
* @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax
* @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
* @param options.url url for the data
* @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
* @param options.dataType request data type: ajax, jsonp, other datatypes supported by jQuery's $.ajax function or the transport function if specified
* @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
* @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
* The expected format is an object containing the following keys:
* results array of objects that will be used as choices
* more (optional) boolean indicating whether there are more results available
* Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
*/
function ajax(options) {
var timeout, // current scheduled but not yet executed request
handler = null,
quietMillis = options.quietMillis || 100,
ajaxUrl = options.url,
self = this;
return function (query) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
var data = options.data, // ajax data function
url = ajaxUrl, // ajax url string or function
transport = options.transport || $.fn.select2.ajaxDefaults.transport,
// deprecated - to be removed in 4.0 - use params instead
deprecated = {
type: options.type || 'GET', // set type of request (GET or POST)
cache: options.cache || false,
jsonpCallback: options.jsonpCallback||undefined,
dataType: options.dataType||"json"
},
params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
data = data ? data.call(self, query.term, query.page, query.context) : null;
url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
if (handler && typeof handler.abort === "function") { handler.abort(); }
if (options.params) {
if ($.isFunction(options.params)) {
$.extend(params, options.params.call(self));
} else {
$.extend(params, options.params);
}
}
$.extend(params, {
url: url,
dataType: options.dataType,
data: data,
success: function (data) {
// TODO - replace query.page with query so users have access to term, page, etc.
var results = options.results(data, query.page);
query.callback(results);
}
});
handler = transport.call(self, params);
}, quietMillis);
};
}
/**
* Produces a query function that works with a local array
*
* @param options object containing configuration parameters. The options parameter can either be an array or an
* object.
*
* If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
*
* If the object form is used it is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
* an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
* key can either be a String in which case it is expected that each element in the 'data' array has a key with the
* value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
* the text.
*/
function local(options) {
var data = options, // data elements
dataText,
tmp,
text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
if ($.isArray(data)) {
tmp = data;
data = { results: tmp };
}
if ($.isFunction(data) === false) {
tmp = data;
data = function() { return tmp; };
}
var dataItem = data();
if (dataItem.text) {
text = dataItem.text;
// if text is not a function we assume it to be a key name
if (!$.isFunction(text)) {
dataText = dataItem.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available
text = function (item) { return item[dataText]; };
}
}
return function (query) {
var t = query.term, filtered = { results: [] }, process;
if (t === "") {
query.callback(data());
return;
}
process = function(datum, collection) {
var group, attr;
datum = datum[0];
if (datum.children) {
group = {};
for (attr in datum) {
if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
}
group.children=[];
$(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
if (group.children.length || query.matcher(t, text(group), datum)) {
collection.push(group);
}
} else {
if (query.matcher(t, text(datum), datum)) {
collection.push(datum);
}
}
};
$(data().results).each2(function(i, datum) { process(datum, filtered.results); });
query.callback(filtered);
};
}
// TODO javadoc
function tags(data) {
var isFunc = $.isFunction(data);
return function (query) {
var t = query.term, filtered = {results: []};
var result = isFunc ? data(query) : data;
if ($.isArray(result)) {
$(result).each(function () {
var isObject = this.text !== undefined,
text = isObject ? this.text : this;
if (t === "" || query.matcher(t, text)) {
filtered.results.push(isObject ? this : {id: this, text: this});
}
});
query.callback(filtered);
}
};
}
/**
* Checks if the formatter function should be used.
*
* Throws an error if it is not a function. Returns true if it should be used,
* false if no formatting should be performed.
*
* @param formatter
*/
function checkFormatter(formatter, formatterName) {
if ($.isFunction(formatter)) return true;
if (!formatter) return false;
if (typeof(formatter) === 'string') return true;
throw new Error(formatterName +" must be a string, function, or falsy value");
}
function evaluate(val) {
if ($.isFunction(val)) {
var args = Array.prototype.slice.call(arguments, 1);
return val.apply(null, args);
}
return val;
}
function countResults(results) {
var count = 0;
$.each(results, function(i, item) {
if (item.children) {
count += countResults(item.children);
} else {
count++;
}
});
return count;
}
/**
* Default tokenizer. This function uses breaks the input on substring match of any string from the
* opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
* two options have to be defined in order for the tokenizer to work.
*
* @param input text user has typed so far or pasted into the search field
* @param selection currently selected choices
* @param selectCallback function(choice) callback tho add the choice to selection
* @param opts select2's opts
* @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
*/
function defaultTokenizer(input, selection, selectCallback, opts) {
var original = input, // store the original so we can compare and know if we need to tell the search to update its text
dupe = false, // check for whether a token we extracted represents a duplicate selected choice
token, // token
index, // position at which the separator was found
i, l, // looping variables
separator; // the matched separator
if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
while (true) {
index = -1;
for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
separator = opts.tokenSeparators[i];
index = input.indexOf(separator);
if (index >= 0) break;
}
if (index < 0) break; // did not find any token separator in the input string, bail
token = input.substring(0, index);
input = input.substring(index + separator.length);
if (token.length > 0) {
token = opts.createSearchChoice.call(this, token, selection);
if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
dupe = false;
for (i = 0, l = selection.length; i < l; i++) {
if (equal(opts.id(token), opts.id(selection[i]))) {
dupe = true; break;
}
}
if (!dupe) selectCallback(token);
}
}
}
if (original!==input) return input;
}
function cleanupJQueryElements() {
var self = this;
Array.prototype.forEach.call(arguments, function (element) {
self[element].remove();
self[element] = null;
});
}
/**
* Creates a new class
*
* @param superClass
* @param methods
*/
function clazz(SuperClass, methods) {
var constructor = function () {};
constructor.prototype = new SuperClass;
constructor.prototype.constructor = constructor;
constructor.prototype.parent = SuperClass.prototype;
constructor.prototype = $.extend(constructor.prototype, methods);
return constructor;
}
AbstractSelect2 = clazz(Object, {
// abstract
bind: function (func) {
var self = this;
return function () {
func.apply(self, arguments);
};
},
// abstract
init: function (opts) {
var results, search, resultsSelector = ".select2-results";
// prepare options
this.opts = opts = this.prepareOpts(opts);
this.id=opts.id;
// destroy if called on an existing component
if (opts.element.data("select2") !== undefined &&
opts.element.data("select2") !== null) {
opts.element.data("select2").destroy();
}
this.container = this.createContainer();
this.liveRegion = $("", {
role: "status",
"aria-live": "polite"
})
.addClass("select2-hidden-accessible")
.appendTo(document.body);
this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
this.containerEventName= this.containerId
.replace(/([.])/g, '_')
.replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
this.container.attr("id", this.containerId);
this.container.attr("title", opts.element.attr("title"));
this.body = $("body");
syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
this.container.attr("style", opts.element.attr("style"));
this.container.css(evaluate(opts.containerCss));
this.container.addClass(evaluate(opts.containerCssClass));
this.elementTabIndex = this.opts.element.attr("tabindex");
// swap container for the element
this.opts.element
.data("select2", this)
.attr("tabindex", "-1")
.before(this.container)
.on("click.select2", killEvent); // do not leak click events
this.container.data("select2", this);
this.dropdown = this.container.find(".select2-drop");
syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
this.dropdown.addClass(evaluate(opts.dropdownCssClass));
this.dropdown.data("select2", this);
this.dropdown.on("click", killEvent);
this.results = results = this.container.find(resultsSelector);
this.search = search = this.container.find("input.select2-input");
this.queryCount = 0;
this.resultsPage = 0;
this.context = null;
// initialize the container
this.initContainer();
this.container.on("click", killEvent);
installFilteredMouseMove(this.results);
this.dropdown.on("mousemove-filtered", resultsSelector, this.bind(this.highlightUnderEvent));
this.dropdown.on("touchstart touchmove touchend", resultsSelector, this.bind(function (event) {
this._touchEvent = true;
this.highlightUnderEvent(event);
}));
this.dropdown.on("touchmove", resultsSelector, this.bind(this.touchMoved));
this.dropdown.on("touchstart touchend", resultsSelector, this.bind(this.clearTouchMoved));
// Waiting for a click event on touch devices to select option and hide dropdown
// otherwise click will be triggered on an underlying element
this.dropdown.on('click', this.bind(function (event) {
if (this._touchEvent) {
this._touchEvent = false;
this.selectHighlighted();
}
}));
installDebouncedScroll(80, this.results);
this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded));
// do not propagate change event from the search field out of the component
$(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();});
$(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();});
// if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
if ($.fn.mousewheel) {
results.mousewheel(function (e, delta, deltaX, deltaY) {
var top = results.scrollTop();
if (deltaY > 0 && top - deltaY <= 0) {
results.scrollTop(0);
killEvent(e);
} else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
results.scrollTop(results.get(0).scrollHeight - results.height());
killEvent(e);
}
});
}
installKeyUpChangeEvent(search);
search.on("keyup-change input paste", this.bind(this.updateResults));
search.on("focus", function () { search.addClass("select2-focused"); });
search.on("blur", function () { search.removeClass("select2-focused");});
this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) {
if ($(e.target).closest(".select2-result-selectable").length > 0) {
this.highlightUnderEvent(e);
this.selectHighlighted(e);
}
}));
// trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
// for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
// dom it will trigger the popup close, which is not what we want
// focusin can cause focus wars between modals and select2 since the dropdown is outside the modal.
this.dropdown.on("click mouseup mousedown touchstart touchend focusin", function (e) { e.stopPropagation(); });
this.nextSearchTerm = undefined;
if ($.isFunction(this.opts.initSelection)) {
// initialize selection based on the current value of the source element
this.initSelection();
// if the user has provided a function that can set selection based on the value of the source element
// we monitor the change event on the element and trigger it, allowing for two way synchronization
this.monitorSource();
}
if (opts.maximumInputLength !== null) {
this.search.attr("maxlength", opts.maximumInputLength);
}
var disabled = opts.element.prop("disabled");
if (disabled === undefined) disabled = false;
this.enable(!disabled);
var readonly = opts.element.prop("readonly");
if (readonly === undefined) readonly = false;
this.readonly(readonly);
// Calculate size of scrollbar
scrollBarDimensions = scrollBarDimensions || measureScrollbar();
this.autofocus = opts.element.prop("autofocus");
opts.element.prop("autofocus", false);
if (this.autofocus) this.focus();
this.search.attr("placeholder", opts.searchInputPlaceholder);
},
// abstract
destroy: function () {
var element=this.opts.element, select2 = element.data("select2");
this.close();
if (this.propertyObserver) {
this.propertyObserver.disconnect();
this.propertyObserver = null;
}
if (select2 !== undefined) {
select2.container.remove();
select2.liveRegion.remove();
select2.dropdown.remove();
element
.removeClass("select2-offscreen")
.removeData("select2")
.off(".select2")
.prop("autofocus", this.autofocus || false);
if (this.elementTabIndex) {
element.attr({tabindex: this.elementTabIndex});
} else {
element.removeAttr("tabindex");
}
element.show();
}
cleanupJQueryElements.call(this,
"container",
"liveRegion",
"dropdown",
"results",
"search"
);
},
// abstract
optionToData: function(element) {
if (element.is("option")) {
return {
id:element.prop("value"),
text:element.text(),
element: element.get(),
css: element.attr("class"),
disabled: element.prop("disabled"),
locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true)
};
} else if (element.is("optgroup")) {
return {
text:element.attr("label"),
children:[],
element: element.get(),
css: element.attr("class")
};
}
},
// abstract
prepareOpts: function (opts) {
var element, select, idKey, ajaxUrl, self = this;
element = opts.element;
if (element.get(0).tagName.toLowerCase() === "select") {
this.select = select = opts.element;
}
if (select) {
// these options are not allowed when attached to a select because they are picked up off the element itself
$.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
if (this in opts) {
throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a element.");
}
});
}
opts = $.extend({}, {
populateResults: function(container, results, query) {
var populate, id=this.opts.id, liveRegion=this.liveRegion;
populate=function(results, container, depth) {
var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
results = opts.sortResults(results, container, query);
for (i = 0, l = results.length; i < l; i = i + 1) {
result=results[i];
disabled = (result.disabled === true);
selectable = (!disabled) && (id(result) !== undefined);
compound=result.children && result.children.length > 0;
node=$(" ");
node.addClass("select2-results-dept-"+depth);
node.addClass("select2-result");
node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
if (disabled) { node.addClass("select2-disabled"); }
if (compound) { node.addClass("select2-result-with-children"); }
node.addClass(self.opts.formatResultCssClass(result));
node.attr("role", "presentation");
label=$(document.createElement("div"));
label.addClass("select2-result-label");
label.attr("id", "select2-result-label-" + nextUid());
label.attr("role", "option");
formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
if (formatted!==undefined) {
label.html(formatted);
node.append(label);
}
if (compound) {
innerContainer=$("");
innerContainer.addClass("select2-result-sub");
populate(result.children, innerContainer, depth+1);
node.append(innerContainer);
}
node.data("select2-data", result);
container.append(node);
}
liveRegion.text(opts.formatMatches(results.length));
};
populate(results, container, 0);
}
}, $.fn.select2.defaults, opts);
if (typeof(opts.id) !== "function") {
idKey = opts.id;
opts.id = function (e) { return e[idKey]; };
}
if ($.isArray(opts.element.data("select2Tags"))) {
if ("tags" in opts) {
throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
}
opts.tags=opts.element.data("select2Tags");
}
if (select) {
opts.query = this.bind(function (query) {
var data = { results: [], more: false },
term = query.term,
children, placeholderOption, process;
process=function(element, collection) {
var group;
if (element.is("option")) {
if (query.matcher(term, element.text(), element)) {
collection.push(self.optionToData(element));
}
} else if (element.is("optgroup")) {
group=self.optionToData(element);
element.children().each2(function(i, elm) { process(elm, group.children); });
if (group.children.length>0) {
collection.push(group);
}
}
};
children=element.children();
// ignore the placeholder option if there is one
if (this.getPlaceholder() !== undefined && children.length > 0) {
placeholderOption = this.getPlaceholderOption();
if (placeholderOption) {
children=children.not(placeholderOption);
}
}
children.each2(function(i, elm) { process(elm, data.results); });
query.callback(data);
});
// this is needed because inside val() we construct choices from options and there id is hardcoded
opts.id=function(e) { return e.id; };
} else {
if (!("query" in opts)) {
if ("ajax" in opts) {
ajaxUrl = opts.element.data("ajax-url");
if (ajaxUrl && ajaxUrl.length > 0) {
opts.ajax.url = ajaxUrl;
}
opts.query = ajax.call(opts.element, opts.ajax);
} else if ("data" in opts) {
opts.query = local(opts.data);
} else if ("tags" in opts) {
opts.query = tags(opts.tags);
if (opts.createSearchChoice === undefined) {
opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; };
}
if (opts.initSelection === undefined) {
opts.initSelection = function (element, callback) {
var data = [];
$(splitVal(element.val(), opts.separator)).each(function () {
var obj = { id: this, text: this },
tags = opts.tags;
if ($.isFunction(tags)) tags=tags();
$(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } });
data.push(obj);
});
callback(data);
};
}
}
}
}
if (typeof(opts.query) !== "function") {
throw "query function not defined for Select2 " + opts.element.attr("id");
}
if (opts.createSearchChoicePosition === 'top') {
opts.createSearchChoicePosition = function(list, item) { list.unshift(item); };
}
else if (opts.createSearchChoicePosition === 'bottom') {
opts.createSearchChoicePosition = function(list, item) { list.push(item); };
}
else if (typeof(opts.createSearchChoicePosition) !== "function") {
throw "invalid createSearchChoicePosition option must be 'top', 'bottom' or a custom function";
}
return opts;
},
/**
* Monitor the original element for changes and update select2 accordingly
*/
// abstract
monitorSource: function () {
var el = this.opts.element, sync, observer;
el.on("change.select2", this.bind(function (e) {
if (this.opts.element.data("select2-change-triggered") !== true) {
this.initSelection();
}
}));
sync = this.bind(function () {
// sync enabled state
var disabled = el.prop("disabled");
if (disabled === undefined) disabled = false;
this.enable(!disabled);
var readonly = el.prop("readonly");
if (readonly === undefined) readonly = false;
this.readonly(readonly);
syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
this.container.addClass(evaluate(this.opts.containerCssClass));
syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
this.dropdown.addClass(evaluate(this.opts.dropdownCssClass));
});
// IE8-10 (IE9/10 won't fire propertyChange via attachEventListener)
if (el.length && el[0].attachEvent) {
el.each(function() {
this.attachEvent("onpropertychange", sync);
});
}
// safari, chrome, firefox, IE11
observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver;
if (observer !== undefined) {
if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
this.propertyObserver = new observer(function (mutations) {
mutations.forEach(sync);
});
this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
}
},
// abstract
triggerSelect: function(data) {
var evt = $.Event("select2-selecting", { val: this.id(data), object: data });
this.opts.element.trigger(evt);
return !evt.isDefaultPrevented();
},
/**
* Triggers the change event on the source element
*/
// abstract
triggerChange: function (details) {
details = details || {};
details= $.extend({}, details, { type: "change", val: this.val() });
// prevents recursive triggering
this.opts.element.data("select2-change-triggered", true);
this.opts.element.trigger(details);
this.opts.element.data("select2-change-triggered", false);
// some validation frameworks ignore the change event and listen instead to keyup, click for selects
// so here we trigger the click event manually
this.opts.element.click();
// ValidationEngine ignores the change event and listens instead to blur
// so here we trigger the blur event manually if so desired
if (this.opts.blurOnChange)
this.opts.element.blur();
},
//abstract
isInterfaceEnabled: function()
{
return this.enabledInterface === true;
},
// abstract
enableInterface: function() {
var enabled = this._enabled && !this._readonly,
disabled = !enabled;
if (enabled === this.enabledInterface) return false;
this.container.toggleClass("select2-container-disabled", disabled);
this.close();
this.enabledInterface = enabled;
return true;
},
// abstract
enable: function(enabled) {
if (enabled === undefined) enabled = true;
if (this._enabled === enabled) return;
this._enabled = enabled;
this.opts.element.prop("disabled", !enabled);
this.enableInterface();
},
// abstract
disable: function() {
this.enable(false);
},
// abstract
readonly: function(enabled) {
if (enabled === undefined) enabled = false;
if (this._readonly === enabled) return;
this._readonly = enabled;
this.opts.element.prop("readonly", enabled);
this.enableInterface();
},
// abstract
opened: function () {
return this.container.hasClass("select2-dropdown-open");
},
// abstract
positionDropdown: function() {
var $dropdown = this.dropdown,
offset = this.container.offset(),
height = this.container.outerHeight(false),
width = this.container.outerWidth(false),
dropHeight = $dropdown.outerHeight(false),
$window = $(window),
windowWidth = $window.width(),
windowHeight = $window.height(),
viewPortRight = $window.scrollLeft() + windowWidth,
viewportBottom = $window.scrollTop() + windowHeight,
dropTop = offset.top + height,
dropLeft = offset.left,
enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
enoughRoomAbove = (offset.top - dropHeight) >= $window.scrollTop(),
dropWidth = $dropdown.outerWidth(false),
enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
aboveNow = $dropdown.hasClass("select2-drop-above"),
bodyOffset,
above,
changeDirection,
css,
resultsListNode;
// always prefer the current above/below alignment, unless there is not enough room
if (aboveNow) {
above = true;
if (!enoughRoomAbove && enoughRoomBelow) {
changeDirection = true;
above = false;
}
} else {
above = false;
if (!enoughRoomBelow && enoughRoomAbove) {
changeDirection = true;
above = true;
}
}
//if we are changing direction we need to get positions when dropdown is hidden;
if (changeDirection) {
$dropdown.hide();
offset = this.container.offset();
height = this.container.outerHeight(false);
width = this.container.outerWidth(false);
dropHeight = $dropdown.outerHeight(false);
viewPortRight = $window.scrollLeft() + windowWidth;
viewportBottom = $window.scrollTop() + windowHeight;
dropTop = offset.top + height;
dropLeft = offset.left;
dropWidth = $dropdown.outerWidth(false);
enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
$dropdown.show();
// fix so the cursor does not move to the left within the search-textbox in IE
this.focusSearch();
}
if (this.opts.dropdownAutoWidth) {
resultsListNode = $('.select2-results', $dropdown)[0];
$dropdown.addClass('select2-drop-auto-width');
$dropdown.css('width', '');
// Add scrollbar width to dropdown if vertical scrollbar is present
dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
dropWidth > width ? width = dropWidth : dropWidth = width;
dropHeight = $dropdown.outerHeight(false);
enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
}
else {
this.container.removeClass('select2-drop-auto-width');
}
//console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
//console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body.scrollTop(), "enough?", enoughRoomAbove);
// fix positioning when body has an offset and is not position: static
if (this.body.css('position') !== 'static') {
bodyOffset = this.body.offset();
dropTop -= bodyOffset.top;
dropLeft -= bodyOffset.left;
}
if (!enoughRoomOnRight) {
dropLeft = offset.left + this.container.outerWidth(false) - dropWidth;
}
css = {
left: dropLeft,
width: width
};
if (above) {
css.top = offset.top - dropHeight;
css.bottom = 'auto';
this.container.addClass("select2-drop-above");
$dropdown.addClass("select2-drop-above");
}
else {
css.top = dropTop;
css.bottom = 'auto';
this.container.removeClass("select2-drop-above");
$dropdown.removeClass("select2-drop-above");
}
css = $.extend(css, evaluate(this.opts.dropdownCss));
$dropdown.css(css);
},
// abstract
shouldOpen: function() {
var event;
if (this.opened()) return false;
if (this._enabled === false || this._readonly === true) return false;
event = $.Event("select2-opening");
this.opts.element.trigger(event);
return !event.isDefaultPrevented();
},
// abstract
clearDropdownAlignmentPreference: function() {
// clear the classes used to figure out the preference of where the dropdown should be opened
this.container.removeClass("select2-drop-above");
this.dropdown.removeClass("select2-drop-above");
},
/**
* Opens the dropdown
*
* @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
* the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
*/
// abstract
open: function () {
if (!this.shouldOpen()) return false;
this.opening();
return true;
},
/**
* Performs the opening of the dropdown
*/
// abstract
opening: function() {
var cid = this.containerEventName,
scroll = "scroll." + cid,
resize = "resize."+cid,
orient = "orientationchange."+cid,
mask;
this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
this.clearDropdownAlignmentPreference();
if(this.dropdown[0] !== this.body.children().last()[0]) {
this.dropdown.detach().appendTo(this.body);
}
// create the dropdown mask if doesn't already exist
mask = $("#select2-drop-mask");
if (mask.length == 0) {
mask = $(document.createElement("div"));
mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
mask.hide();
mask.appendTo(this.body);
mask.on("mousedown touchstart click", function (e) {
// Prevent IE from generating a click event on the body
reinsertElement(mask);
var dropdown = $("#select2-drop"), self;
if (dropdown.length > 0) {
self=dropdown.data("select2");
if (self.opts.selectOnBlur) {
self.selectHighlighted({noFocus: true});
}
self.close();
e.preventDefault();
e.stopPropagation();
}
});
}
// ensure the mask is always right before the dropdown
if (this.dropdown.prev()[0] !== mask[0]) {
this.dropdown.before(mask);
}
// move the global id to the correct dropdown
$("#select2-drop").removeAttr("id");
this.dropdown.attr("id", "select2-drop");
// show the elements
mask.show();
this.positionDropdown();
this.dropdown.show();
this.positionDropdown();
this.dropdown.addClass("select2-drop-active");
// attach listeners to events that can change the position of the container and thus require
// the position of the dropdown to be updated as well so it does not come unglued from the container
var that = this;
this.container.parents().add(window).each(function () {
$(this).on(resize+" "+scroll+" "+orient, function (e) {
if (that.opened()) that.positionDropdown();
});
});
},
// abstract
close: function () {
if (!this.opened()) return;
var cid = this.containerEventName,
scroll = "scroll." + cid,
resize = "resize."+cid,
orient = "orientationchange."+cid;
// unbind event listeners
this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); });
this.clearDropdownAlignmentPreference();
$("#select2-drop-mask").hide();
this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
this.dropdown.hide();
this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
this.results.empty();
this.clearSearch();
this.search.removeClass("select2-active");
this.opts.element.trigger($.Event("select2-close"));
},
/**
* Opens control, sets input value, and updates results.
*/
// abstract
externalSearch: function (term) {
this.open();
this.search.val(term);
this.updateResults(false);
},
// abstract
clearSearch: function () {
},
//abstract
getMaximumSelectionSize: function() {
return evaluate(this.opts.maximumSelectionSize);
},
// abstract
ensureHighlightVisible: function () {
var results = this.results, children, index, child, hb, rb, y, more;
index = this.highlight();
if (index < 0) return;
if (index == 0) {
// if the first element is highlighted scroll all the way to the top,
// that way any unselectable headers above it will also be scrolled
// into view
results.scrollTop(0);
return;
}
children = this.findHighlightableChoices().find('.select2-result-label');
child = $(children[index]);
hb = child.offset().top + child.outerHeight(true);
// if this is the last child lets also make sure select2-more-results is visible
if (index === children.length - 1) {
more = results.find("li.select2-more-results");
if (more.length > 0) {
hb = more.offset().top + more.outerHeight(true);
}
}
rb = results.offset().top + results.outerHeight(true);
if (hb > rb) {
results.scrollTop(results.scrollTop() + (hb - rb));
}
y = child.offset().top - results.offset().top;
// make sure the top of the element is visible
if (y < 0 && child.css('display') != 'none' ) {
results.scrollTop(results.scrollTop() + y); // y is negative
}
},
// abstract
findHighlightableChoices: function() {
return this.results.find(".select2-result-selectable:not(.select2-disabled):not(.select2-selected)");
},
// abstract
moveHighlight: function (delta) {
var choices = this.findHighlightableChoices(),
index = this.highlight();
while (index > -1 && index < choices.length) {
index += delta;
var choice = $(choices[index]);
if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
this.highlight(index);
break;
}
}
},
// abstract
highlight: function (index) {
var choices = this.findHighlightableChoices(),
choice,
data;
if (arguments.length === 0) {
return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
}
if (index >= choices.length) index = choices.length - 1;
if (index < 0) index = 0;
this.removeHighlight();
choice = $(choices[index]);
choice.addClass("select2-highlighted");
// ensure assistive technology can determine the active choice
this.search.attr("aria-activedescendant", choice.find(".select2-result-label").attr("id"));
this.ensureHighlightVisible();
this.liveRegion.text(choice.text());
data = choice.data("select2-data");
if (data) {
this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data });
}
},
removeHighlight: function() {
this.results.find(".select2-highlighted").removeClass("select2-highlighted");
},
touchMoved: function() {
this._touchMoved = true;
},
clearTouchMoved: function() {
this._touchMoved = false;
},
// abstract
countSelectableResults: function() {
return this.findHighlightableChoices().length;
},
// abstract
highlightUnderEvent: function (event) {
var el = $(event.target).closest(".select2-result-selectable");
if (el.length > 0 && !el.is(".select2-highlighted")) {
var choices = this.findHighlightableChoices();
this.highlight(choices.index(el));
} else if (el.length == 0) {
// if we are over an unselectable item remove all highlights
this.removeHighlight();
}
},
// abstract
loadMoreIfNeeded: function () {
var results = this.results,
more = results.find("li.select2-more-results"),
below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
page = this.resultsPage + 1,
self=this,
term=this.search.val(),
context=this.context;
if (more.length === 0) return;
below = more.offset().top - results.offset().top - results.height();
if (below <= this.opts.loadMorePadding) {
more.addClass("select2-active");
this.opts.query({
element: this.opts.element,
term: term,
page: page,
context: context,
matcher: this.opts.matcher,
callback: this.bind(function (data) {
// ignore a response if the select2 has been closed before it was received
if (!self.opened()) return;
self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
self.postprocessResults(data, false, false);
if (data.more===true) {
more.detach().appendTo(results).text(evaluate(self.opts.formatLoadMore, page+1));
window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
} else {
more.remove();
}
self.positionDropdown();
self.resultsPage = page;
self.context = data.context;
this.opts.element.trigger({ type: "select2-loaded", items: data });
})});
}
},
/**
* Default tokenizer function which does nothing
*/
tokenize: function() {
},
/**
* @param initial whether or not this is the call to this method right after the dropdown has been opened
*/
// abstract
updateResults: function (initial) {
var search = this.search,
results = this.results,
opts = this.opts,
data,
self = this,
input,
term = search.val(),
lastTerm = $.data(this.container, "select2-last-term"),
// sequence number used to drop out-of-order responses
queryNumber;
// prevent duplicate queries against the same term
if (initial !== true && lastTerm && equal(term, lastTerm)) return;
$.data(this.container, "select2-last-term", term);
// if the search is currently hidden we do not alter the results
if (initial !== true && (this.showSearchInput === false || !this.opened())) {
return;
}
function postRender() {
search.removeClass("select2-active");
self.positionDropdown();
if (results.find('.select2-no-results,.select2-selection-limit,.select2-searching').length) {
self.liveRegion.text(results.text());
}
else {
self.liveRegion.text(self.opts.formatMatches(results.find('.select2-result-selectable').length));
}
}
function render(html) {
results.html(html);
postRender();
}
queryNumber = ++this.queryCount;
var maxSelSize = this.getMaximumSelectionSize();
if (maxSelSize >=1) {
data = this.data();
if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
render("" + evaluate(opts.formatSelectionTooBig, maxSelSize) + " ");
return;
}
}
if (search.val().length < opts.minimumInputLength) {
if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
render("" + evaluate(opts.formatInputTooShort, search.val(), opts.minimumInputLength) + " ");
} else {
render("");
}
if (initial && this.showSearch) this.showSearch(true);
return;
}
if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
render("" + evaluate(opts.formatInputTooLong, search.val(), opts.maximumInputLength) + " ");
} else {
render("");
}
return;
}
if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
render("" + evaluate(opts.formatSearching) + " ");
}
search.addClass("select2-active");
this.removeHighlight();
// give the tokenizer a chance to pre-process the input
input = this.tokenize();
if (input != undefined && input != null) {
search.val(input);
}
this.resultsPage = 1;
opts.query({
element: opts.element,
term: search.val(),
page: this.resultsPage,
context: null,
matcher: opts.matcher,
callback: this.bind(function (data) {
var def; // default choice
// ignore old responses
if (queryNumber != this.queryCount) {
return;
}
// ignore a response if the select2 has been closed before it was received
if (!this.opened()) {
this.search.removeClass("select2-active");
return;
}
// save context, if any
this.context = (data.context===undefined) ? null : data.context;
// create a default choice and prepend it to the list
if (this.opts.createSearchChoice && search.val() !== "") {
def = this.opts.createSearchChoice.call(self, search.val(), data.results);
if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
if ($(data.results).filter(
function () {
return equal(self.id(this), self.id(def));
}).length === 0) {
this.opts.createSearchChoicePosition(data.results, def);
}
}
}
if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
render("" + evaluate(opts.formatNoMatches, search.val()) + " ");
return;
}
results.empty();
self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
results.append("" + self.opts.escapeMarkup(evaluate(opts.formatLoadMore, this.resultsPage)) + " ");
window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
}
this.postprocessResults(data, initial);
postRender();
this.opts.element.trigger({ type: "select2-loaded", items: data });
})});
},
// abstract
cancel: function () {
this.close();
},
// abstract
blur: function () {
// if selectOnBlur == true, select the currently highlighted option
if (this.opts.selectOnBlur)
this.selectHighlighted({noFocus: true});
this.close();
this.container.removeClass("select2-container-active");
// synonymous to .is(':focus'), which is available in jquery >= 1.6
if (this.search[0] === document.activeElement) { this.search.blur(); }
this.clearSearch();
this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
},
// abstract
focusSearch: function () {
focus(this.search);
},
// abstract
selectHighlighted: function (options) {
if (this._touchMoved) {
this.clearTouchMoved();
return;
}
var index=this.highlight(),
highlighted=this.results.find(".select2-highlighted"),
data = highlighted.closest('.select2-result').data("select2-data");
if (data) {
this.highlight(index);
this.onSelect(data, options);
} else if (options && options.noFocus) {
this.close();
}
},
// abstract
getPlaceholder: function () {
var placeholderOption;
return this.opts.element.attr("placeholder") ||
this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
this.opts.element.data("placeholder") ||
this.opts.placeholder ||
((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined);
},
// abstract
getPlaceholderOption: function() {
if (this.select) {
var firstOption = this.select.children('option').first();
if (this.opts.placeholderOption !== undefined ) {
//Determine the placeholder option based on the specified placeholderOption setting
return (this.opts.placeholderOption === "first" && firstOption) ||
(typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select));
} else if ($.trim(firstOption.text()) === "" && firstOption.val() === "") {
//No explicit placeholder option specified, use the first if it's blank
return firstOption;
}
}
},
/**
* Get the desired width for the container element. This is
* derived first from option `width` passed to select2, then
* the inline 'style' on the original element, and finally
* falls back to the jQuery calculated element width.
*/
// abstract
initContainerWidth: function () {
function resolveContainerWidth() {
var style, attrs, matches, i, l, attr;
if (this.opts.width === "off") {
return null;
} else if (this.opts.width === "element"){
return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
} else if (this.opts.width === "copy" || this.opts.width === "resolve") {
// check if there is inline style on the element that contains width
style = this.opts.element.attr('style');
if (style !== undefined) {
attrs = style.split(';');
for (i = 0, l = attrs.length; i < l; i = i + 1) {
attr = attrs[i].replace(/\s/g, '');
matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);
if (matches !== null && matches.length >= 1)
return matches[1];
}
}
if (this.opts.width === "resolve") {
// next check if css('width') can resolve a width that is percent based, this is sometimes possible
// when attached to input type=hidden or elements hidden via css
style = this.opts.element.css('width');
if (style.indexOf("%") > 0) return style;
// finally, fallback on the calculated width of the element
return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
}
return null;
} else if ($.isFunction(this.opts.width)) {
return this.opts.width();
} else {
return this.opts.width;
}
};
var width = resolveContainerWidth.call(this);
if (width !== null) {
this.container.css("width", width);
}
}
});
SingleSelect2 = clazz(AbstractSelect2, {
// single
createContainer: function () {
var container = $(document.createElement("div")).attr({
"class": "select2-container"
}).html([
"",
" ",
" ",
" ",
" ",
" ",
"",
"
",
" ",
" ",
"
",
"
",
"
"].join(""));
return container;
},
// single
enableInterface: function() {
if (this.parent.enableInterface.apply(this, arguments)) {
this.focusser.prop("disabled", !this.isInterfaceEnabled());
}
},
// single
opening: function () {
var el, range, len;
if (this.opts.minimumResultsForSearch >= 0) {
this.showSearch(true);
}
this.parent.opening.apply(this, arguments);
if (this.showSearchInput !== false) {
// IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range
// all other browsers handle this just fine
this.search.val(this.focusser.val());
}
if (this.opts.shouldFocusInput(this)) {
this.search.focus();
// move the cursor to the end after focussing, otherwise it will be at the beginning and
// new text will appear *before* focusser.val()
el = this.search.get(0);
if (el.createTextRange) {
range = el.createTextRange();
range.collapse(false);
range.select();
} else if (el.setSelectionRange) {
len = this.search.val().length;
el.setSelectionRange(len, len);
}
}
// initializes search's value with nextSearchTerm (if defined by user)
// ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
if(this.search.val() === "") {
if(this.nextSearchTerm != undefined){
this.search.val(this.nextSearchTerm);
this.search.select();
}
}
this.focusser.prop("disabled", true).val("");
this.updateResults(true);
this.opts.element.trigger($.Event("select2-open"));
},
// single
close: function () {
if (!this.opened()) return;
this.parent.close.apply(this, arguments);
this.focusser.prop("disabled", false);
if (this.opts.shouldFocusInput(this)) {
this.focusser.focus();
}
},
// single
focus: function () {
if (this.opened()) {
this.close();
} else {
this.focusser.prop("disabled", false);
if (this.opts.shouldFocusInput(this)) {
this.focusser.focus();
}
}
},
// single
isFocused: function () {
return this.container.hasClass("select2-container-active");
},
// single
cancel: function () {
this.parent.cancel.apply(this, arguments);
this.focusser.prop("disabled", false);
if (this.opts.shouldFocusInput(this)) {
this.focusser.focus();
}
},
// single
destroy: function() {
$("label[for='" + this.focusser.attr('id') + "']")
.attr('for', this.opts.element.attr("id"));
this.parent.destroy.apply(this, arguments);
cleanupJQueryElements.call(this,
"selection",
"focusser"
);
},
// single
initContainer: function () {
var selection,
container = this.container,
dropdown = this.dropdown,
idSuffix = nextUid(),
elementLabel;
if (this.opts.minimumResultsForSearch < 0) {
this.showSearch(false);
} else {
this.showSearch(true);
}
this.selection = selection = container.find(".select2-choice");
this.focusser = container.find(".select2-focusser");
// add aria associations
selection.find(".select2-chosen").attr("id", "select2-chosen-"+idSuffix);
this.focusser.attr("aria-labelledby", "select2-chosen-"+idSuffix);
this.results.attr("id", "select2-results-"+idSuffix);
this.search.attr("aria-owns", "select2-results-"+idSuffix);
// rewrite labels from original element to focusser
this.focusser.attr("id", "s2id_autogen"+idSuffix);
elementLabel = $("label[for='" + this.opts.element.attr("id") + "']");
this.focusser.prev()
.text(elementLabel.text())
.attr('for', this.focusser.attr('id'));
// Ensure the original element retains an accessible name
var originalTitle = this.opts.element.attr("title");
this.opts.element.attr("title", (originalTitle || elementLabel.text()));
this.focusser.attr("tabindex", this.elementTabIndex);
// write label for search field using the label from the focusser element
this.search.attr("id", this.focusser.attr('id') + '_search');
this.search.prev()
.text($("label[for='" + this.focusser.attr('id') + "']").text())
.attr('for', this.search.attr('id'));
this.search.on("keydown", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
// prevent the page from scrolling
killEvent(e);
return;
}
switch (e.which) {
case KEY.UP:
case KEY.DOWN:
this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
killEvent(e);
return;
case KEY.ENTER:
this.selectHighlighted();
killEvent(e);
return;
case KEY.TAB:
this.selectHighlighted({noFocus: true});
return;
case KEY.ESC:
this.cancel(e);
killEvent(e);
return;
}
}));
this.search.on("blur", this.bind(function(e) {
// a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
// without this the search field loses focus which is annoying
if (document.activeElement === this.body.get(0)) {
window.setTimeout(this.bind(function() {
if (this.opened()) {
this.search.focus();
}
}), 0);
}
}));
this.focusser.on("keydown", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
return;
}
if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
killEvent(e);
return;
}
if (e.which == KEY.DOWN || e.which == KEY.UP
|| (e.which == KEY.ENTER && this.opts.openOnEnter)) {
if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return;
this.open();
killEvent(e);
return;
}
if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
if (this.opts.allowClear) {
this.clear();
}
killEvent(e);
return;
}
}));
installKeyUpChangeEvent(this.focusser);
this.focusser.on("keyup-change input", this.bind(function(e) {
if (this.opts.minimumResultsForSearch >= 0) {
e.stopPropagation();
if (this.opened()) return;
this.open();
}
}));
selection.on("mousedown touchstart", "abbr", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
this.clear();
killEventImmediately(e);
this.close();
this.selection.focus();
}));
selection.on("mousedown touchstart", this.bind(function (e) {
// Prevent IE from generating a click event on the body
reinsertElement(selection);
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
if (this.opened()) {
this.close();
} else if (this.isInterfaceEnabled()) {
this.open();
}
killEvent(e);
}));
dropdown.on("mousedown touchstart", this.bind(function() {
if (this.opts.shouldFocusInput(this)) {
this.search.focus();
}
}));
selection.on("focus", this.bind(function(e) {
killEvent(e);
}));
this.focusser.on("focus", this.bind(function(){
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.container.addClass("select2-container-active");
})).on("blur", this.bind(function() {
if (!this.opened()) {
this.container.removeClass("select2-container-active");
this.opts.element.trigger($.Event("select2-blur"));
}
}));
this.search.on("focus", this.bind(function(){
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.container.addClass("select2-container-active");
}));
this.initContainerWidth();
this.opts.element.addClass("select2-offscreen");
this.setPlaceholder();
},
// single
clear: function(triggerChange) {
var data=this.selection.data("select2-data");
if (data) { // guard against queued quick consecutive clicks
var evt = $.Event("select2-clearing");
this.opts.element.trigger(evt);
if (evt.isDefaultPrevented()) {
return;
}
var placeholderOption = this.getPlaceholderOption();
this.opts.element.val(placeholderOption ? placeholderOption.val() : "");
this.selection.find(".select2-chosen").empty();
this.selection.removeData("select2-data");
this.setPlaceholder();
if (triggerChange !== false){
this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
this.triggerChange({removed:data});
}
}
},
/**
* Sets selection based on source element's value
*/
// single
initSelection: function () {
var selected;
if (this.isPlaceholderOptionSelected()) {
this.updateSelection(null);
this.close();
this.setPlaceholder();
} else {
var self = this;
this.opts.initSelection.call(null, this.opts.element, function(selected){
if (selected !== undefined && selected !== null) {
self.updateSelection(selected);
self.close();
self.setPlaceholder();
self.nextSearchTerm = self.opts.nextSearchTerm(selected, self.search.val());
}
});
}
},
isPlaceholderOptionSelected: function() {
var placeholderOption;
if (this.getPlaceholder() === undefined) return false; // no placeholder specified so no option should be considered
return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected"))
|| (this.opts.element.val() === "")
|| (this.opts.element.val() === undefined)
|| (this.opts.element.val() === null);
},
// single
prepareOpts: function () {
var opts = this.parent.prepareOpts.apply(this, arguments),
self=this;
if (opts.element.get(0).tagName.toLowerCase() === "select") {
// install the selection initializer
opts.initSelection = function (element, callback) {
var selected = element.find("option").filter(function() { return this.selected && !this.disabled });
// a single select box always has a value, no need to null check 'selected'
callback(self.optionToData(selected));
};
} else if ("data" in opts) {
// install default initSelection when applied to hidden input and data is local
opts.initSelection = opts.initSelection || function (element, callback) {
var id = element.val();
//search in data by id, storing the actual matching item
var match = null;
opts.query({
matcher: function(term, text, el){
var is_match = equal(id, opts.id(el));
if (is_match) {
match = el;
}
return is_match;
},
callback: !$.isFunction(callback) ? $.noop : function() {
callback(match);
}
});
};
}
return opts;
},
// single
getPlaceholder: function() {
// if a placeholder is specified on a single select without a valid placeholder option ignore it
if (this.select) {
if (this.getPlaceholderOption() === undefined) {
return undefined;
}
}
return this.parent.getPlaceholder.apply(this, arguments);
},
// single
setPlaceholder: function () {
var placeholder = this.getPlaceholder();
if (this.isPlaceholderOptionSelected() && placeholder !== undefined) {
// check for a placeholder option if attached to a select
if (this.select && this.getPlaceholderOption() === undefined) return;
this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));
this.selection.addClass("select2-default");
this.container.removeClass("select2-allowclear");
}
},
// single
postprocessResults: function (data, initial, noHighlightUpdate) {
var selected = 0, self = this, showSearchInput = true;
// find the selected element in the result list
this.findHighlightableChoices().each2(function (i, elm) {
if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
selected = i;
return false;
}
});
// and highlight it
if (noHighlightUpdate !== false) {
if (initial === true && selected >= 0) {
this.highlight(selected);
} else {
this.highlight(0);
}
}
// hide the search box if this is the first we got the results and there are enough of them for search
if (initial === true) {
var min = this.opts.minimumResultsForSearch;
if (min >= 0) {
this.showSearch(countResults(data.results) >= min);
}
}
},
// single
showSearch: function(showSearchInput) {
if (this.showSearchInput === showSearchInput) return;
this.showSearchInput = showSearchInput;
this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput);
this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput);
//add "select2-with-searchbox" to the container if search box is shown
$(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput);
},
// single
onSelect: function (data, options) {
if (!this.triggerSelect(data)) { return; }
var old = this.opts.element.val(),
oldData = this.data();
this.opts.element.val(this.id(data));
this.updateSelection(data);
this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });
this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
this.close();
if ((!options || !options.noFocus) && this.opts.shouldFocusInput(this)) {
this.focusser.focus();
}
if (!equal(old, this.id(data))) {
this.triggerChange({ added: data, removed: oldData });
}
},
// single
updateSelection: function (data) {
var container=this.selection.find(".select2-chosen"), formatted, cssClass;
this.selection.data("select2-data", data);
container.empty();
if (data !== null) {
formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
}
if (formatted !== undefined) {
container.append(formatted);
}
cssClass=this.opts.formatSelectionCssClass(data, container);
if (cssClass !== undefined) {
container.addClass(cssClass);
}
this.selection.removeClass("select2-default");
if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
this.container.addClass("select2-allowclear");
}
},
// single
val: function () {
var val,
triggerChange = false,
data = null,
self = this,
oldData = this.data();
if (arguments.length === 0) {
return this.opts.element.val();
}
val = arguments[0];
if (arguments.length > 1) {
triggerChange = arguments[1];
}
if (this.select) {
this.select
.val(val)
.find("option").filter(function() { return this.selected }).each2(function (i, elm) {
data = self.optionToData(elm);
return false;
});
this.updateSelection(data);
this.setPlaceholder();
if (triggerChange) {
this.triggerChange({added: data, removed:oldData});
}
} else {
// val is an id. !val is true for [undefined,null,'',0] - 0 is legal
if (!val && val !== 0) {
this.clear(triggerChange);
return;
}
if (this.opts.initSelection === undefined) {
throw new Error("cannot call val() if initSelection() is not defined");
}
this.opts.element.val(val);
this.opts.initSelection(this.opts.element, function(data){
self.opts.element.val(!data ? "" : self.id(data));
self.updateSelection(data);
self.setPlaceholder();
if (triggerChange) {
self.triggerChange({added: data, removed:oldData});
}
});
}
},
// single
clearSearch: function () {
this.search.val("");
this.focusser.val("");
},
// single
data: function(value) {
var data,
triggerChange = false;
if (arguments.length === 0) {
data = this.selection.data("select2-data");
if (data == undefined) data = null;
return data;
} else {
if (arguments.length > 1) {
triggerChange = arguments[1];
}
if (!value) {
this.clear(triggerChange);
} else {
data = this.data();
this.opts.element.val(!value ? "" : this.id(value));
this.updateSelection(value);
if (triggerChange) {
this.triggerChange({added: value, removed:data});
}
}
}
}
});
MultiSelect2 = clazz(AbstractSelect2, {
// multi
createContainer: function () {
var container = $(document.createElement("div")).attr({
"class": "select2-container select2-container-multi"
}).html([
"",
""].join(""));
return container;
},
// multi
prepareOpts: function () {
var opts = this.parent.prepareOpts.apply(this, arguments),
self=this;
// TODO validate placeholder is a string if specified
if (opts.element.get(0).tagName.toLowerCase() === "select") {
// install the selection initializer
opts.initSelection = function (element, callback) {
var data = [];
element.find("option").filter(function() { return this.selected && !this.disabled }).each2(function (i, elm) {
data.push(self.optionToData(elm));
});
callback(data);
};
} else if ("data" in opts) {
// install default initSelection when applied to hidden input and data is local
opts.initSelection = opts.initSelection || function (element, callback) {
var ids = splitVal(element.val(), opts.separator);
//search in data by array of ids, storing matching items in a list
var matches = [];
opts.query({
matcher: function(term, text, el){
var is_match = $.grep(ids, function(id) {
return equal(id, opts.id(el));
}).length;
if (is_match) {
matches.push(el);
}
return is_match;
},
callback: !$.isFunction(callback) ? $.noop : function() {
// reorder matches based on the order they appear in the ids array because right now
// they are in the order in which they appear in data array
var ordered = [];
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
for (var j = 0; j < matches.length; j++) {
var match = matches[j];
if (equal(id, opts.id(match))) {
ordered.push(match);
matches.splice(j, 1);
break;
}
}
}
callback(ordered);
}
});
};
}
return opts;
},
// multi
selectChoice: function (choice) {
var selected = this.container.find(".select2-search-choice-focus");
if (selected.length && choice && choice[0] == selected[0]) {
} else {
if (selected.length) {
this.opts.element.trigger("choice-deselected", selected);
}
selected.removeClass("select2-search-choice-focus");
if (choice && choice.length) {
this.close();
choice.addClass("select2-search-choice-focus");
this.opts.element.trigger("choice-selected", choice);
}
}
},
// multi
destroy: function() {
$("label[for='" + this.search.attr('id') + "']")
.attr('for', this.opts.element.attr("id"));
this.parent.destroy.apply(this, arguments);
cleanupJQueryElements.call(this,
"searchContainer",
"selection"
);
},
// multi
initContainer: function () {
var selector = ".select2-choices", selection;
this.searchContainer = this.container.find(".select2-search-field");
this.selection = selection = this.container.find(selector);
var _this = this;
this.selection.on("click", ".select2-search-choice:not(.select2-locked)", function (e) {
//killEvent(e);
_this.search[0].focus();
_this.selectChoice($(this));
});
// rewrite labels from original element to focusser
this.search.attr("id", "s2id_autogen"+nextUid());
this.search.prev()
.text($("label[for='" + this.opts.element.attr("id") + "']").text())
.attr('for', this.search.attr('id'));
this.search.on("input paste", this.bind(function() {
if (!this.isInterfaceEnabled()) return;
if (!this.opened()) {
this.open();
}
}));
this.search.attr("tabindex", this.elementTabIndex);
this.keydowns = 0;
this.search.on("keydown", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
++this.keydowns;
var selected = selection.find(".select2-search-choice-focus");
var prev = selected.prev(".select2-search-choice:not(.select2-locked)");
var next = selected.next(".select2-search-choice:not(.select2-locked)");
var pos = getCursorInfo(this.search);
if (selected.length &&
(e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) {
var selectedChoice = selected;
if (e.which == KEY.LEFT && prev.length) {
selectedChoice = prev;
}
else if (e.which == KEY.RIGHT) {
selectedChoice = next.length ? next : null;
}
else if (e.which === KEY.BACKSPACE) {
if (this.unselect(selected.first())) {
this.search.width(10);
selectedChoice = prev.length ? prev : next;
}
} else if (e.which == KEY.DELETE) {
if (this.unselect(selected.first())) {
this.search.width(10);
selectedChoice = next.length ? next : null;
}
} else if (e.which == KEY.ENTER) {
selectedChoice = null;
}
this.selectChoice(selectedChoice);
killEvent(e);
if (!selectedChoice || !selectedChoice.length) {
this.open();
}
return;
} else if (((e.which === KEY.BACKSPACE && this.keydowns == 1)
|| e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) {
this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());
killEvent(e);
return;
} else {
this.selectChoice(null);
}
if (this.opened()) {
switch (e.which) {
case KEY.UP:
case KEY.DOWN:
this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
killEvent(e);
return;
case KEY.ENTER:
this.selectHighlighted();
killEvent(e);
return;
case KEY.TAB:
this.selectHighlighted({noFocus:true});
this.close();
return;
case KEY.ESC:
this.cancel(e);
killEvent(e);
return;
}
}
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
|| e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
return;
}
if (e.which === KEY.ENTER) {
if (this.opts.openOnEnter === false) {
return;
} else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
return;
}
}
this.open();
if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
// prevent the page from scrolling
killEvent(e);
}
if (e.which === KEY.ENTER) {
// prevent form from being submitted
killEvent(e);
}
}));
this.search.on("keyup", this.bind(function (e) {
this.keydowns = 0;
this.resizeSearch();
})
);
this.search.on("blur", this.bind(function(e) {
this.container.removeClass("select2-container-active");
this.search.removeClass("select2-focused");
this.selectChoice(null);
if (!this.opened()) this.clearSearch();
e.stopImmediatePropagation();
this.opts.element.trigger($.Event("select2-blur"));
}));
this.container.on("click", selector, this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
if ($(e.target).closest(".select2-search-choice").length > 0) {
// clicked inside a select2 search choice, do not open
return;
}
this.selectChoice(null);
this.clearPlaceholder();
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.open();
this.focusSearch();
e.preventDefault();
}));
this.container.on("focus", selector, this.bind(function () {
if (!this.isInterfaceEnabled()) return;
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.container.addClass("select2-container-active");
this.dropdown.addClass("select2-drop-active");
this.clearPlaceholder();
}));
this.initContainerWidth();
this.opts.element.addClass("select2-offscreen");
// set the placeholder if necessary
this.clearSearch();
},
// multi
enableInterface: function() {
if (this.parent.enableInterface.apply(this, arguments)) {
this.search.prop("disabled", !this.isInterfaceEnabled());
}
},
// multi
initSelection: function () {
var data;
if (this.opts.element.val() === "" && this.opts.element.text() === "") {
this.updateSelection([]);
this.close();
// set the placeholder if necessary
this.clearSearch();
}
if (this.select || this.opts.element.val() !== "") {
var self = this;
this.opts.initSelection.call(null, this.opts.element, function(data){
if (data !== undefined && data !== null) {
self.updateSelection(data);
self.close();
// set the placeholder if necessary
self.clearSearch();
}
});
}
},
// multi
clearSearch: function () {
var placeholder = this.getPlaceholder(),
maxWidth = this.getMaxSearchWidth();
if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
this.search.val(placeholder).addClass("select2-default");
// stretch the search box to full width of the container so as much of the placeholder is visible as possible
// we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944
this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width"));
} else {
this.search.val("").width(10);
}
},
// multi
clearPlaceholder: function () {
if (this.search.hasClass("select2-default")) {
this.search.val("").removeClass("select2-default");
}
},
// multi
opening: function () {
this.clearPlaceholder(); // should be done before super so placeholder is not used to search
this.resizeSearch();
this.parent.opening.apply(this, arguments);
this.focusSearch();
// initializes search's value with nextSearchTerm (if defined by user)
// ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
if(this.search.val() === "") {
if(this.nextSearchTerm != undefined){
this.search.val(this.nextSearchTerm);
this.search.select();
}
}
this.updateResults(true);
if (this.opts.shouldFocusInput(this)) {
this.search.focus();
}
this.opts.element.trigger($.Event("select2-open"));
},
// multi
close: function () {
if (!this.opened()) return;
this.parent.close.apply(this, arguments);
},
// multi
focus: function () {
this.close();
this.search.focus();
},
// multi
isFocused: function () {
return this.search.hasClass("select2-focused");
},
// multi
updateSelection: function (data) {
var ids = [], filtered = [], self = this;
// filter out duplicates
$(data).each(function () {
if (indexOf(self.id(this), ids) < 0) {
ids.push(self.id(this));
filtered.push(this);
}
});
data = filtered;
this.selection.find(".select2-search-choice").remove();
$(data).each(function () {
self.addSelectedChoice(this);
});
self.postprocessResults();
},
// multi
tokenize: function() {
var input = this.search.val();
input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts);
if (input != null && input != undefined) {
this.search.val(input);
if (input.length > 0) {
this.open();
}
}
},
// multi
onSelect: function (data, options) {
if (!this.triggerSelect(data)) { return; }
this.addSelectedChoice(data);
this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
// keep track of the search's value before it gets cleared
this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
this.clearSearch();
this.updateResults();
if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true);
if (this.opts.closeOnSelect) {
this.close();
this.search.width(10);
} else {
if (this.countSelectableResults()>0) {
this.search.width(10);
this.resizeSearch();
if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
// if we reached max selection size repaint the results so choices
// are replaced with the max selection reached message
this.updateResults(true);
} else {
// initializes search's value with nextSearchTerm and update search result
if(this.nextSearchTerm != undefined){
this.search.val(this.nextSearchTerm);
this.updateResults();
this.search.select();
}
}
this.positionDropdown();
} else {
// if nothing left to select close
this.close();
this.search.width(10);
}
}
// since its not possible to select an element that has already been
// added we do not need to check if this is a new element before firing change
this.triggerChange({ added: data });
if (!options || !options.noFocus)
this.focusSearch();
},
// multi
cancel: function () {
this.close();
this.focusSearch();
},
addSelectedChoice: function (data) {
var enableChoice = !data.locked,
enabledItem = $(
"" +
"
" +
" " +
" "),
disabledItem = $(
"" +
"
" +
" ");
var choice = enableChoice ? enabledItem : disabledItem,
id = this.id(data),
val = this.getVal(),
formatted,
cssClass;
formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
if (formatted != undefined) {
choice.find("div").replaceWith(""+formatted+"
");
}
cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
if (cssClass != undefined) {
choice.addClass(cssClass);
}
if(enableChoice){
choice.find(".select2-search-choice-close")
.on("mousedown", killEvent)
.on("click dblclick", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
this.unselect($(e.target));
this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
killEvent(e);
this.close();
this.focusSearch();
})).on("focus", this.bind(function () {
if (!this.isInterfaceEnabled()) return;
this.container.addClass("select2-container-active");
this.dropdown.addClass("select2-drop-active");
}));
}
choice.data("select2-data", data);
choice.insertBefore(this.searchContainer);
val.push(id);
this.setVal(val);
},
// multi
unselect: function (selected) {
var val = this.getVal(),
data,
index;
selected = selected.closest(".select2-search-choice");
if (selected.length === 0) {
throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
}
data = selected.data("select2-data");
if (!data) {
// prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
// and invoked on an element already removed
return;
}
var evt = $.Event("select2-removing");
evt.val = this.id(data);
evt.choice = data;
this.opts.element.trigger(evt);
if (evt.isDefaultPrevented()) {
return false;
}
while((index = indexOf(this.id(data), val)) >= 0) {
val.splice(index, 1);
this.setVal(val);
if (this.select) this.postprocessResults();
}
selected.remove();
this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
this.triggerChange({ removed: data });
return true;
},
// multi
postprocessResults: function (data, initial, noHighlightUpdate) {
var val = this.getVal(),
choices = this.results.find(".select2-result"),
compound = this.results.find(".select2-result-with-children"),
self = this;
choices.each2(function (i, choice) {
var id = self.id(choice.data("select2-data"));
if (indexOf(id, val) >= 0) {
choice.addClass("select2-selected");
// mark all children of the selected parent as selected
choice.find(".select2-result-selectable").addClass("select2-selected");
}
});
compound.each2(function(i, choice) {
// hide an optgroup if it doesn't have any selectable children
if (!choice.is('.select2-result-selectable')
&& choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
choice.addClass("select2-selected");
}
});
if (this.highlight() == -1 && noHighlightUpdate !== false){
self.highlight(0);
}
//If all results are chosen render formatNoMatches
if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){
if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) {
if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) {
this.results.append("" + evaluate(self.opts.formatNoMatches, self.search.val()) + " ");
}
}
}
},
// multi
getMaxSearchWidth: function() {
return this.selection.width() - getSideBorderPadding(this.search);
},
// multi
resizeSearch: function () {
var minimumWidth, left, maxWidth, containerLeft, searchWidth,
sideBorderPadding = getSideBorderPadding(this.search);
minimumWidth = measureTextWidth(this.search) + 10;
left = this.search.offset().left;
maxWidth = this.selection.width();
containerLeft = this.selection.offset().left;
searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
if (searchWidth < minimumWidth) {
searchWidth = maxWidth - sideBorderPadding;
}
if (searchWidth < 40) {
searchWidth = maxWidth - sideBorderPadding;
}
if (searchWidth <= 0) {
searchWidth = minimumWidth;
}
this.search.width(Math.floor(searchWidth));
},
// multi
getVal: function () {
var val;
if (this.select) {
val = this.select.val();
return val === null ? [] : val;
} else {
val = this.opts.element.val();
return splitVal(val, this.opts.separator);
}
},
// multi
setVal: function (val) {
var unique;
if (this.select) {
this.select.val(val);
} else {
unique = [];
// filter out duplicates
$(val).each(function () {
if (indexOf(this, unique) < 0) unique.push(this);
});
this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
}
},
// multi
buildChangeDetails: function (old, current) {
var current = current.slice(0),
old = old.slice(0);
// remove intersection from each array
for (var i = 0; i < current.length; i++) {
for (var j = 0; j < old.length; j++) {
if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
current.splice(i, 1);
if(i>0){
i--;
}
old.splice(j, 1);
j--;
}
}
}
return {added: current, removed: old};
},
// multi
val: function (val, triggerChange) {
var oldData, self=this;
if (arguments.length === 0) {
return this.getVal();
}
oldData=this.data();
if (!oldData.length) oldData=[];
// val is an id. !val is true for [undefined,null,'',0] - 0 is legal
if (!val && val !== 0) {
this.opts.element.val("");
this.updateSelection([]);
this.clearSearch();
if (triggerChange) {
this.triggerChange({added: this.data(), removed: oldData});
}
return;
}
// val is a list of ids
this.setVal(val);
if (this.select) {
this.opts.initSelection(this.select, this.bind(this.updateSelection));
if (triggerChange) {
this.triggerChange(this.buildChangeDetails(oldData, this.data()));
}
} else {
if (this.opts.initSelection === undefined) {
throw new Error("val() cannot be called if initSelection() is not defined");
}
this.opts.initSelection(this.opts.element, function(data){
var ids=$.map(data, self.id);
self.setVal(ids);
self.updateSelection(data);
self.clearSearch();
if (triggerChange) {
self.triggerChange(self.buildChangeDetails(oldData, self.data()));
}
});
}
this.clearSearch();
},
// multi
onSortStart: function() {
if (this.select) {
throw new Error("Sorting of elements is not supported when attached to . Attach to instead.");
}
// collapse search field into 0 width so its container can be collapsed as well
this.search.width(0);
// hide the container
this.searchContainer.hide();
},
// multi
onSortEnd:function() {
var val=[], self=this;
// show search and move it to the end of the list
this.searchContainer.show();
// make sure the search container is the last item in the list
this.searchContainer.appendTo(this.searchContainer.parent());
// since we collapsed the width in dragStarted, we resize it here
this.resizeSearch();
// update selection
this.selection.find(".select2-search-choice").each(function() {
val.push(self.opts.id($(this).data("select2-data")));
});
this.setVal(val);
this.triggerChange();
},
// multi
data: function(values, triggerChange) {
var self=this, ids, old;
if (arguments.length === 0) {
return this.selection
.children(".select2-search-choice")
.map(function() { return $(this).data("select2-data"); })
.get();
} else {
old = this.data();
if (!values) { values = []; }
ids = $.map(values, function(e) { return self.opts.id(e); });
this.setVal(ids);
this.updateSelection(values);
this.clearSearch();
if (triggerChange) {
this.triggerChange(this.buildChangeDetails(old, this.data()));
}
}
}
});
$.fn.select2 = function () {
var args = Array.prototype.slice.call(arguments, 0),
opts,
select2,
method, value, multiple,
allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"],
valueMethods = ["opened", "isFocused", "container", "dropdown"],
propertyMethods = ["val", "data"],
methodsMap = { search: "externalSearch" };
this.each(function () {
if (args.length === 0 || typeof(args[0]) === "object") {
opts = args.length === 0 ? {} : $.extend({}, args[0]);
opts.element = $(this);
if (opts.element.get(0).tagName.toLowerCase() === "select") {
multiple = opts.element.prop("multiple");
} else {
multiple = opts.multiple || false;
if ("tags" in opts) {opts.multiple = multiple = true;}
}
select2 = multiple ? new window.Select2["class"].multi() : new window.Select2["class"].single();
select2.init(opts);
} else if (typeof(args[0]) === "string") {
if (indexOf(args[0], allowedMethods) < 0) {
throw "Unknown method: " + args[0];
}
value = undefined;
select2 = $(this).data("select2");
if (select2 === undefined) return;
method=args[0];
if (method === "container") {
value = select2.container;
} else if (method === "dropdown") {
value = select2.dropdown;
} else {
if (methodsMap[method]) method = methodsMap[method];
value = select2[method].apply(select2, args.slice(1));
}
if (indexOf(args[0], valueMethods) >= 0
|| (indexOf(args[0], propertyMethods) >= 0 && args.length == 1)) {
return false; // abort the iteration, ready to return first matched value
}
} else {
throw "Invalid arguments to select2 plugin: " + args;
}
});
return (value === undefined) ? this : value;
};
// plugin defaults, accessible to users
$.fn.select2.defaults = {
width: "copy",
loadMorePadding: 0,
closeOnSelect: true,
openOnEnter: true,
containerCss: {},
dropdownCss: {},
containerCssClass: "",
dropdownCssClass: "",
formatResult: function(result, container, query, escapeMarkup) {
var markup=[];
markMatch(result.text, query.term, markup, escapeMarkup);
return markup.join("");
},
formatSelection: function (data, container, escapeMarkup) {
return data ? escapeMarkup(data.text) : undefined;
},
sortResults: function (results, container, query) {
return results;
},
formatResultCssClass: function(data) {return data.css;},
formatSelectionCssClass: function(data, container) {return undefined;},
formatMatches: function (matches) { return matches + " results are available, use up and down arrow keys to navigate."; },
formatNoMatches: function () { return "No matches found"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " or more character" + (n == 1? "" : "s"); },
formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); },
formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
formatLoadMore: function (pageNumber) { return "Loading more results…"; },
formatSearching: function () { return "Searching…"; },
minimumResultsForSearch: 0,
minimumInputLength: 0,
maximumInputLength: null,
maximumSelectionSize: 0,
id: function (e) { return e == undefined ? null : e.id; },
matcher: function(term, text) {
return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
},
separator: ",",
tokenSeparators: [],
tokenizer: defaultTokenizer,
escapeMarkup: defaultEscapeMarkup,
blurOnChange: false,
selectOnBlur: false,
adaptContainerCssClass: function(c) { return c; },
adaptDropdownCssClass: function(c) { return null; },
nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; },
searchInputPlaceholder: '',
createSearchChoicePosition: 'top',
shouldFocusInput: function (instance) {
// Attempt to detect touch devices
var supportsTouchEvents = (('ontouchstart' in window) ||
(navigator.msMaxTouchPoints > 0));
// Only devices which support touch events should be special cased
if (!supportsTouchEvents) {
return true;
}
// Never focus the input if search is disabled
if (instance.opts.minimumResultsForSearch < 0) {
return false;
}
return true;
}
};
$.fn.select2.ajaxDefaults = {
transport: $.ajax,
params: {
type: "GET",
cache: false,
dataType: "json"
}
};
// exports
window.Select2 = {
query: {
ajax: ajax,
local: local,
tags: tags
}, util: {
debounce: debounce,
markMatch: markMatch,
escapeMarkup: defaultEscapeMarkup,
stripDiacritics: stripDiacritics
}, "class": {
"abstract": AbstractSelect2,
"single": SingleSelect2,
"multi": MultiSelect2
}
};
}(jQuery));
/* ===================================================
* bootstrap-transition.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#transitions
* ===================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* CSS TRANSITION SUPPORT (http://www.modernizr.com/)
* ======================================================= */
$(function () {
$.support.transition = (function () {
var transitionEnd = (function () {
var el = document.createElement('bootstrap')
, transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd'
, 'MozTransition' : 'transitionend'
, 'OTransition' : 'oTransitionEnd otransitionend'
, 'transition' : 'transitionend'
}
, name
for (name in transEndEventNames){
if (el.style[name] !== undefined) {
return transEndEventNames[name]
}
}
}())
return transitionEnd && {
end: transitionEnd
}
})()
})
}(window.jQuery);
/* ==========================================================
* bootstrap-affix.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#affix
* ==========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* AFFIX CLASS DEFINITION
* ====================== */
var Affix = function (element, options) {
this.options = $.extend({}, $.fn.affix.defaults, options)
this.$window = $(window)
.on('scroll.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.affix.data-api', $.proxy(function () { setTimeout($.proxy(this.checkPosition, this), 1) }, this))
this.$element = $(element)
this.checkPosition()
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var scrollHeight = $(document).height()
, scrollTop = this.$window.scrollTop()
, position = this.$element.offset()
, offset = this.options.offset
, offsetBottom = offset.bottom
, offsetTop = offset.top
, reset = 'affix affix-top affix-bottom'
, affix
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top()
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()
affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ?
false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ?
'bottom' : offsetTop != null && scrollTop <= offsetTop ?
'top' : false
if (this.affixed === affix) return
this.affixed = affix
this.unpin = affix == 'bottom' ? position.top - scrollTop : null
this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : ''))
}
/* AFFIX PLUGIN DEFINITION
* ======================= */
var old = $.fn.affix
$.fn.affix = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('affix')
, options = typeof option == 'object' && option
if (!data) $this.data('affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.affix.Constructor = Affix
$.fn.affix.defaults = {
offset: 0
}
/* AFFIX NO CONFLICT
* ================= */
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
/* AFFIX DATA-API
* ============== */
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
, data = $spy.data()
data.offset = data.offset || {}
data.offsetBottom && (data.offset.bottom = data.offsetBottom)
data.offsetTop && (data.offset.top = data.offsetTop)
$spy.affix(data)
})
})
}(window.jQuery);
/* ==========================================================
* bootstrap-alert.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#alerts
* ==========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* ALERT CLASS DEFINITION
* ====================== */
var dismiss = '[data-dismiss="alert"]'
, Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.prototype.close = function (e) {
var $this = $(this)
, selector = $this.attr('data-target')
, $parent
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = $(selector)
e && e.preventDefault()
$parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent())
$parent.trigger(e = $.Event('close'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
$parent
.trigger('closed')
.remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent.on($.support.transition.end, removeElement) :
removeElement()
}
/* ALERT PLUGIN DEFINITION
* ======================= */
var old = $.fn.alert
$.fn.alert = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('alert')
if (!data) $this.data('alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.alert.Constructor = Alert
/* ALERT NO CONFLICT
* ================= */
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
/* ALERT DATA-API
* ============== */
$(document).on('click.alert.data-api', dismiss, Alert.prototype.close)
}(window.jQuery);
/* ============================================================
* bootstrap-button.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#buttons
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function ($) {
"use strict"; // jshint ;_;
/* BUTTON PUBLIC CLASS DEFINITION
* ============================== */
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.button.defaults, options)
}
Button.prototype.setState = function (state) {
var d = 'disabled'
, $el = this.$element
, data = $el.data()
, val = $el.is('input') ? 'val' : 'html'
state = state + 'Text'
data.resetText || $el.data('resetText', $el[val]())
$el[val](data[state] || this.options[state])
// push to event loop to allow forms to submit
setTimeout(function () {
state == 'loadingText' ?
$el.addClass(d).attr(d, d) :
$el.removeClass(d).removeAttr(d)
}, 0)
}
Button.prototype.toggle = function () {
var $parent = this.$element.closest('[data-toggle="buttons-radio"]')
$parent && $parent
.find('.active')
.removeClass('active')
this.$element.toggleClass('active')
}
/* BUTTON PLUGIN DEFINITION
* ======================== */
var old = $.fn.button
$.fn.button = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('button')
, options = typeof option == 'object' && option
if (!data) $this.data('button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
$.fn.button.defaults = {
loadingText: 'loading...'
}
$.fn.button.Constructor = Button
/* BUTTON NO CONFLICT
* ================== */
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
/* BUTTON DATA-API
* =============== */
$(document).on('click.button.data-api', '[data-toggle^=button]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
$btn.button('toggle')
})
}(window.jQuery);
/* ==========================================================
* bootstrap-carousel.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#carousel
* ==========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* CAROUSEL CLASS DEFINITION
* ========================= */
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.options.pause == 'hover' && this.$element
.on('mouseenter', $.proxy(this.pause, this))
.on('mouseleave', $.proxy(this.cycle, this))
}
Carousel.prototype = {
cycle: function (e) {
if (!e) this.paused = false
if (this.interval) clearInterval(this.interval);
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
, getActiveIndex: function () {
this.$active = this.$element.find('.item.active')
this.$items = this.$active.parent().children()
return this.$items.index(this.$active)
}
, to: function (pos) {
var activeIndex = this.getActiveIndex()
, that = this
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) {
return this.$element.one('slid', function () {
that.to(pos)
})
}
if (activeIndex == pos) {
return this.pause().cycle()
}
return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
}
, pause: function (e) {
if (!e) this.paused = true
if (this.$element.find('.next, .prev').length && $.support.transition.end) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
clearInterval(this.interval)
this.interval = null
return this
}
, next: function () {
if (this.sliding) return
return this.slide('next')
}
, prev: function () {
if (this.sliding) return
return this.slide('prev')
}
, slide: function (type, next) {
var $active = this.$element.find('.item.active')
, $next = next || $active[type]()
, isCycling = this.interval
, direction = type == 'next' ? 'left' : 'right'
, fallback = type == 'next' ? 'first' : 'last'
, that = this
, e
this.sliding = true
isCycling && this.pause()
$next = $next.length ? $next : this.$element.find('.item')[fallback]()
e = $.Event('slide', {
relatedTarget: $next[0]
, direction: direction
})
if ($next.hasClass('active')) return
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
this.$element.one('slid', function () {
var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()])
$nextIndicator && $nextIndicator.addClass('active')
})
}
if ($.support.transition && this.$element.hasClass('slide')) {
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
this.$element.one($.support.transition.end, function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () { that.$element.trigger('slid') }, 0)
})
} else {
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger('slid')
}
isCycling && this.cycle()
return this
}
}
/* CAROUSEL PLUGIN DEFINITION
* ========================== */
var old = $.fn.carousel
$.fn.carousel = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('carousel')
, options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option)
, action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
$.fn.carousel.defaults = {
interval: 5000
, pause: 'hover'
}
$.fn.carousel.Constructor = Carousel
/* CAROUSEL NO CONFLICT
* ==================== */
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
/* CAROUSEL DATA-API
* ================= */
$(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
var $this = $(this), href
, $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
, options = $.extend({}, $target.data(), $this.data())
, slideIndex
$target.carousel(options)
if (slideIndex = $this.attr('data-slide-to')) {
$target.data('carousel').pause().to(slideIndex).cycle()
}
e.preventDefault()
})
}(window.jQuery);
/* =============================================================
* bootstrap-collapse.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#collapse
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function ($) {
"use strict"; // jshint ;_;
/* COLLAPSE PUBLIC CLASS DEFINITION
* ================================ */
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.collapse.defaults, options)
if (this.options.parent) {
this.$parent = $(this.options.parent)
}
this.options.toggle && this.toggle()
}
Collapse.prototype = {
constructor: Collapse
, dimension: function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
, show: function () {
var dimension
, scroll
, actives
, hasData
if (this.transitioning || this.$element.hasClass('in')) return
dimension = this.dimension()
scroll = $.camelCase(['scroll', dimension].join('-'))
actives = this.$parent && this.$parent.find('> .accordion-group > .in')
if (actives && actives.length) {
hasData = actives.data('collapse')
if (hasData && hasData.transitioning) return
actives.collapse('hide')
hasData || actives.data('collapse', null)
}
this.$element[dimension](0)
this.transition('addClass', $.Event('show'), 'shown')
$.support.transition && this.$element[dimension](this.$element[0][scroll])
}
, hide: function () {
var dimension
if (this.transitioning || !this.$element.hasClass('in')) return
dimension = this.dimension()
this.reset(this.$element[dimension]())
this.transition('removeClass', $.Event('hide'), 'hidden')
this.$element[dimension](0)
}
, reset: function (size) {
var dimension = this.dimension()
this.$element
.removeClass('collapse')
[dimension](size || 'auto')
[0].offsetWidth
this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')
return this
}
, transition: function (method, startEvent, completeEvent) {
var that = this
, complete = function () {
if (startEvent.type == 'show') that.reset()
that.transitioning = 0
that.$element.trigger(completeEvent)
}
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
this.transitioning = 1
this.$element[method]('in')
$.support.transition && this.$element.hasClass('collapse') ?
this.$element.one($.support.transition.end, complete) :
complete()
}
, toggle: function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
}
/* COLLAPSE PLUGIN DEFINITION
* ========================== */
var old = $.fn.collapse
$.fn.collapse = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('collapse')
, options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.collapse.defaults = {
toggle: true
}
$.fn.collapse.Constructor = Collapse
/* COLLAPSE NO CONFLICT
* ==================== */
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
/* COLLAPSE DATA-API
* ================= */
$(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
var $this = $(this), href
, target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
, option = $(target).data('collapse') ? 'toggle' : $this.data()
$this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
$(target).collapse(option)
})
}(window.jQuery);
/* ============================================================
* bootstrap-dropdown.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#dropdowns
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function ($) {
"use strict"; // jshint ;_;
/* DROPDOWN CLASS DEFINITION
* ========================= */
var toggle = '[data-toggle=dropdown]'
, Dropdown = function (element) {
var $el = $(element).on('click.dropdown.data-api', this.toggle)
$('html').on('click.dropdown.data-api', function () {
$el.parent().removeClass('open')
})
}
Dropdown.prototype = {
constructor: Dropdown
, toggle: function (e) {
var $this = $(this)
, $parent
, isActive
if ($this.is('.disabled, :disabled')) return
$parent = getParent($this)
isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement) {
// if mobile we we use a backdrop because click events don't delegate
$('
').insertBefore($(this)).on('click', clearMenus)
}
$parent.toggleClass('open')
}
$this.focus()
return false
}
, keydown: function (e) {
var $this
, $items
, $active
, $parent
, isActive
, index
if (!/(38|40|27)/.test(e.keyCode)) return
$this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
$parent = getParent($this)
isActive = $parent.hasClass('open')
if (!isActive || (isActive && e.keyCode == 27)) {
if (e.which == 27) $parent.find(toggle).focus()
return $this.click()
}
$items = $('[role=menu] li:not(.divider):visible a', $parent)
if (!$items.length) return
index = $items.index($items.filter(':focus'))
if (e.keyCode == 38 && index > 0) index-- // up
if (e.keyCode == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items
.eq(index)
.focus()
}
}
function clearMenus() {
$('.dropdown-backdrop').remove()
$(toggle).each(function () {
getParent($(this)).removeClass('open')
})
}
function getParent($this) {
var selector = $this.attr('data-target')
, $parent
if (!selector) {
selector = $this.attr('href')
selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = selector && $(selector)
if (!$parent || !$parent.length) $parent = $this.parent()
return $parent
}
/* DROPDOWN PLUGIN DEFINITION
* ========================== */
var old = $.fn.dropdown
$.fn.dropdown = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('dropdown')
if (!data) $this.data('dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.dropdown.Constructor = Dropdown
/* DROPDOWN NO CONFLICT
* ==================== */
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
/* APPLY TO STANDARD DROPDOWN ELEMENTS
* =================================== */
$(document)
.on('click.dropdown.data-api', clearMenus)
.on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.dropdown.data-api' , toggle, Dropdown.prototype.toggle)
.on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)
}(window.jQuery);
/* ===========================================================
* bootstrap-modal.js v2.2.5
* ===========================================================
* Copyright 2012 Jordan Schroter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* MODAL CLASS DEFINITION
* ====================== */
var Modal = function (element, options) {
this.init(element, options);
};
Modal.prototype = {
constructor: Modal,
init: function (element, options) {
var that = this;
this.options = options;
this.$element = $(element)
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this));
this.options.remote && this.$element.find('.modal-body').load(this.options.remote, function () {
var e = $.Event('loaded');
that.$element.trigger(e);
});
var manager = typeof this.options.manager === 'function' ?
this.options.manager.call(this) : this.options.manager;
manager = manager.appendModal ?
manager : $(manager).modalmanager().data('modalmanager');
manager.appendModal(this);
},
toggle: function () {
return this[!this.isShown ? 'show' : 'hide']();
},
show: function () {
var e = $.Event('show');
if (this.isShown) return;
this.$element.trigger(e);
if (e.isDefaultPrevented()) return;
this.escape();
this.tab();
this.options.loading && this.loading();
},
hide: function (e) {
e && e.preventDefault();
e = $.Event('hide');
this.$element.trigger(e);
if (!this.isShown || e.isDefaultPrevented()) return;
this.isShown = false;
this.escape();
this.tab();
this.isLoading && this.loading();
$(document).off('focusin.modal');
this.$element
.removeClass('in')
.removeClass('animated')
.removeClass(this.options.attentionAnimation)
.removeClass('modal-overflow')
.attr('aria-hidden', true);
$.support.transition && this.$element.hasClass('fade') ?
this.hideWithTransition() :
this.hideModal();
},
layout: function () {
var prop = this.options.height ? 'height' : 'max-height',
value = this.options.height || this.options.maxHeight;
if (this.options.width){
this.$element.css('width', this.options.width);
var that = this;
this.$element.css('margin-left', function () {
if (/%/ig.test(that.options.width)){
return -(parseInt(that.options.width) / 2) + '%';
} else {
return -($(this).width() / 2) + 'px';
}
});
} else {
this.$element.css('width', '');
this.$element.css('margin-left', '');
}
this.$element.find('.modal-body')
.css('overflow', '')
.css(prop, '');
if (value){
this.$element.find('.modal-body')
.css('overflow', 'auto')
.css(prop, value);
}
var modalOverflow = $(window).height() - 10 < this.$element.height();
if (modalOverflow || this.options.modalOverflow) {
this.$element
.css('margin-top', 0)
.addClass('modal-overflow');
} else {
this.$element
.css('margin-top', 0 - this.$element.height() / 2)
.removeClass('modal-overflow');
}
},
tab: function () {
var that = this;
if (this.isShown && this.options.consumeTab) {
this.$element.on('keydown.tabindex.modal', '[data-tabindex]', function (e) {
if (e.keyCode && e.keyCode == 9){
var $next = $(this),
$rollover = $(this);
that.$element.find('[data-tabindex]:enabled:not([readonly])').each(function (e) {
if (!e.shiftKey){
$next = $next.data('tabindex') < $(this).data('tabindex') ?
$next = $(this) :
$rollover = $(this);
} else {
$next = $next.data('tabindex') > $(this).data('tabindex') ?
$next = $(this) :
$rollover = $(this);
}
});
$next[0] !== $(this)[0] ?
$next.focus() : $rollover.focus();
e.preventDefault();
}
});
} else if (!this.isShown) {
this.$element.off('keydown.tabindex.modal');
}
},
escape: function () {
var that = this;
if (this.isShown && this.options.keyboard) {
if (!this.$element.attr('tabindex')) this.$element.attr('tabindex', -1);
this.$element.on('keyup.dismiss.modal', function (e) {
e.which == 27 && that.hide();
});
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.modal')
}
},
hideWithTransition: function () {
var that = this
, timeout = setTimeout(function () {
that.$element.off($.support.transition.end);
that.hideModal();
}, 500);
this.$element.one($.support.transition.end, function () {
clearTimeout(timeout);
that.hideModal();
});
},
hideModal: function () {
var prop = this.options.height ? 'height' : 'max-height';
var value = this.options.height || this.options.maxHeight;
if (value){
this.$element.find('.modal-body')
.css('overflow', '')
.css(prop, '');
}
this.$element
.hide()
.trigger('hidden');
},
removeLoading: function () {
this.$loading.remove();
this.$loading = null;
this.isLoading = false;
},
loading: function (callback) {
callback = callback || function () {};
var animate = this.$element.hasClass('fade') ? 'fade' : '';
if (!this.isLoading) {
var doAnimate = $.support.transition && animate;
this.$loading = $('')
.append(this.options.spinner)
.appendTo(this.$element);
if (doAnimate) this.$loading[0].offsetWidth; // force reflow
this.$loading.addClass('in');
this.isLoading = true;
doAnimate ?
this.$loading.one($.support.transition.end, callback) :
callback();
} else if (this.isLoading && this.$loading) {
this.$loading.removeClass('in');
var that = this;
$.support.transition && this.$element.hasClass('fade')?
this.$loading.one($.support.transition.end, function () { that.removeLoading() }) :
that.removeLoading();
} else if (callback) {
callback(this.isLoading);
}
},
focus: function () {
var $focusElem = this.$element.find(this.options.focusOn);
$focusElem = $focusElem.length ? $focusElem : this.$element;
$focusElem.focus();
},
attention: function (){
// NOTE: transitionEnd with keyframes causes odd behaviour
if (this.options.attentionAnimation){
this.$element
.removeClass('animated')
.removeClass(this.options.attentionAnimation);
var that = this;
setTimeout(function () {
that.$element
.addClass('animated')
.addClass(that.options.attentionAnimation);
}, 0);
}
this.focus();
},
destroy: function () {
var e = $.Event('destroy');
this.$element.trigger(e);
if (e.isDefaultPrevented()) return;
this.$element
.off('.modal')
.removeData('modal')
.removeClass('in')
.attr('aria-hidden', true);
if (this.$parent !== this.$element.parent()) {
this.$element.appendTo(this.$parent);
} else if (!this.$parent.length) {
// modal is not part of the DOM so remove it.
this.$element.remove();
this.$element = null;
}
this.$element.trigger('destroyed');
}
};
/* MODAL PLUGIN DEFINITION
* ======================= */
$.fn.modal = function (option, args) {
return this.each(function () {
var $this = $(this),
data = $this.data('modal'),
options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option);
if (!data) $this.data('modal', (data = new Modal(this, options)));
if (typeof option == 'string') data[option].apply(data, [].concat(args));
else if (options.show) data.show()
})
};
$.fn.modal.defaults = {
keyboard: true,
backdrop: true,
loading: false,
show: true,
width: null,
height: null,
maxHeight: null,
modalOverflow: false,
consumeTab: true,
focusOn: null,
replace: false,
resize: false,
attentionAnimation: 'shake',
manager: 'body',
spinner: '
',
backdropTemplate: '
'
};
$.fn.modal.Constructor = Modal;
/* MODAL DATA-API
* ============== */
$(function () {
$(document).off('click.modal').on('click.modal.data-api', '[data-toggle="modal"]', function ( e ) {
var $this = $(this),
href = $this.attr('href'),
$target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))), //strip for ie7
option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data());
e.preventDefault();
$target
.modal(option)
.one('hide', function () {
$this.focus();
})
});
});
}(window.jQuery);
/* =============================================================
* bootstrap-scrollspy.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#scrollspy
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* SCROLLSPY CLASS DEFINITION
* ========================== */
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
, $element = $(element).is('body') ? $(window) : $(element)
, href
this.options = $.extend({}, $.fn.scrollspy.defaults, options)
this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process)
this.selector = (this.options.target
|| ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
|| '') + ' .nav li > a'
this.$body = $('body')
this.refresh()
this.process()
}
ScrollSpy.prototype = {
constructor: ScrollSpy
, refresh: function () {
var self = this
, $targets
this.offsets = $([])
this.targets = $([])
$targets = this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
, href = $el.data('target') || $el.attr('href')
, $href = /^#\w/.test(href) && $(href)
return ( $href
&& $href.length
&& [[ $href.position().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]] ) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
, process: function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
, scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
, maxScroll = scrollHeight - this.$scrollElement.height()
, offsets = this.offsets
, targets = this.targets
, activeTarget = this.activeTarget
, i
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets.last()[0])
&& this.activate ( i )
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate( targets[i] )
}
}
, activate: function (target) {
var active
, selector
this.activeTarget = target
$(this.selector)
.parent('.active')
.removeClass('active')
selector = this.selector
+ '[data-target="' + target + '"],'
+ this.selector + '[href="' + target + '"]'
active = $(selector)
.parent('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active.closest('li.dropdown').addClass('active')
}
active.trigger('activate')
}
}
/* SCROLLSPY PLUGIN DEFINITION
* =========================== */
var old = $.fn.scrollspy
$.fn.scrollspy = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('scrollspy')
, options = typeof option == 'object' && option
if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
$.fn.scrollspy.defaults = {
offset: 10
}
/* SCROLLSPY NO CONFLICT
* ===================== */
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
/* SCROLLSPY DATA-API
* ================== */
$(window).on('load', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(window.jQuery);
/* ========================================================
* bootstrap-tab.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#tabs
* ========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* TAB CLASS DEFINITION
* ==================== */
var Tab = function (element) {
this.element = $(element)
}
Tab.prototype = {
constructor: Tab
, show: function () {
var $this = this.element
, $ul = $this.closest('ul:not(.dropdown-menu)')
, selector = $this.attr('data-target')
, previous
, $target
, e
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ( $this.parent('li').hasClass('active') ) return
previous = $ul.find('.active:last a')[0]
e = $.Event('show', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
$target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown'
, relatedTarget: previous
})
})
}
, activate: function ( element, container, callback) {
var $active = container.find('> .active')
, transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if ( element.parent('.dropdown-menu') ) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active.one($.support.transition.end, next) :
next()
$active.removeClass('in')
}
}
/* TAB PLUGIN DEFINITION
* ===================== */
var old = $.fn.tab
$.fn.tab = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('tab')
if (!data) $this.data('tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tab.Constructor = Tab
/* TAB NO CONFLICT
* =============== */
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
/* TAB DATA-API
* ============ */
$(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
e.preventDefault()
$(this).tab('show')
})
}(window.jQuery);
/* ===========================================================
* bootstrap-tooltip.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#tooltips
* Inspired by the original jQuery.tipsy by Jason Frame
* ===========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* TOOLTIP PUBLIC CLASS DEFINITION
* =============================== */
var Tooltip = function (element, options) {
this.init('tooltip', element, options)
}
Tooltip.prototype = {
constructor: Tooltip
, init: function (type, element, options) {
var eventIn
, eventOut
, triggers
, trigger
, i
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.enabled = true
triggers = this.options.trigger.split(' ')
for (i = triggers.length; i--;) {
trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
, getOptions: function (options) {
options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay
, hide: options.delay
}
}
return options
}
, enter: function (e) {
var defaults = $.fn[this.type].defaults
, options = {}
, self
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
}, this)
self = $(e.currentTarget)[this.type](options).data(this.type)
if (!self.options.delay || !self.options.delay.show) return self.show()
clearTimeout(this.timeout)
self.hoverState = 'in'
this.timeout = setTimeout(function() {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
, leave: function (e) {
var self = $(e.currentTarget)[this.type](this._options).data(this.type)
if (this.timeout) clearTimeout(this.timeout)
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.hoverState = 'out'
this.timeout = setTimeout(function() {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
, show: function () {
var $tip
, pos
, actualWidth
, actualHeight
, placement
, tp
, e = $.Event('show')
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip = this.tip()
this.setContent()
if (this.options.animation) {
$tip.addClass('fade')
}
placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
pos = this.getPosition()
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
switch (placement) {
case 'bottom':
tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}
break
case 'top':
tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}
break
case 'left':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}
break
case 'right':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
break
}
this.applyPlacement(tp, placement)
this.$element.trigger('shown')
}
}
, applyPlacement: function(offset, placement){
var $tip = this.tip()
, width = $tip[0].offsetWidth
, height = $tip[0].offsetHeight
, actualWidth
, actualHeight
, delta
, replace
$tip
.offset(offset)
.addClass(placement)
.addClass('in')
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
replace = true
}
if (placement == 'bottom' || placement == 'top') {
delta = 0
if (offset.left < 0){
delta = offset.left * -2
offset.left = 0
$tip.offset(offset)
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
}
this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
} else {
this.replaceArrow(actualHeight - height, actualHeight, 'top')
}
if (replace) $tip.offset(offset)
}
, replaceArrow: function(delta, dimension, position){
this
.arrow()
.css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
}
, setContent: function () {
var $tip = this.tip()
, title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
, hide: function () {
var that = this
, $tip = this.tip()
, e = $.Event('hide')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
function removeWithAnimation() {
var timeout = setTimeout(function () {
$tip.off($.support.transition.end).detach()
}, 500)
$tip.one($.support.transition.end, function () {
clearTimeout(timeout)
$tip.detach()
})
}
$.support.transition && this.$tip.hasClass('fade') ?
removeWithAnimation() :
$tip.detach()
this.$element.trigger('hidden')
return this
}
, fixTitle: function () {
var $e = this.$element
if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
, hasContent: function () {
return this.getTitle()
}
, getPosition: function () {
var el = this.$element[0]
return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
width: el.offsetWidth
, height: el.offsetHeight
}, this.$element.offset())
}
, getTitle: function () {
var title
, $e = this.$element
, o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
, tip: function () {
return this.$tip = this.$tip || $(this.options.template)
}
, arrow: function(){
return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow")
}
, validate: function () {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
}
, enable: function () {
this.enabled = true
}
, disable: function () {
this.enabled = false
}
, toggleEnabled: function () {
this.enabled = !this.enabled
}
, toggle: function (e) {
var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this
self.tip().hasClass('in') ? self.hide() : self.show()
}
, destroy: function () {
this.hide().$element.off('.' + this.type).removeData(this.type)
}
}
/* TOOLTIP PLUGIN DEFINITION
* ========================= */
var old = $.fn.tooltip
$.fn.tooltip = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('tooltip')
, options = typeof option == 'object' && option
if (!data) $this.data('tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tooltip.Constructor = Tooltip
$.fn.tooltip.defaults = {
animation: true
, placement: 'top'
, selector: false
, template: '
'
, trigger: 'hover focus'
, title: ''
, delay: 0
, html: false
, container: false
}
/* TOOLTIP NO CONFLICT
* =================== */
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(window.jQuery);
/* ===========================================================
* bootstrap-popover.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#popovers
* ===========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* POPOVER PUBLIC CLASS DEFINITION
* =============================== */
var Popover = function (element, options) {
this.init('popover', element, options)
}
/* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js
========================================== */
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, {
constructor: Popover
, setContent: function () {
var $tip = this.tip()
, title = this.getTitle()
, content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content)
$tip.removeClass('fade top bottom left right in')
}
, hasContent: function () {
return this.getTitle() || this.getContent()
}
, getContent: function () {
var content
, $e = this.$element
, o = this.options
content = (typeof o.content == 'function' ? o.content.call($e[0]) : o.content)
|| $e.attr('data-content')
return content
}
, tip: function () {
if (!this.$tip) {
this.$tip = $(this.options.template)
}
return this.$tip
}
, destroy: function () {
this.hide().$element.off('.' + this.type).removeData(this.type)
}
})
/* POPOVER PLUGIN DEFINITION
* ======================= */
var old = $.fn.popover
$.fn.popover = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('popover')
, options = typeof option == 'object' && option
if (!data) $this.data('popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.popover.Constructor = Popover
$.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, {
placement: 'right'
, trigger: 'click'
, content: ''
, template: '
'
})
/* POPOVER NO CONFLICT
* =================== */
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(window.jQuery);
/* =============================================================
* bootstrap-typeahead.js v2.3.2
* http://twitter.github.com/bootstrap/javascript.html#typeahead
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function($){
"use strict"; // jshint ;_;
/* TYPEAHEAD PUBLIC CLASS DEFINITION
* ================================= */
var Typeahead = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.typeahead.defaults, options)
this.matcher = this.options.matcher || this.matcher
this.sorter = this.options.sorter || this.sorter
this.highlighter = this.options.highlighter || this.highlighter
this.updater = this.options.updater || this.updater
this.source = this.options.source
this.$menu = $(this.options.menu)
this.shown = false
this.listen()
}
Typeahead.prototype = {
constructor: Typeahead
, select: function () {
var val = this.$menu.find('.active').attr('data-value')
this.$element
.val(this.updater(val))
.change()
return this.hide()
}
, updater: function (item) {
return item
}
, show: function () {
var pos = $.extend({}, this.$element.position(), {
height: this.$element[0].offsetHeight
})
this.$menu
.insertAfter(this.$element)
.css({
top: pos.top + pos.height
, left: pos.left
})
.show()
this.shown = true
return this
}
, hide: function () {
this.$menu.hide()
this.shown = false
return this
}
, lookup: function (event) {
var items
this.query = this.$element.val()
if (!this.query || this.query.length < this.options.minLength) {
return this.shown ? this.hide() : this
}
items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source
return items ? this.process(items) : this
}
, process: function (items) {
var that = this
items = $.grep(items, function (item) {
return that.matcher(item)
})
items = this.sorter(items)
if (!items.length) {
return this.shown ? this.hide() : this
}
return this.render(items.slice(0, this.options.items)).show()
}
, matcher: function (item) {
return ~item.toLowerCase().indexOf(this.query.toLowerCase())
}
, sorter: function (items) {
var beginswith = []
, caseSensitive = []
, caseInsensitive = []
, item
while (item = items.shift()) {
if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
else if (~item.indexOf(this.query)) caseSensitive.push(item)
else caseInsensitive.push(item)
}
return beginswith.concat(caseSensitive, caseInsensitive)
}
, highlighter: function (item) {
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '
' + match + ' '
})
}
, render: function (items) {
var that = this
items = $(items).map(function (i, item) {
i = $(that.options.item).attr('data-value', item)
i.find('a').html(that.highlighter(item))
return i[0]
})
items.first().addClass('active')
this.$menu.html(items)
return this
}
, next: function (event) {
var active = this.$menu.find('.active').removeClass('active')
, next = active.next()
if (!next.length) {
next = $(this.$menu.find('li')[0])
}
next.addClass('active')
}
, prev: function (event) {
var active = this.$menu.find('.active').removeClass('active')
, prev = active.prev()
if (!prev.length) {
prev = this.$menu.find('li').last()
}
prev.addClass('active')
}
, listen: function () {
this.$element
.on('focus', $.proxy(this.focus, this))
.on('blur', $.proxy(this.blur, this))
.on('keypress', $.proxy(this.keypress, this))
.on('keyup', $.proxy(this.keyup, this))
if (this.eventSupported('keydown')) {
this.$element.on('keydown', $.proxy(this.keydown, this))
}
this.$menu
.on('click', $.proxy(this.click, this))
.on('mouseenter', 'li', $.proxy(this.mouseenter, this))
.on('mouseleave', 'li', $.proxy(this.mouseleave, this))
}
, eventSupported: function(eventName) {
var isSupported = eventName in this.$element
if (!isSupported) {
this.$element.setAttribute(eventName, 'return;')
isSupported = typeof this.$element[eventName] === 'function'
}
return isSupported
}
, move: function (e) {
if (!this.shown) return
switch(e.keyCode) {
case 9: // tab
case 13: // enter
case 27: // escape
e.preventDefault()
break
case 38: // up arrow
e.preventDefault()
this.prev()
break
case 40: // down arrow
e.preventDefault()
this.next()
break
}
e.stopPropagation()
}
, keydown: function (e) {
this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27])
this.move(e)
}
, keypress: function (e) {
if (this.suppressKeyPressRepeat) return
this.move(e)
}
, keyup: function (e) {
switch(e.keyCode) {
case 40: // down arrow
case 38: // up arrow
case 16: // shift
case 17: // ctrl
case 18: // alt
break
case 9: // tab
case 13: // enter
if (!this.shown) return
this.select()
break
case 27: // escape
if (!this.shown) return
this.hide()
break
default:
this.lookup()
}
e.stopPropagation()
e.preventDefault()
}
, focus: function (e) {
this.focused = true
}
, blur: function (e) {
this.focused = false
if (!this.mousedover && this.shown) this.hide()
}
, click: function (e) {
e.stopPropagation()
e.preventDefault()
this.select()
this.$element.focus()
}
, mouseenter: function (e) {
this.mousedover = true
this.$menu.find('.active').removeClass('active')
$(e.currentTarget).addClass('active')
}
, mouseleave: function (e) {
this.mousedover = false
if (!this.focused && this.shown) this.hide()
}
}
/* TYPEAHEAD PLUGIN DEFINITION
* =========================== */
var old = $.fn.typeahead
$.fn.typeahead = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('typeahead')
, options = typeof option == 'object' && option
if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.typeahead.defaults = {
source: []
, items: 8
, menu: ''
, item: '
'
, minLength: 1
}
$.fn.typeahead.Constructor = Typeahead
/* TYPEAHEAD NO CONFLICT
* =================== */
$.fn.typeahead.noConflict = function () {
$.fn.typeahead = old
return this
}
/* TYPEAHEAD DATA-API
* ================== */
$(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
var $this = $(this)
if ($this.data('typeahead')) return
$this.typeahead($this.data())
})
}(window.jQuery);
/* ===========================================================
* bootstrap-modalmanager.js v2.2.5
* ===========================================================
* Copyright 2012 Jordan Schroter.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* MODAL MANAGER CLASS DEFINITION
* ====================== */
var ModalManager = function (element, options) {
this.init(element, options);
};
ModalManager.prototype = {
constructor: ModalManager,
init: function (element, options) {
this.$element = $(element);
this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
this.stack = [];
this.backdropCount = 0;
if (this.options.resize) {
var resizeTimeout,
that = this;
$(window).on('resize.modal', function(){
resizeTimeout && clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(function(){
for (var i = 0; i < that.stack.length; i++){
that.stack[i].isShown && that.stack[i].layout();
}
}, 10);
});
}
},
createModal: function (element, options) {
$(element).modal($.extend({ manager: this }, options));
},
appendModal: function (modal) {
this.stack.push(modal);
var that = this;
modal.$element.on('show.modalmanager', targetIsSelf(function (e) {
var showModal = function(){
modal.isShown = true;
var transition = $.support.transition && modal.$element.hasClass('fade');
that.$element
.toggleClass('modal-open', that.hasOpenModal())
.toggleClass('page-overflow', $(window).height() < that.$element.height());
modal.$parent = modal.$element.parent();
modal.$container = that.createContainer(modal);
modal.$element.appendTo(modal.$container);
that.backdrop(modal, function () {
modal.$element.show();
if (transition) {
//modal.$element[0].style.display = 'run-in';
modal.$element[0].offsetWidth;
//modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
}
modal.layout();
modal.$element
.addClass('in')
.attr('aria-hidden', false);
var complete = function () {
that.setFocus();
modal.$element.trigger('shown');
};
transition ?
modal.$element.one($.support.transition.end, complete) :
complete();
});
};
modal.options.replace ?
that.replace(showModal) :
showModal();
}));
modal.$element.on('hidden.modalmanager', targetIsSelf(function (e) {
that.backdrop(modal);
// handle the case when a modal may have been removed from the dom before this callback executes
if (!modal.$element.parent().length) {
that.destroyModal(modal);
} else if (modal.$backdrop){
var transition = $.support.transition && modal.$element.hasClass('fade');
// trigger a relayout due to firebox's buggy transition end event
if (transition) { modal.$element[0].offsetWidth; }
$.support.transition && modal.$element.hasClass('fade') ?
modal.$backdrop.one($.support.transition.end, function () { modal.destroy(); }) :
modal.destroy();
} else {
modal.destroy();
}
}));
modal.$element.on('destroyed.modalmanager', targetIsSelf(function (e) {
that.destroyModal(modal);
}));
},
getOpenModals: function () {
var openModals = [];
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) openModals.push(this.stack[i]);
}
return openModals;
},
hasOpenModal: function () {
return this.getOpenModals().length > 0;
},
setFocus: function () {
var topModal;
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) topModal = this.stack[i];
}
if (!topModal) return;
topModal.focus();
},
destroyModal: function (modal) {
modal.$element.off('.modalmanager');
if (modal.$backdrop) this.removeBackdrop(modal);
this.stack.splice(this.getIndexOfModal(modal), 1);
var hasOpenModal = this.hasOpenModal();
this.$element.toggleClass('modal-open', hasOpenModal);
if (!hasOpenModal){
this.$element.removeClass('page-overflow');
}
this.removeContainer(modal);
this.setFocus();
},
getModalAt: function (index) {
return this.stack[index];
},
getIndexOfModal: function (modal) {
for (var i = 0; i < this.stack.length; i++){
if (modal === this.stack[i]) return i;
}
},
replace: function (callback) {
var topModal;
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) topModal = this.stack[i];
}
if (topModal) {
this.$backdropHandle = topModal.$backdrop;
topModal.$backdrop = null;
callback && topModal.$element.one('hidden',
targetIsSelf( $.proxy(callback, this) ));
topModal.hide();
} else if (callback) {
callback();
}
},
removeBackdrop: function (modal) {
modal.$backdrop.remove();
modal.$backdrop = null;
},
createBackdrop: function (animate, tmpl) {
var $backdrop;
if (!this.$backdropHandle) {
$backdrop = $(tmpl)
.addClass(animate)
.appendTo(this.$element);
} else {
$backdrop = this.$backdropHandle;
$backdrop.off('.modalmanager');
this.$backdropHandle = null;
this.isLoading && this.removeSpinner();
}
return $backdrop;
},
removeContainer: function (modal) {
modal.$container.remove();
modal.$container = null;
},
createContainer: function (modal) {
var $container;
$container = $('
')
.css('z-index', getzIndex('modal', this.getOpenModals().length))
.appendTo(this.$element);
if (modal && modal.options.backdrop != 'static') {
$container.on('click.modal', targetIsSelf(function (e) {
modal.hide();
}));
} else if (modal) {
$container.on('click.modal', targetIsSelf(function (e) {
modal.attention();
}));
}
return $container;
},
backdrop: function (modal, callback) {
var animate = modal.$element.hasClass('fade') ? 'fade' : '',
showBackdrop = modal.options.backdrop &&
this.backdropCount < this.options.backdropLimit;
if (modal.isShown && showBackdrop) {
var doAnimate = $.support.transition && animate && !this.$backdropHandle;
modal.$backdrop = this.createBackdrop(animate, modal.options.backdropTemplate);
modal.$backdrop.css('z-index', getzIndex( 'backdrop', this.getOpenModals().length ));
if (doAnimate) modal.$backdrop[0].offsetWidth; // force reflow
modal.$backdrop.addClass('in');
this.backdropCount += 1;
doAnimate ?
modal.$backdrop.one($.support.transition.end, callback) :
callback();
} else if (!modal.isShown && modal.$backdrop) {
modal.$backdrop.removeClass('in');
this.backdropCount -= 1;
var that = this;
$.support.transition && modal.$element.hasClass('fade')?
modal.$backdrop.one($.support.transition.end, function () { that.removeBackdrop(modal) }) :
that.removeBackdrop(modal);
} else if (callback) {
callback();
}
},
removeSpinner: function(){
this.$spinner && this.$spinner.remove();
this.$spinner = null;
this.isLoading = false;
},
removeLoading: function () {
this.$backdropHandle && this.$backdropHandle.remove();
this.$backdropHandle = null;
this.removeSpinner();
},
loading: function (callback) {
callback = callback || function () { };
this.$element
.toggleClass('modal-open', !this.isLoading || this.hasOpenModal())
.toggleClass('page-overflow', $(window).height() < this.$element.height());
if (!this.isLoading) {
this.$backdropHandle = this.createBackdrop('fade', this.options.backdropTemplate);
this.$backdropHandle[0].offsetWidth; // force reflow
var openModals = this.getOpenModals();
this.$backdropHandle
.css('z-index', getzIndex('backdrop', openModals.length + 1))
.addClass('in');
var $spinner = $(this.options.spinner)
.css('z-index', getzIndex('modal', openModals.length + 1))
.appendTo(this.$element)
.addClass('in');
this.$spinner = $(this.createContainer())
.append($spinner)
.on('click.modalmanager', $.proxy(this.loading, this));
this.isLoading = true;
$.support.transition ?
this.$backdropHandle.one($.support.transition.end, callback) :
callback();
} else if (this.isLoading && this.$backdropHandle) {
this.$backdropHandle.removeClass('in');
var that = this;
$.support.transition ?
this.$backdropHandle.one($.support.transition.end, function () { that.removeLoading() }) :
that.removeLoading();
} else if (callback) {
callback(this.isLoading);
}
}
};
/* PRIVATE METHODS
* ======================= */
// computes and caches the zindexes
var getzIndex = (function () {
var zIndexFactor,
baseIndex = {};
return function (type, pos) {
if (typeof zIndexFactor === 'undefined'){
var $baseModal = $('
').appendTo('body'),
$baseBackdrop = $('
').appendTo('body');
baseIndex['modal'] = +$baseModal.css('z-index');
baseIndex['backdrop'] = +$baseBackdrop.css('z-index');
zIndexFactor = baseIndex['modal'] - baseIndex['backdrop'];
$baseModal.remove();
$baseBackdrop.remove();
$baseBackdrop = $baseModal = null;
}
return baseIndex[type] + (zIndexFactor * pos);
}
}());
// make sure the event target is the modal itself in order to prevent
// other components such as tabsfrom triggering the modal manager.
// if Boostsrap namespaced events, this would not be needed.
function targetIsSelf(callback){
return function (e) {
if (e && this === e.target){
return callback.apply(this, arguments);
}
}
}
/* MODAL MANAGER PLUGIN DEFINITION
* ======================= */
$.fn.modalmanager = function (option, args) {
return this.each(function () {
var $this = $(this),
data = $this.data('modalmanager');
if (!data) $this.data('modalmanager', (data = new ModalManager(this, option)));
if (typeof option === 'string') data[option].apply(data, [].concat(args))
})
};
$.fn.modalmanager.defaults = {
backdropLimit: 999,
resize: true,
spinner: '
',
backdropTemplate: '
'
};
$.fn.modalmanager.Constructor = ModalManager
// ModalManager handles the modal-open class so we need
// to remove conflicting bootstrap 3 event handlers
$(function () {
$(document).off('show.bs.modal').off('hidden.bs.modal');
});
}(jQuery);
/**
* bootbox.js [master branch]
*
* http://bootboxjs.com/license.txt
*/
// @see https://github.com/makeusabrew/bootbox/issues/180
// @see https://github.com/makeusabrew/bootbox/issues/186
(function (root, factory) {
"use strict";
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery"], factory);
} else if (typeof exports === "object") {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
// Browser globals (root is window)
root.bootbox = factory(root.jQuery);
}
}(this, function init($, undefined) {
"use strict";
// the base DOM structure needed to create a modal
var templates = {
dialog:
"
",
header:
"",
footer:
"",
closeButton:
"
× ",
form:
"
",
inputs: {
text:
"
",
textarea:
"
",
email:
"
",
select:
"
",
checkbox:
"
",
date:
"
",
time:
"
",
number:
"
",
password:
"
"
}
};
var defaults = {
// default language
locale: "en",
// show backdrop or not
backdrop: true,
// animate the modal in/out
animate: true,
// additional class string applied to the top level dialog
className: null,
// whether or not to include a close button
closeButton: true,
// show the dialog immediately by default
show: true,
// dialog container
container: "body"
};
// our public object; augmented after our private API
var exports = {};
/**
* @private
*/
function _t(key) {
var locale = locales[defaults.locale];
return locale ? locale[key] : locales.en[key];
}
function processCallback(e, dialog, callback) {
e.stopPropagation();
e.preventDefault();
// by default we assume a callback will get rid of the dialog,
// although it is given the opportunity to override this
// so, if the callback can be invoked and it *explicitly returns false*
// then we'll set a flag to keep the dialog active...
var preserveDialog = $.isFunction(callback) && callback(e) === false;
// ... otherwise we'll bin it
if (!preserveDialog) {
dialog.modal("hide");
}
}
function getKeyLength(obj) {
// @TODO defer to Object.keys(x).length if available?
var k, t = 0;
for (k in obj) {
t ++;
}
return t;
}
function each(collection, iterator) {
var index = 0;
$.each(collection, function(key, value) {
iterator(key, value, index++);
});
}
function sanitize(options) {
var buttons;
var total;
if (typeof options !== "object") {
throw new Error("Please supply an object of options");
}
if (!options.message) {
throw new Error("Please specify a message");
}
// make sure any supplied options take precedence over defaults
options = $.extend({}, defaults, options);
if (!options.buttons) {
options.buttons = {};
}
// we only support Bootstrap's "static" and false backdrop args
// supporting true would mean you could dismiss the dialog without
// explicitly interacting with it
options.backdrop = options.backdrop ? "static" : false;
buttons = options.buttons;
total = getKeyLength(buttons);
each(buttons, function(key, button, index) {
if ($.isFunction(button)) {
// short form, assume value is our callback. Since button
// isn't an object it isn't a reference either so re-assign it
button = buttons[key] = {
callback: button
};
}
// before any further checks make sure by now button is the correct type
if ($.type(button) !== "object") {
throw new Error("button with key " + key + " must be an object");
}
if (!button.label) {
// the lack of an explicit label means we'll assume the key is good enough
button.label = key;
}
if (!button.className) {
if (total <= 2 && index === total-1) {
// always add a primary to the main option in a two-button dialog
button.className = "btn-primary";
} else {
button.className = "btn-default";
}
}
});
return options;
}
/**
* map a flexible set of arguments into a single returned object
* if args.length is already one just return it, otherwise
* use the properties argument to map the unnamed args to
* object properties
* so in the latter case:
* mapArguments(["foo", $.noop], ["message", "callback"])
* -> { message: "foo", callback: $.noop }
*/
function mapArguments(args, properties) {
var argn = args.length;
var options = {};
if (argn < 1 || argn > 2) {
throw new Error("Invalid argument length");
}
if (argn === 2 || typeof args[0] === "string") {
options[properties[0]] = args[0];
options[properties[1]] = args[1];
} else {
options = args[0];
}
return options;
}
/**
* merge a set of default dialog options with user supplied arguments
*/
function mergeArguments(defaults, args, properties) {
return $.extend(
// deep merge
true,
// ensure the target is an empty, unreferenced object
{},
// the base options object for this type of dialog (often just buttons)
defaults,
// args could be an object or array; if it's an array properties will
// map it to a proper options object
mapArguments(
args,
properties
)
);
}
/**
* this entry-level method makes heavy use of composition to take a simple
* range of inputs and return valid options suitable for passing to bootbox.dialog
*/
function mergeDialogOptions(className, labels, properties, args) {
// build up a base set of dialog properties
var baseOptions = {
className: "bootbox-" + className,
buttons: createLabels.apply(null, labels)
};
// ensure the buttons properties generated, *after* merging
// with user args are still valid against the supplied labels
return validateButtons(
// merge the generated base properties with user supplied arguments
mergeArguments(
baseOptions,
args,
// if args.length > 1, properties specify how each arg maps to an object key
properties
),
labels
);
}
/**
* from a given list of arguments return a suitable object of button labels
* all this does is normalise the given labels and translate them where possible
* e.g. "ok", "confirm" -> { ok: "OK, cancel: "Annuleren" }
*/
function createLabels() {
var buttons = {};
for (var i = 0, j = arguments.length; i < j; i++) {
var argument = arguments[i];
var key = argument.toLowerCase();
var value = argument.toUpperCase();
buttons[key] = {
label: _t(value)
};
}
return buttons;
}
function validateButtons(options, buttons) {
var allowedButtons = {};
each(buttons, function(key, value) {
allowedButtons[value] = true;
});
each(options.buttons, function(key) {
if (allowedButtons[key] === undefined) {
throw new Error("button key " + key + " is not allowed (options are " + buttons.join("\n") + ")");
}
});
return options;
}
exports.alert = function() {
var options;
options = mergeDialogOptions("alert", ["ok"], ["message", "callback"], arguments);
if (options.callback && !$.isFunction(options.callback)) {
throw new Error("alert requires callback property to be a function when provided");
}
/**
* overrides
*/
options.buttons.ok.callback = options.onEscape = function() {
if ($.isFunction(options.callback)) {
return options.callback();
}
return true;
};
return exports.dialog(options);
};
exports.confirm = function() {
var options;
options = mergeDialogOptions("confirm", ["cancel", "confirm"], ["message", "callback"], arguments);
/**
* overrides; undo anything the user tried to set they shouldn't have
*/
options.buttons.cancel.callback = options.onEscape = function() {
return options.callback(false);
};
options.buttons.confirm.callback = function() {
return options.callback(true);
};
// confirm specific validation
if (!$.isFunction(options.callback)) {
throw new Error("confirm requires a callback");
}
return exports.dialog(options);
};
exports.prompt = function() {
var options;
var defaults;
var dialog;
var form;
var input;
var shouldShow;
var inputOptions;
// we have to create our form first otherwise
// its value is undefined when gearing up our options
// @TODO this could be solved by allowing message to
// be a function instead...
form = $(templates.form);
// prompt defaults are more complex than others in that
// users can override more defaults
// @TODO I don't like that prompt has to do a lot of heavy
// lifting which mergeDialogOptions can *almost* support already
// just because of 'value' and 'inputType' - can we refactor?
defaults = {
className: "bootbox-prompt",
buttons: createLabels("cancel", "confirm"),
value: "",
inputType: "text"
};
options = validateButtons(
mergeArguments(defaults, arguments, ["title", "callback"]),
["cancel", "confirm"]
);
// capture the user's show value; we always set this to false before
// spawning the dialog to give us a chance to attach some handlers to
// it, but we need to make sure we respect a preference not to show it
shouldShow = (options.show === undefined) ? true : options.show;
// check if the browser supports the option.inputType
var html5inputs = ["date","time","number"];
var i = document.createElement("input");
i.setAttribute("type", options.inputType);
if(html5inputs[options.inputType]){
options.inputType = i.type;
}
/**
* overrides; undo anything the user tried to set they shouldn't have
*/
options.message = form;
options.buttons.cancel.callback = options.onEscape = function() {
return options.callback(null);
};
options.buttons.confirm.callback = function() {
var value;
switch (options.inputType) {
case "text":
case "textarea":
case "email":
case "select":
case "date":
case "time":
case "number":
case "password":
value = input.val();
break;
case "checkbox":
var checkedItems = input.find("input:checked");
// we assume that checkboxes are always multiple,
// hence we default to an empty array
value = [];
each(checkedItems, function(_, item) {
value.push($(item).val());
});
break;
}
return options.callback(value);
};
options.show = false;
// prompt specific validation
if (!options.title) {
throw new Error("prompt requires a title");
}
if (!$.isFunction(options.callback)) {
throw new Error("prompt requires a callback");
}
if (!templates.inputs[options.inputType]) {
throw new Error("invalid prompt type");
}
// create the input based on the supplied type
input = $(templates.inputs[options.inputType]);
switch (options.inputType) {
case "text":
case "textarea":
case "email":
case "date":
case "time":
case "number":
case "password":
input.val(options.value);
break;
case "select":
var groups = {};
inputOptions = options.inputOptions || [];
if (!inputOptions.length) {
throw new Error("prompt with select requires options");
}
each(inputOptions, function(_, option) {
// assume the element to attach to is the input...
var elem = input;
if (option.value === undefined || option.text === undefined) {
throw new Error("given options in wrong format");
}
// ... but override that element if this option sits in a group
if (option.group) {
// initialise group if necessary
if (!groups[option.group]) {
groups[option.group] = $("
").attr("label", option.group);
}
elem = groups[option.group];
}
elem.append("
" + option.text + " ");
});
each(groups, function(_, group) {
input.append(group);
});
// safe to set a select's value as per a normal input
input.val(options.value);
break;
case "checkbox":
var values = $.isArray(options.value) ? options.value : [options.value];
inputOptions = options.inputOptions || [];
if (!inputOptions.length) {
throw new Error("prompt with checkbox requires options");
}
if (!inputOptions[0].value || !inputOptions[0].text) {
throw new Error("given options in wrong format");
}
// checkboxes have to nest within a containing element, so
// they break the rules a bit and we end up re-assigning
// our 'input' element to this container instead
input = $("
");
each(inputOptions, function(_, option) {
var checkbox = $(templates.inputs[options.inputType]);
checkbox.find("input").attr("value", option.value);
checkbox.find("label").append(option.text);
// we've ensured values is an array so we can always iterate over it
each(values, function(_, value) {
if (value === option.value) {
checkbox.find("input").prop("checked", true);
}
});
input.append(checkbox);
});
break;
}
if (options.placeholder) {
input.attr("placeholder", options.placeholder);
}
if(options.pattern){
input.attr("pattern", options.pattern);
}
// now place it in our form
form.append(input);
form.on("submit", function(e) {
e.preventDefault();
// Fix for SammyJS (or similar JS routing library) hijacking the form post.
e.stopPropagation();
// @TODO can we actually click *the* button object instead?
// e.g. buttons.confirm.click() or similar
dialog.find(".btn-primary").click();
});
dialog = exports.dialog(options);
// clear the existing handler focusing the submit button...
dialog.off("shown.bs.modal");
// ...and replace it with one focusing our input, if possible
dialog.on("shown.bs.modal", function() {
input.focus();
});
if (shouldShow === true) {
dialog.modal("show");
}
return dialog;
};
exports.dialog = function(options) {
options = sanitize(options);
var dialog = $(templates.dialog);
var innerDialog = dialog.find(".modal-dialog");
var body = dialog.find(".modal-body");
var buttons = options.buttons;
var buttonStr = "";
var callbacks = {
onEscape: options.onEscape
};
each(buttons, function(key, button) {
// @TODO I don't like this string appending to itself; bit dirty. Needs reworking
// can we just build up button elements instead? slower but neater. Then button
// can just become a template too
buttonStr += "
" + button.label + " ";
callbacks[key] = button.callback;
});
body.find(".bootbox-body").html(options.message);
if (options.animate === true) {
dialog.addClass("fade");
}
if (options.className) {
dialog.addClass(options.className);
}
if (options.size === "large") {
innerDialog.addClass("modal-lg");
}
if (options.size === "small") {
innerDialog.addClass("modal-sm");
}
if (options.title) {
body.before(templates.header);
}
if (options.closeButton) {
var closeButton = $(templates.closeButton);
if (options.title) {
dialog.find(".modal-header").prepend(closeButton);
} else {
closeButton.css("margin-top", "-10px").prependTo(body);
}
}
if (options.title) {
dialog.find(".modal-title").html(options.title);
}
if (buttonStr.length) {
body.after(templates.footer);
dialog.find(".modal-footer").html(buttonStr);
}
/**
* Bootstrap event listeners; used handle extra
* setup & teardown required after the underlying
* modal has performed certain actions
*/
dialog.on("hidden.bs.modal", function(e) {
// ensure we don't accidentally intercept hidden events triggered
// by children of the current dialog. We shouldn't anymore now BS
// namespaces its events; but still worth doing
if (e.target === this) {
dialog.remove();
}
});
/*
dialog.on("show.bs.modal", function() {
// sadly this doesn't work; show is called *just* before
// the backdrop is added so we'd need a setTimeout hack or
// otherwise... leaving in as would be nice
if (options.backdrop) {
dialog.next(".modal-backdrop").addClass("bootbox-backdrop");
}
});
*/
dialog.on("shown.bs.modal", function() {
dialog.find(".btn-primary:first").focus();
});
/**
* Bootbox event listeners; experimental and may not last
* just an attempt to decouple some behaviours from their
* respective triggers
*/
dialog.on("escape.close.bb", function(e) {
if (callbacks.onEscape) {
processCallback(e, dialog, callbacks.onEscape);
}
});
/**
* Standard jQuery event listeners; used to handle user
* interaction with our dialog
*/
dialog.on("click", ".modal-footer button", function(e) {
var callbackKey = $(this).data("bb-handler");
processCallback(e, dialog, callbacks[callbackKey]);
});
dialog.on("click", ".bootbox-close-button", function(e) {
// onEscape might be falsy but that's fine; the fact is
// if the user has managed to click the close button we
// have to close the dialog, callback or not
processCallback(e, dialog, callbacks.onEscape);
});
dialog.on("keyup", function(e) {
if (e.which === 27) {
dialog.trigger("escape.close.bb");
}
});
// the remainder of this method simply deals with adding our
// dialogent to the DOM, augmenting it with Bootstrap's modal
// functionality and then giving the resulting object back
// to our caller
$(options.container).append(dialog);
dialog.modal({
backdrop: options.backdrop,
keyboard: false,
show: false
});
if (options.show) {
dialog.modal("show");
}
// @TODO should we return the raw element here or should
// we wrap it in an object on which we can expose some neater
// methods, e.g. var d = bootbox.alert(); d.hide(); instead
// of d.modal("hide");
/*
function BBDialog(elem) {
this.elem = elem;
}
BBDialog.prototype = {
hide: function() {
return this.elem.modal("hide");
},
show: function() {
return this.elem.modal("show");
}
};
*/
return dialog;
};
exports.setDefaults = function() {
var values = {};
if (arguments.length === 2) {
// allow passing of single key/value...
values[arguments[0]] = arguments[1];
} else {
// ... and as an object too
values = arguments[0];
}
$.extend(defaults, values);
};
exports.hideAll = function() {
$(".bootbox").modal("hide");
};
/**
* standard locales. Please add more according to ISO 639-1 standard. Multiple language variants are
* unlikely to be required. If this gets too large it can be split out into separate JS files.
*/
var locales = {
br : {
OK : "OK",
CANCEL : "Cancelar",
CONFIRM : "Sim"
},
da : {
OK : "OK",
CANCEL : "Annuller",
CONFIRM : "Accepter"
},
de : {
OK : "OK",
CANCEL : "Abbrechen",
CONFIRM : "Akzeptieren"
},
el : {
OK : "Εντάξει",
CANCEL : "ΑκÏÏωση",
CONFIRM : "Επιβεβαίωση"
},
en : {
OK : "OK",
CANCEL : "Cancel",
CONFIRM : "OK"
},
es : {
OK : "OK",
CANCEL : "Cancelar",
CONFIRM : "Aceptar"
},
fi : {
OK : "OK",
CANCEL : "Peruuta",
CONFIRM : "OK"
},
fr : {
OK : "OK",
CANCEL : "Annuler",
CONFIRM : "D'accord"
},
he : {
OK : "×ישור",
CANCEL : "ביטול",
CONFIRM : "×ישור"
},
it : {
OK : "OK",
CANCEL : "Annulla",
CONFIRM : "Conferma"
},
lt : {
OK : "Gerai",
CANCEL : "Atšaukti",
CONFIRM : "Patvirtinti"
},
lv : {
OK : "Labi",
CANCEL : "Atcelt",
CONFIRM : "ApstiprinÄt"
},
nl : {
OK : "OK",
CANCEL : "Annuleren",
CONFIRM : "Accepteren"
},
no : {
OK : "OK",
CANCEL : "Avbryt",
CONFIRM : "OK"
},
pl : {
OK : "OK",
CANCEL : "Anuluj",
CONFIRM : "Potwierdź"
},
ru : {
OK : "OK",
CANCEL : "Отмена",
CONFIRM : "Применить"
},
sv : {
OK : "OK",
CANCEL : "Avbryt",
CONFIRM : "OK"
},
tr : {
OK : "Tamam",
CANCEL : "Ä°ptal",
CONFIRM : "Onayla"
},
zh_CN : {
OK : "OK",
CANCEL : "å–消",
CONFIRM : "确认"
},
zh_TW : {
OK : "OK",
CANCEL : "å–消",
CONFIRM : "確èª"
}
};
exports.init = function(_$) {
return init(_$ || $);
};
return exports;
}));
// Underscore.js 1.6.0
// http://underscorejs.org
// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.6.0';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return obj;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, length = obj.length; i < length; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
}
}
return obj;
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var length = obj.length;
if (length !== +length) {
var keys = _.keys(obj);
length = keys.length;
}
each(obj, function(value, index, list) {
index = keys ? keys[--length] : --length;
if (!initial) {
memo = obj[index];
initial = true;
} else {
memo = iterator.call(context, memo, obj[index], index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var result;
any(obj, function(value, index, list) {
if (predicate.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context);
each(obj, function(value, index, list) {
if (predicate.call(context, value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, function(value, index, list) {
return !predicate.call(context, value, index, list);
}, context);
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
predicate || (predicate = _.identity);
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context);
each(obj, function(value, index, list) {
if (!(result = result && predicate.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, predicate, context) {
predicate || (predicate = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context);
each(obj, function(value, index, list) {
if (result || (result = predicate.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
return any(obj, function(value) {
return value === target;
});
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matches(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matches(attrs));
};
// Return the maximum element or (element-based computation).
// Can't optimize arrays of integers longer than 65,535 elements.
// See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797)
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.max.apply(Math, obj);
}
var result = -Infinity, lastComputed = -Infinity;
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
if (computed > lastComputed) {
result = value;
lastComputed = computed;
}
});
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.min.apply(Math, obj);
}
var result = Infinity, lastComputed = Infinity;
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
if (computed < lastComputed) {
result = value;
lastComputed = computed;
}
});
return result;
};
// Shuffle an array, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var rand;
var index = 0;
var shuffled = [];
each(obj, function(value) {
rand = _.random(index++);
shuffled[index - 1] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (obj.length !== +obj.length) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// An internal function to generate lookup iterators.
var lookupIterator = function(value) {
if (value == null) return _.identity;
if (_.isFunction(value)) return value;
return _.property(value);
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, iterator, context) {
iterator = lookupIterator(iterator);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iterator, context) {
var result = {};
iterator = lookupIterator(iterator);
each(obj, function(value, index) {
var key = iterator.call(context, value, index, obj);
behavior(result, key, value);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, key, value) {
_.has(result, key) ? result[key].push(value) : result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, key, value) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, key) {
_.has(result, key) ? result[key]++ : result[key] = 1;
});
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator, context) {
iterator = lookupIterator(iterator);
var value = iterator.call(context, obj);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >>> 1;
iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
}
return low;
};
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if ((n == null) || guard) return array[0];
if (n < 0) return [];
return slice.call(array, 0, n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if ((n == null) || guard) return array[array.length - 1];
return slice.call(array, Math.max(array.length - n, 0));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, (n == null) || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, output) {
if (shallow && _.every(input, _.isArray)) {
return concat.apply(output, input);
}
each(input, function(value) {
if (_.isArray(value) || _.isArguments(value)) {
shallow ? push.apply(output, value) : flatten(value, shallow, output);
} else {
output.push(value);
}
});
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Split an array into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(array, predicate) {
var pass = [], fail = [];
each(array, function(elem) {
(predicate(elem) ? pass : fail).push(elem);
});
return [pass, fail];
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator, context) {
if (_.isFunction(isSorted)) {
context = iterator;
iterator = isSorted;
isSorted = false;
}
var initial = iterator ? _.map(array, iterator, context) : array;
var results = [];
var seen = [];
each(initial, function(value, index) {
if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
seen.push(value);
results.push(array[index]);
}
});
return results;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(_.flatten(arguments, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.contains(other, item);
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.contains(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var length = _.max(_.pluck(arguments, 'length').concat(0));
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(arguments, '' + i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, length = list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, length = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < length; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var hasIndex = from != null;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
}
var i = (hasIndex ? from : array.length);
while (i--) if (array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(length);
while(idx < length) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
var args, bound;
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
return function() {
var position = 0;
var args = boundArgs.slice();
for (var i = 0, length = args.length; i < length; i++) {
if (args[i] === _) args[i] = arguments[position++];
}
while (position < arguments.length) args.push(arguments[position++]);
return func.apply(this, args);
};
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length === 0) throw new Error('bindAll must be passed function names');
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(null, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = new Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = new Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
each(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
for (var key in obj) {
if (!_.contains(keys, key)) copy[key] = obj[key];
}
return copy;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
if (obj[prop] === void 0) obj[prop] = source[prop];
}
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] == a) return bStack[length] == b;
}
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
_.isFunction(bCtor) && (bCtor instanceof bCtor))
&& ('constructor' in a && 'constructor' in b)) {
return false;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Optimize `isFunction` if appropriate.
if (typeof (/./) !== 'function') {
_.isFunction = function(obj) {
return typeof obj === 'function';
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj != +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
_.constant = function(value) {
return function () {
return value;
};
};
_.property = function(key) {
return function(obj) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of `key:value` pairs.
_.matches = function(attrs) {
return function(obj) {
if (obj === attrs) return true; //avoid comparing an object to itself.
for (var key in attrs) {
if (attrs[key] !== obj[key])
return false;
}
return true;
}
};
// Run a function **n** times.
_.times = function(n, iterator, context) {
var accum = Array(Math.max(0, n));
for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() { return new Date().getTime(); };
// List of HTML entities for escaping.
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}
};
entityMap.unescape = _.invert(entityMap.escape);
// Regexes containing the keys and values listed immediately above.
var entityRegexes = {
escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
};
// Functions for escaping and unescaping strings to/from HTML interpolation.
_.each(['escape', 'unescape'], function(method) {
_[method] = function(string) {
if (string == null) return '';
return ('' + string).replace(entityRegexes[method], function(match) {
return entityMap[method][match];
});
};
});
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property) {
if (object == null) return void 0;
var value = object[property];
return _.isFunction(value) ? value.call(object) : value;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
var render;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
_.extend(_.prototype, {
// Start chaining a wrapped Underscore object.
chain: function() {
this._chain = true;
return this;
},
// Extracts the result from a wrapped and chained object.
value: function() {
return this._wrapped;
}
});
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}).call(this);
// Underscore.string
// (c) 2010 Esa-Matti Suuronen
// Underscore.string is freely distributable under the terms of the MIT license.
// Documentation: https://github.com/epeli/underscore.string
// Some code is borrowed from MooTools and Alexandru Marasteanu.
// Version '2.3.3'
!function(root, String){
'use strict';
// Defining helper functions.
var nativeTrim = String.prototype.trim;
var nativeTrimRight = String.prototype.trimRight;
var nativeTrimLeft = String.prototype.trimLeft;
var parseNumber = function(source) { return source * 1 || 0; };
var strRepeat = function(str, qty){
if (qty < 1) return '';
var result = '';
while (qty > 0) {
if (qty & 1) result += str;
qty >>= 1, str += str;
}
return result;
};
var slice = [].slice;
var defaultToWhiteSpace = function(characters) {
if (characters == null)
return '\\s';
else if (characters.source)
return characters.source;
else
return '[' + _s.escapeRegExp(characters) + ']';
};
// Helper for toBoolean
function boolMatch(s, matchers) {
var i, matcher, down = s.toLowerCase();
matchers = [].concat(matchers);
for (i = 0; i < matchers.length; i += 1) {
matcher = matchers[i];
if (!matcher) continue;
if (matcher.test && matcher.test(s)) return true;
if (matcher.toLowerCase() === down) return true;
}
}
var escapeChars = {
lt: '<',
gt: '>',
quot: '"',
amp: '&',
apos: "'"
};
var reversedEscapeChars = {};
for(var key in escapeChars) reversedEscapeChars[escapeChars[key]] = key;
reversedEscapeChars["'"] = '#39';
// sprintf() for JavaScript 0.7-beta1
// http://www.diveintojavascript.com/projects/javascript-sprintf
//
// Copyright (c) Alexandru Marasteanu
// All rights reserved.
var sprintf = (function() {
function get_type(variable) {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}
var str_repeat = strRepeat;
var str_format = function() {
if (!str_format.cache.hasOwnProperty(arguments[0])) {
str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
}
return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
};
str_format.format = function(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
for (i = 0; i < tree_length; i++) {
node_type = get_type(parse_tree[i]);
if (node_type === 'string') {
output.push(parse_tree[i]);
}
else if (node_type === 'array') {
match = parse_tree[i]; // convenience purposes only
if (match[2]) { // keyword argument
arg = argv[cursor];
for (k = 0; k < match[2].length; k++) {
if (!arg.hasOwnProperty(match[2][k])) {
throw new Error(sprintf('[_.sprintf] property "%s" does not exist', match[2][k]));
}
arg = arg[match[2][k]];
}
} else if (match[1]) { // positional argument (explicit)
arg = argv[match[1]];
}
else { // positional argument (implicit)
arg = argv[cursor++];
}
if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
throw new Error(sprintf('[_.sprintf] expecting number but found %s', get_type(arg)));
}
switch (match[8]) {
case 'b': arg = arg.toString(2); break;
case 'c': arg = String.fromCharCode(arg); break;
case 'd': arg = parseInt(arg, 10); break;
case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
case 'o': arg = arg.toString(8); break;
case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
case 'u': arg = Math.abs(arg); break;
case 'x': arg = arg.toString(16); break;
case 'X': arg = arg.toString(16).toUpperCase(); break;
}
arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
pad_length = match[6] - String(arg).length;
pad = match[6] ? str_repeat(pad_character, pad_length) : '';
output.push(match[5] ? arg + pad : pad + arg);
}
}
return output.join('');
};
str_format.cache = {};
str_format.parse = function(fmt) {
var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
while (_fmt) {
if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
}
else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
parse_tree.push('%');
}
else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
var field_list = [], replacement_field = match[2], field_match = [];
if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else {
throw new Error('[_.sprintf] huh?');
}
}
}
else {
throw new Error('[_.sprintf] huh?');
}
match[2] = field_list;
}
else {
arg_names |= 2;
}
if (arg_names === 3) {
throw new Error('[_.sprintf] mixing positional and named placeholders is not (yet) supported');
}
parse_tree.push(match);
}
else {
throw new Error('[_.sprintf] huh?');
}
_fmt = _fmt.substring(match[0].length);
}
return parse_tree;
};
return str_format;
})();
// Defining underscore.string
var _s = {
VERSION: '2.3.0',
isBlank: function(str){
if (str == null) str = '';
return (/^\s*$/).test(str);
},
stripTags: function(str){
if (str == null) return '';
return String(str).replace(/<\/?[^>]+>/g, '');
},
capitalize : function(str){
str = str == null ? '' : String(str);
return str.charAt(0).toUpperCase() + str.slice(1);
},
chop: function(str, step){
if (str == null) return [];
str = String(str);
step = ~~step;
return step > 0 ? str.match(new RegExp('.{1,' + step + '}', 'g')) : [str];
},
clean: function(str){
return _s.strip(str).replace(/\s+/g, ' ');
},
count: function(str, substr){
if (str == null || substr == null) return 0;
str = String(str);
substr = String(substr);
var count = 0,
pos = 0,
length = substr.length;
while (true) {
pos = str.indexOf(substr, pos);
if (pos === -1) break;
count++;
pos += length;
}
return count;
},
chars: function(str) {
if (str == null) return [];
return String(str).split('');
},
swapCase: function(str) {
if (str == null) return '';
return String(str).replace(/\S/g, function(c){
return c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase();
});
},
escapeHTML: function(str) {
if (str == null) return '';
return String(str).replace(/[&<>"']/g, function(m){ return '&' + reversedEscapeChars[m] + ';'; });
},
unescapeHTML: function(str) {
if (str == null) return '';
return String(str).replace(/\&([^;]+);/g, function(entity, entityCode){
var match;
if (entityCode in escapeChars) {
return escapeChars[entityCode];
} else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
return String.fromCharCode(parseInt(match[1], 16));
} else if (match = entityCode.match(/^#(\d+)$/)) {
return String.fromCharCode(~~match[1]);
} else {
return entity;
}
});
},
escapeRegExp: function(str){
if (str == null) return '';
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
},
splice: function(str, i, howmany, substr){
var arr = _s.chars(str);
arr.splice(~~i, ~~howmany, substr);
return arr.join('');
},
insert: function(str, i, substr){
return _s.splice(str, i, 0, substr);
},
include: function(str, needle){
if (needle === '') return true;
if (str == null) return false;
return String(str).indexOf(needle) !== -1;
},
join: function() {
var args = slice.call(arguments),
separator = args.shift();
if (separator == null) separator = '';
return args.join(separator);
},
lines: function(str) {
if (str == null) return [];
return String(str).split("\n");
},
reverse: function(str){
return _s.chars(str).reverse().join('');
},
startsWith: function(str, starts){
if (starts === '') return true;
if (str == null || starts == null) return false;
str = String(str); starts = String(starts);
return str.length >= starts.length && str.slice(0, starts.length) === starts;
},
endsWith: function(str, ends){
if (ends === '') return true;
if (str == null || ends == null) return false;
str = String(str); ends = String(ends);
return str.length >= ends.length && str.slice(str.length - ends.length) === ends;
},
succ: function(str){
if (str == null) return '';
str = String(str);
return str.slice(0, -1) + String.fromCharCode(str.charCodeAt(str.length-1) + 1);
},
titleize: function(str){
if (str == null) return '';
str = String(str).toLowerCase();
return str.replace(/(?:^|\s|-)\S/g, function(c){ return c.toUpperCase(); });
},
camelize: function(str){
return _s.trim(str).replace(/[-_\s]+(.)?/g, function(match, c){ return c ? c.toUpperCase() : ""; });
},
underscored: function(str){
return _s.trim(str).replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase();
},
dasherize: function(str){
return _s.trim(str).replace(/([A-Z])/g, '-$1').replace(/[-_\s]+/g, '-').toLowerCase();
},
classify: function(str){
return _s.titleize(String(str).replace(/[\W_]/g, ' ')).replace(/\s/g, '');
},
humanize: function(str){
return _s.capitalize(_s.underscored(str).replace(/_id$/,'').replace(/_/g, ' '));
},
trim: function(str, characters){
if (str == null) return '';
if (!characters && nativeTrim) return nativeTrim.call(str);
characters = defaultToWhiteSpace(characters);
return String(str).replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), '');
},
ltrim: function(str, characters){
if (str == null) return '';
if (!characters && nativeTrimLeft) return nativeTrimLeft.call(str);
characters = defaultToWhiteSpace(characters);
return String(str).replace(new RegExp('^' + characters + '+'), '');
},
rtrim: function(str, characters){
if (str == null) return '';
if (!characters && nativeTrimRight) return nativeTrimRight.call(str);
characters = defaultToWhiteSpace(characters);
return String(str).replace(new RegExp(characters + '+$'), '');
},
truncate: function(str, length, truncateStr){
if (str == null) return '';
str = String(str); truncateStr = truncateStr || '...';
length = ~~length;
return str.length > length ? str.slice(0, length) + truncateStr : str;
},
/**
* _s.prune: a more elegant version of truncate
* prune extra chars, never leaving a half-chopped word.
* @author github.com/rwz
*/
prune: function(str, length, pruneStr){
if (str == null) return '';
str = String(str); length = ~~length;
pruneStr = pruneStr != null ? String(pruneStr) : '...';
if (str.length <= length) return str;
var tmpl = function(c){ return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' '; },
template = str.slice(0, length+1).replace(/.(?=\W*\w*$)/g, tmpl); // 'Hello, world' -> 'HellAA AAAAA'
if (template.slice(template.length-2).match(/\w\w/))
template = template.replace(/\s*\S+$/, '');
else
template = _s.rtrim(template.slice(0, template.length-1));
return (template+pruneStr).length > str.length ? str : str.slice(0, template.length)+pruneStr;
},
words: function(str, delimiter) {
if (_s.isBlank(str)) return [];
return _s.trim(str, delimiter).split(delimiter || /\s+/);
},
pad: function(str, length, padStr, type) {
str = str == null ? '' : String(str);
length = ~~length;
var padlen = 0;
if (!padStr)
padStr = ' ';
else if (padStr.length > 1)
padStr = padStr.charAt(0);
switch(type) {
case 'right':
padlen = length - str.length;
return str + strRepeat(padStr, padlen);
case 'both':
padlen = length - str.length;
return strRepeat(padStr, Math.ceil(padlen/2)) + str
+ strRepeat(padStr, Math.floor(padlen/2));
default: // 'left'
padlen = length - str.length;
return strRepeat(padStr, padlen) + str;
}
},
lpad: function(str, length, padStr) {
return _s.pad(str, length, padStr);
},
rpad: function(str, length, padStr) {
return _s.pad(str, length, padStr, 'right');
},
lrpad: function(str, length, padStr) {
return _s.pad(str, length, padStr, 'both');
},
sprintf: sprintf,
vsprintf: function(fmt, argv){
argv.unshift(fmt);
return sprintf.apply(null, argv);
},
toNumber: function(str, decimals) {
if (!str) return 0;
str = _s.trim(str);
if (!str.match(/^-?\d+(?:\.\d+)?$/)) return NaN;
return parseNumber(parseNumber(str).toFixed(~~decimals));
},
numberFormat : function(number, dec, dsep, tsep) {
if (isNaN(number) || number == null) return '';
number = number.toFixed(~~dec);
tsep = typeof tsep == 'string' ? tsep : ',';
var parts = number.split('.'), fnums = parts[0],
decimals = parts[1] ? (dsep || '.') + parts[1] : '';
return fnums.replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + tsep) + decimals;
},
strRight: function(str, sep){
if (str == null) return '';
str = String(str); sep = sep != null ? String(sep) : sep;
var pos = !sep ? -1 : str.indexOf(sep);
return ~pos ? str.slice(pos+sep.length, str.length) : str;
},
strRightBack: function(str, sep){
if (str == null) return '';
str = String(str); sep = sep != null ? String(sep) : sep;
var pos = !sep ? -1 : str.lastIndexOf(sep);
return ~pos ? str.slice(pos+sep.length, str.length) : str;
},
strLeft: function(str, sep){
if (str == null) return '';
str = String(str); sep = sep != null ? String(sep) : sep;
var pos = !sep ? -1 : str.indexOf(sep);
return ~pos ? str.slice(0, pos) : str;
},
strLeftBack: function(str, sep){
if (str == null) return '';
str += ''; sep = sep != null ? ''+sep : sep;
var pos = str.lastIndexOf(sep);
return ~pos ? str.slice(0, pos) : str;
},
toSentence: function(array, separator, lastSeparator, serial) {
separator = separator || ', ';
lastSeparator = lastSeparator || ' and ';
var a = array.slice(), lastMember = a.pop();
if (array.length > 2 && serial) lastSeparator = _s.rtrim(separator) + lastSeparator;
return a.length ? a.join(separator) + lastSeparator + lastMember : lastMember;
},
toSentenceSerial: function() {
var args = slice.call(arguments);
args[3] = true;
return _s.toSentence.apply(_s, args);
},
slugify: function(str) {
if (str == null) return '';
var from = "ąà áäâãåæăćęèéëêìÃïîłńòóöôõøśșțùúüûñçżź",
to = "aaaaaaaaaceeeeeiiiilnoooooosstuuuunczz",
regex = new RegExp(defaultToWhiteSpace(from), 'g');
str = String(str).toLowerCase().replace(regex, function(c){
var index = from.indexOf(c);
return to.charAt(index) || '-';
});
return _s.dasherize(str.replace(/[^\w\s-]/g, ''));
},
surround: function(str, wrapper) {
return [wrapper, str, wrapper].join('');
},
quote: function(str, quoteChar) {
return _s.surround(str, quoteChar || '"');
},
unquote: function(str, quoteChar) {
quoteChar = quoteChar || '"';
if (str[0] === quoteChar && str[str.length-1] === quoteChar)
return str.slice(1,str.length-1);
else return str;
},
exports: function() {
var result = {};
for (var prop in this) {
if (!this.hasOwnProperty(prop) || prop.match(/^(?:include|contains|reverse)$/)) continue;
result[prop] = this[prop];
}
return result;
},
repeat: function(str, qty, separator){
if (str == null) return '';
qty = ~~qty;
// using faster implementation if separator is not needed;
if (separator == null) return strRepeat(String(str), qty);
// this one is about 300x slower in Google Chrome
for (var repeat = []; qty > 0; repeat[--qty] = str) {}
return repeat.join(separator);
},
naturalCmp: function(str1, str2){
if (str1 == str2) return 0;
if (!str1) return -1;
if (!str2) return 1;
var cmpRegex = /(\.\d+)|(\d+)|(\D+)/g,
tokens1 = String(str1).toLowerCase().match(cmpRegex),
tokens2 = String(str2).toLowerCase().match(cmpRegex),
count = Math.min(tokens1.length, tokens2.length);
for(var i = 0; i < count; i++) {
var a = tokens1[i], b = tokens2[i];
if (a !== b){
var num1 = parseInt(a, 10);
if (!isNaN(num1)){
var num2 = parseInt(b, 10);
if (!isNaN(num2) && num1 - num2)
return num1 - num2;
}
return a < b ? -1 : 1;
}
}
if (tokens1.length === tokens2.length)
return tokens1.length - tokens2.length;
return str1 < str2 ? -1 : 1;
},
levenshtein: function(str1, str2) {
if (str1 == null && str2 == null) return 0;
if (str1 == null) return String(str2).length;
if (str2 == null) return String(str1).length;
str1 = String(str1); str2 = String(str2);
var current = [], prev, value;
for (var i = 0; i <= str2.length; i++)
for (var j = 0; j <= str1.length; j++) {
if (i && j)
if (str1.charAt(j - 1) === str2.charAt(i - 1))
value = prev;
else
value = Math.min(current[j], current[j - 1], prev) + 1;
else
value = i + j;
prev = current[j];
current[j] = value;
}
return current.pop();
},
toBoolean: function(str, trueValues, falseValues) {
if (typeof str === "number") str = "" + str;
if (typeof str !== "string") return !!str;
str = _s.trim(str);
if (boolMatch(str, trueValues || ["true", "1"])) return true;
if (boolMatch(str, falseValues || ["false", "0"])) return false;
}
};
// Aliases
_s.strip = _s.trim;
_s.lstrip = _s.ltrim;
_s.rstrip = _s.rtrim;
_s.center = _s.lrpad;
_s.rjust = _s.lpad;
_s.ljust = _s.rpad;
_s.contains = _s.include;
_s.q = _s.quote;
_s.toBool = _s.toBoolean;
// Exporting
// CommonJS module is defined
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports)
module.exports = _s;
exports._s = _s;
}
// Register as a named module with AMD.
if (typeof define === 'function' && define.amd)
define('underscore.string', [], function(){ return _s; });
// Integrate with Underscore.js if defined
// or create our own underscore object.
root._ = root._ || {};
root._.string = root._.str = _s;
}(this, String);
/**
* @license wysihtml5 v0.3.0
* https://github.com/xing/wysihtml5
*
* Author: Christopher Blum (https://github.com/tiff)
*
* Copyright (C) 2012 XING AG
* Licensed under the MIT license (MIT)
*
*/
var wysihtml5 = {
version: "0.3.0",
// namespaces
commands: {},
dom: {},
quirks: {},
toolbar: {},
lang: {},
selection: {},
views: {},
INVISIBLE_SPACE: "\uFEFF",
EMPTY_FUNCTION: function() {},
ELEMENT_NODE: 1,
TEXT_NODE: 3,
BACKSPACE_KEY: 8,
ENTER_KEY: 13,
ESCAPE_KEY: 27,
SPACE_KEY: 32,
DELETE_KEY: 46
};/**
* @license Rangy, a cross-browser JavaScript range and selection library
* http://code.google.com/p/rangy/
*
* Copyright 2011, Tim Down
* Licensed under the MIT license.
* Version: 1.2.2
* Build date: 13 November 2011
*/
window['rangy'] = (function() {
var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined";
var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
"commonAncestorContainer", "START_TO_START", "START_TO_END", "END_TO_START", "END_TO_END"];
var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore",
"setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents",
"extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"];
var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"];
// Subset of TextRange's full set of methods that we're interested in
var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "getBookmark", "moveToBookmark",
"moveToElementText", "parentElement", "pasteHTML", "select", "setEndPoint", "getBoundingClientRect"];
/*----------------------------------------------------------------------------------------------------------------*/
// Trio of functions taken from Peter Michaux's article:
// http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
function isHostMethod(o, p) {
var t = typeof o[p];
return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown";
}
function isHostObject(o, p) {
return !!(typeof o[p] == OBJECT && o[p]);
}
function isHostProperty(o, p) {
return typeof o[p] != UNDEFINED;
}
// Creates a convenience function to save verbose repeated calls to tests functions
function createMultiplePropertyTest(testFunc) {
return function(o, props) {
var i = props.length;
while (i--) {
if (!testFunc(o, props[i])) {
return false;
}
}
return true;
};
}
// Next trio of functions are a convenience to save verbose repeated calls to previous two functions
var areHostMethods = createMultiplePropertyTest(isHostMethod);
var areHostObjects = createMultiplePropertyTest(isHostObject);
var areHostProperties = createMultiplePropertyTest(isHostProperty);
function isTextRange(range) {
return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties);
}
var api = {
version: "1.2.2",
initialized: false,
supported: true,
util: {
isHostMethod: isHostMethod,
isHostObject: isHostObject,
isHostProperty: isHostProperty,
areHostMethods: areHostMethods,
areHostObjects: areHostObjects,
areHostProperties: areHostProperties,
isTextRange: isTextRange
},
features: {},
modules: {},
config: {
alertOnWarn: false,
preferTextRange: false
}
};
function fail(reason) {
window.alert("Rangy not supported in your browser. Reason: " + reason);
api.initialized = true;
api.supported = false;
}
api.fail = fail;
function warn(msg) {
var warningMessage = "Rangy warning: " + msg;
if (api.config.alertOnWarn) {
window.alert(warningMessage);
} else if (typeof window.console != UNDEFINED && typeof window.console.log != UNDEFINED) {
window.console.log(warningMessage);
}
}
api.warn = warn;
if ({}.hasOwnProperty) {
api.util.extend = function(o, props) {
for (var i in props) {
if (props.hasOwnProperty(i)) {
o[i] = props[i];
}
}
};
} else {
fail("hasOwnProperty not supported");
}
var initListeners = [];
var moduleInitializers = [];
// Initialization
function init() {
if (api.initialized) {
return;
}
var testRange;
var implementsDomRange = false, implementsTextRange = false;
// First, perform basic feature tests
if (isHostMethod(document, "createRange")) {
testRange = document.createRange();
if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) {
implementsDomRange = true;
}
testRange.detach();
}
var body = isHostObject(document, "body") ? document.body : document.getElementsByTagName("body")[0];
if (body && isHostMethod(body, "createTextRange")) {
testRange = body.createTextRange();
if (isTextRange(testRange)) {
implementsTextRange = true;
}
}
if (!implementsDomRange && !implementsTextRange) {
fail("Neither Range nor TextRange are implemented");
}
api.initialized = true;
api.features = {
implementsDomRange: implementsDomRange,
implementsTextRange: implementsTextRange
};
// Initialize modules and call init listeners
var allListeners = moduleInitializers.concat(initListeners);
for (var i = 0, len = allListeners.length; i < len; ++i) {
try {
allListeners[i](api);
} catch (ex) {
if (isHostObject(window, "console") && isHostMethod(window.console, "log")) {
window.console.log("Init listener threw an exception. Continuing.", ex);
}
}
}
}
// Allow external scripts to initialize this library in case it's loaded after the document has loaded
api.init = init;
// Execute listener immediately if already initialized
api.addInitListener = function(listener) {
if (api.initialized) {
listener(api);
} else {
initListeners.push(listener);
}
};
var createMissingNativeApiListeners = [];
api.addCreateMissingNativeApiListener = function(listener) {
createMissingNativeApiListeners.push(listener);
};
function createMissingNativeApi(win) {
win = win || window;
init();
// Notify listeners
for (var i = 0, len = createMissingNativeApiListeners.length; i < len; ++i) {
createMissingNativeApiListeners[i](win);
}
}
api.createMissingNativeApi = createMissingNativeApi;
/**
* @constructor
*/
function Module(name) {
this.name = name;
this.initialized = false;
this.supported = false;
}
Module.prototype.fail = function(reason) {
this.initialized = true;
this.supported = false;
throw new Error("Module '" + this.name + "' failed to load: " + reason);
};
Module.prototype.warn = function(msg) {
api.warn("Module " + this.name + ": " + msg);
};
Module.prototype.createError = function(msg) {
return new Error("Error in Rangy " + this.name + " module: " + msg);
};
api.createModule = function(name, initFunc) {
var module = new Module(name);
api.modules[name] = module;
moduleInitializers.push(function(api) {
initFunc(api, module);
module.initialized = true;
module.supported = true;
});
};
api.requireModules = function(modules) {
for (var i = 0, len = modules.length, module, moduleName; i < len; ++i) {
moduleName = modules[i];
module = api.modules[moduleName];
if (!module || !(module instanceof Module)) {
throw new Error("Module '" + moduleName + "' not found");
}
if (!module.supported) {
throw new Error("Module '" + moduleName + "' not supported");
}
}
};
/*----------------------------------------------------------------------------------------------------------------*/
// Wait for document to load before running tests
var docReady = false;
var loadHandler = function(e) {
if (!docReady) {
docReady = true;
if (!api.initialized) {
init();
}
}
};
// Test whether we have window and document objects that we will need
if (typeof window == UNDEFINED) {
fail("No window found");
return;
}
if (typeof document == UNDEFINED) {
fail("No document found");
return;
}
if (isHostMethod(document, "addEventListener")) {
document.addEventListener("DOMContentLoaded", loadHandler, false);
}
// Add a fallback in case the DOMContentLoaded event isn't supported
if (isHostMethod(window, "addEventListener")) {
window.addEventListener("load", loadHandler, false);
} else if (isHostMethod(window, "attachEvent")) {
window.attachEvent("onload", loadHandler);
} else {
fail("Window does not have required addEventListener or attachEvent method");
}
return api;
})();
rangy.createModule("DomUtil", function(api, module) {
var UNDEF = "undefined";
var util = api.util;
// Perform feature tests
if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) {
module.fail("document missing a Node creation method");
}
if (!util.isHostMethod(document, "getElementsByTagName")) {
module.fail("document missing getElementsByTagName method");
}
var el = document.createElement("div");
if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] ||
!util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) {
module.fail("Incomplete Element implementation");
}
// innerHTML is required for Range's createContextualFragment method
if (!util.isHostProperty(el, "innerHTML")) {
module.fail("Element is missing innerHTML property");
}
var textNode = document.createTextNode("test");
if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] ||
!util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) ||
!util.areHostProperties(textNode, ["data"]))) {
module.fail("Incomplete Text Node implementation");
}
/*----------------------------------------------------------------------------------------------------------------*/
// Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been
// able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that
// contains just the document as a single element and the value searched for is the document.
var arrayContains = /*Array.prototype.indexOf ?
function(arr, val) {
return arr.indexOf(val) > -1;
}:*/
function(arr, val) {
var i = arr.length;
while (i--) {
if (arr[i] === val) {
return true;
}
}
return false;
};
// Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI
function isHtmlNamespace(node) {
var ns;
return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml");
}
function parentElement(node) {
var parent = node.parentNode;
return (parent.nodeType == 1) ? parent : null;
}
function getNodeIndex(node) {
var i = 0;
while( (node = node.previousSibling) ) {
i++;
}
return i;
}
function getNodeLength(node) {
var childNodes;
return isCharacterDataNode(node) ? node.length : ((childNodes = node.childNodes) ? childNodes.length : 0);
}
function getCommonAncestor(node1, node2) {
var ancestors = [], n;
for (n = node1; n; n = n.parentNode) {
ancestors.push(n);
}
for (n = node2; n; n = n.parentNode) {
if (arrayContains(ancestors, n)) {
return n;
}
}
return null;
}
function isAncestorOf(ancestor, descendant, selfIsAncestor) {
var n = selfIsAncestor ? descendant : descendant.parentNode;
while (n) {
if (n === ancestor) {
return true;
} else {
n = n.parentNode;
}
}
return false;
}
function getClosestAncestorIn(node, ancestor, selfIsAncestor) {
var p, n = selfIsAncestor ? node : node.parentNode;
while (n) {
p = n.parentNode;
if (p === ancestor) {
return n;
}
n = p;
}
return null;
}
function isCharacterDataNode(node) {
var t = node.nodeType;
return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment
}
function insertAfter(node, precedingNode) {
var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode;
if (nextNode) {
parent.insertBefore(node, nextNode);
} else {
parent.appendChild(node);
}
return node;
}
// Note that we cannot use splitText() because it is bugridden in IE 9.
function splitDataNode(node, index) {
var newNode = node.cloneNode(false);
newNode.deleteData(0, index);
node.deleteData(index, node.length - index);
insertAfter(newNode, node);
return newNode;
}
function getDocument(node) {
if (node.nodeType == 9) {
return node;
} else if (typeof node.ownerDocument != UNDEF) {
return node.ownerDocument;
} else if (typeof node.document != UNDEF) {
return node.document;
} else if (node.parentNode) {
return getDocument(node.parentNode);
} else {
throw new Error("getDocument: no document found for node");
}
}
function getWindow(node) {
var doc = getDocument(node);
if (typeof doc.defaultView != UNDEF) {
return doc.defaultView;
} else if (typeof doc.parentWindow != UNDEF) {
return doc.parentWindow;
} else {
throw new Error("Cannot get a window object for node");
}
}
function getIframeDocument(iframeEl) {
if (typeof iframeEl.contentDocument != UNDEF) {
return iframeEl.contentDocument;
} else if (typeof iframeEl.contentWindow != UNDEF) {
return iframeEl.contentWindow.document;
} else {
throw new Error("getIframeWindow: No Document object found for iframe element");
}
}
function getIframeWindow(iframeEl) {
if (typeof iframeEl.contentWindow != UNDEF) {
return iframeEl.contentWindow;
} else if (typeof iframeEl.contentDocument != UNDEF) {
return iframeEl.contentDocument.defaultView;
} else {
throw new Error("getIframeWindow: No Window object found for iframe element");
}
}
function getBody(doc) {
return util.isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0];
}
function getRootContainer(node) {
var parent;
while ( (parent = node.parentNode) ) {
node = parent;
}
return node;
}
function comparePoints(nodeA, offsetA, nodeB, offsetB) {
// See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing
var nodeC, root, childA, childB, n;
if (nodeA == nodeB) {
// Case 1: nodes are the same
return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1;
} else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) {
// Case 2: node C (container B or an ancestor) is a child node of A
return offsetA <= getNodeIndex(nodeC) ? -1 : 1;
} else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) {
// Case 3: node C (container A or an ancestor) is a child node of B
return getNodeIndex(nodeC) < offsetB ? -1 : 1;
} else {
// Case 4: containers are siblings or descendants of siblings
root = getCommonAncestor(nodeA, nodeB);
childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true);
childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true);
if (childA === childB) {
// This shouldn't be possible
throw new Error("comparePoints got to case 4 and childA and childB are the same!");
} else {
n = root.firstChild;
while (n) {
if (n === childA) {
return -1;
} else if (n === childB) {
return 1;
}
n = n.nextSibling;
}
throw new Error("Should not be here!");
}
}
}
function fragmentFromNodeChildren(node) {
var fragment = getDocument(node).createDocumentFragment(), child;
while ( (child = node.firstChild) ) {
fragment.appendChild(child);
}
return fragment;
}
function inspectNode(node) {
if (!node) {
return "[No node]";
}
if (isCharacterDataNode(node)) {
return '"' + node.data + '"';
} else if (node.nodeType == 1) {
var idAttr = node.id ? ' id="' + node.id + '"' : "";
return "<" + node.nodeName + idAttr + ">[" + node.childNodes.length + "]";
} else {
return node.nodeName;
}
}
/**
* @constructor
*/
function NodeIterator(root) {
this.root = root;
this._next = root;
}
NodeIterator.prototype = {
_current: null,
hasNext: function() {
return !!this._next;
},
next: function() {
var n = this._current = this._next;
var child, next;
if (this._current) {
child = n.firstChild;
if (child) {
this._next = child;
} else {
next = null;
while ((n !== this.root) && !(next = n.nextSibling)) {
n = n.parentNode;
}
this._next = next;
}
}
return this._current;
},
detach: function() {
this._current = this._next = this.root = null;
}
};
function createIterator(root) {
return new NodeIterator(root);
}
/**
* @constructor
*/
function DomPosition(node, offset) {
this.node = node;
this.offset = offset;
}
DomPosition.prototype = {
equals: function(pos) {
return this.node === pos.node & this.offset == pos.offset;
},
inspect: function() {
return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]";
}
};
/**
* @constructor
*/
function DOMException(codeName) {
this.code = this[codeName];
this.codeName = codeName;
this.message = "DOMException: " + this.codeName;
}
DOMException.prototype = {
INDEX_SIZE_ERR: 1,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INVALID_STATE_ERR: 11
};
DOMException.prototype.toString = function() {
return this.message;
};
api.dom = {
arrayContains: arrayContains,
isHtmlNamespace: isHtmlNamespace,
parentElement: parentElement,
getNodeIndex: getNodeIndex,
getNodeLength: getNodeLength,
getCommonAncestor: getCommonAncestor,
isAncestorOf: isAncestorOf,
getClosestAncestorIn: getClosestAncestorIn,
isCharacterDataNode: isCharacterDataNode,
insertAfter: insertAfter,
splitDataNode: splitDataNode,
getDocument: getDocument,
getWindow: getWindow,
getIframeWindow: getIframeWindow,
getIframeDocument: getIframeDocument,
getBody: getBody,
getRootContainer: getRootContainer,
comparePoints: comparePoints,
inspectNode: inspectNode,
fragmentFromNodeChildren: fragmentFromNodeChildren,
createIterator: createIterator,
DomPosition: DomPosition
};
api.DOMException = DOMException;
});rangy.createModule("DomRange", function(api, module) {
api.requireModules( ["DomUtil"] );
var dom = api.dom;
var DomPosition = dom.DomPosition;
var DOMException = api.DOMException;
/*----------------------------------------------------------------------------------------------------------------*/
// Utility functions
function isNonTextPartiallySelected(node, range) {
return (node.nodeType != 3) &&
(dom.isAncestorOf(node, range.startContainer, true) || dom.isAncestorOf(node, range.endContainer, true));
}
function getRangeDocument(range) {
return dom.getDocument(range.startContainer);
}
function dispatchEvent(range, type, args) {
var listeners = range._listeners[type];
if (listeners) {
for (var i = 0, len = listeners.length; i < len; ++i) {
listeners[i].call(range, {target: range, args: args});
}
}
}
function getBoundaryBeforeNode(node) {
return new DomPosition(node.parentNode, dom.getNodeIndex(node));
}
function getBoundaryAfterNode(node) {
return new DomPosition(node.parentNode, dom.getNodeIndex(node) + 1);
}
function insertNodeAtPosition(node, n, o) {
var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node;
if (dom.isCharacterDataNode(n)) {
if (o == n.length) {
dom.insertAfter(node, n);
} else {
n.parentNode.insertBefore(node, o == 0 ? n : dom.splitDataNode(n, o));
}
} else if (o >= n.childNodes.length) {
n.appendChild(node);
} else {
n.insertBefore(node, n.childNodes[o]);
}
return firstNodeInserted;
}
function cloneSubtree(iterator) {
var partiallySelected;
for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {
partiallySelected = iterator.isPartiallySelectedSubtree();
node = node.cloneNode(!partiallySelected);
if (partiallySelected) {
subIterator = iterator.getSubtreeIterator();
node.appendChild(cloneSubtree(subIterator));
subIterator.detach(true);
}
if (node.nodeType == 10) { // DocumentType
throw new DOMException("HIERARCHY_REQUEST_ERR");
}
frag.appendChild(node);
}
return frag;
}
function iterateSubtree(rangeIterator, func, iteratorState) {
var it, n;
iteratorState = iteratorState || { stop: false };
for (var node, subRangeIterator; node = rangeIterator.next(); ) {
//log.debug("iterateSubtree, partially selected: " + rangeIterator.isPartiallySelectedSubtree(), nodeToString(node));
if (rangeIterator.isPartiallySelectedSubtree()) {
// The node is partially selected by the Range, so we can use a new RangeIterator on the portion of the
// node selected by the Range.
if (func(node) === false) {
iteratorState.stop = true;
return;
} else {
subRangeIterator = rangeIterator.getSubtreeIterator();
iterateSubtree(subRangeIterator, func, iteratorState);
subRangeIterator.detach(true);
if (iteratorState.stop) {
return;
}
}
} else {
// The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its
// descendant
it = dom.createIterator(node);
while ( (n = it.next()) ) {
if (func(n) === false) {
iteratorState.stop = true;
return;
}
}
}
}
}
function deleteSubtree(iterator) {
var subIterator;
while (iterator.next()) {
if (iterator.isPartiallySelectedSubtree()) {
subIterator = iterator.getSubtreeIterator();
deleteSubtree(subIterator);
subIterator.detach(true);
} else {
iterator.remove();
}
}
}
function extractSubtree(iterator) {
for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {
if (iterator.isPartiallySelectedSubtree()) {
node = node.cloneNode(false);
subIterator = iterator.getSubtreeIterator();
node.appendChild(extractSubtree(subIterator));
subIterator.detach(true);
} else {
iterator.remove();
}
if (node.nodeType == 10) { // DocumentType
throw new DOMException("HIERARCHY_REQUEST_ERR");
}
frag.appendChild(node);
}
return frag;
}
function getNodesInRange(range, nodeTypes, filter) {
//log.info("getNodesInRange, " + nodeTypes.join(","));
var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex;
var filterExists = !!filter;
if (filterNodeTypes) {
regex = new RegExp("^(" + nodeTypes.join("|") + ")$");
}
var nodes = [];
iterateSubtree(new RangeIterator(range, false), function(node) {
if ((!filterNodeTypes || regex.test(node.nodeType)) && (!filterExists || filter(node))) {
nodes.push(node);
}
});
return nodes;
}
function inspect(range) {
var name = (typeof range.getName == "undefined") ? "Range" : range.getName();
return "[" + name + "(" + dom.inspectNode(range.startContainer) + ":" + range.startOffset + ", " +
dom.inspectNode(range.endContainer) + ":" + range.endOffset + ")]";
}
/*----------------------------------------------------------------------------------------------------------------*/
// RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange)
/**
* @constructor
*/
function RangeIterator(range, clonePartiallySelectedTextNodes) {
this.range = range;
this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes;
if (!range.collapsed) {
this.sc = range.startContainer;
this.so = range.startOffset;
this.ec = range.endContainer;
this.eo = range.endOffset;
var root = range.commonAncestorContainer;
if (this.sc === this.ec && dom.isCharacterDataNode(this.sc)) {
this.isSingleCharacterDataNode = true;
this._first = this._last = this._next = this.sc;
} else {
this._first = this._next = (this.sc === root && !dom.isCharacterDataNode(this.sc)) ?
this.sc.childNodes[this.so] : dom.getClosestAncestorIn(this.sc, root, true);
this._last = (this.ec === root && !dom.isCharacterDataNode(this.ec)) ?
this.ec.childNodes[this.eo - 1] : dom.getClosestAncestorIn(this.ec, root, true);
}
}
}
RangeIterator.prototype = {
_current: null,
_next: null,
_first: null,
_last: null,
isSingleCharacterDataNode: false,
reset: function() {
this._current = null;
this._next = this._first;
},
hasNext: function() {
return !!this._next;
},
next: function() {
// Move to next node
var current = this._current = this._next;
if (current) {
this._next = (current !== this._last) ? current.nextSibling : null;
// Check for partially selected text nodes
if (dom.isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) {
if (current === this.ec) {
(current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo);
}
if (this._current === this.sc) {
(current = current.cloneNode(true)).deleteData(0, this.so);
}
}
}
return current;
},
remove: function() {
var current = this._current, start, end;
if (dom.isCharacterDataNode(current) && (current === this.sc || current === this.ec)) {
start = (current === this.sc) ? this.so : 0;
end = (current === this.ec) ? this.eo : current.length;
if (start != end) {
current.deleteData(start, end - start);
}
} else {
if (current.parentNode) {
current.parentNode.removeChild(current);
} else {
}
}
},
// Checks if the current node is partially selected
isPartiallySelectedSubtree: function() {
var current = this._current;
return isNonTextPartiallySelected(current, this.range);
},
getSubtreeIterator: function() {
var subRange;
if (this.isSingleCharacterDataNode) {
subRange = this.range.cloneRange();
subRange.collapse();
} else {
subRange = new Range(getRangeDocument(this.range));
var current = this._current;
var startContainer = current, startOffset = 0, endContainer = current, endOffset = dom.getNodeLength(current);
if (dom.isAncestorOf(current, this.sc, true)) {
startContainer = this.sc;
startOffset = this.so;
}
if (dom.isAncestorOf(current, this.ec, true)) {
endContainer = this.ec;
endOffset = this.eo;
}
updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset);
}
return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes);
},
detach: function(detachRange) {
if (detachRange) {
this.range.detach();
}
this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null;
}
};
/*----------------------------------------------------------------------------------------------------------------*/
// Exceptions
/**
* @constructor
*/
function RangeException(codeName) {
this.code = this[codeName];
this.codeName = codeName;
this.message = "RangeException: " + this.codeName;
}
RangeException.prototype = {
BAD_BOUNDARYPOINTS_ERR: 1,
INVALID_NODE_TYPE_ERR: 2
};
RangeException.prototype.toString = function() {
return this.message;
};
/*----------------------------------------------------------------------------------------------------------------*/
/**
* Currently iterates through all nodes in the range on creation until I think of a decent way to do it
* TODO: Look into making this a proper iterator, not requiring preloading everything first
* @constructor
*/
function RangeNodeIterator(range, nodeTypes, filter) {
this.nodes = getNodesInRange(range, nodeTypes, filter);
this._next = this.nodes[0];
this._position = 0;
}
RangeNodeIterator.prototype = {
_current: null,
hasNext: function() {
return !!this._next;
},
next: function() {
this._current = this._next;
this._next = this.nodes[ ++this._position ];
return this._current;
},
detach: function() {
this._current = this._next = this.nodes = null;
}
};
var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10];
var rootContainerNodeTypes = [2, 9, 11];
var readonlyNodeTypes = [5, 6, 10, 12];
var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11];
var surroundNodeTypes = [1, 3, 4, 5, 7, 8];
function createAncestorFinder(nodeTypes) {
return function(node, selfIsAncestor) {
var t, n = selfIsAncestor ? node : node.parentNode;
while (n) {
t = n.nodeType;
if (dom.arrayContains(nodeTypes, t)) {
return n;
}
n = n.parentNode;
}
return null;
};
}
var getRootContainer = dom.getRootContainer;
var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] );
var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes);
var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] );
function assertNoDocTypeNotationEntityAncestor(node, allowSelf) {
if (getDocTypeNotationEntityAncestor(node, allowSelf)) {
throw new RangeException("INVALID_NODE_TYPE_ERR");
}
}
function assertNotDetached(range) {
if (!range.startContainer) {
throw new DOMException("INVALID_STATE_ERR");
}
}
function assertValidNodeType(node, invalidTypes) {
if (!dom.arrayContains(invalidTypes, node.nodeType)) {
throw new RangeException("INVALID_NODE_TYPE_ERR");
}
}
function assertValidOffset(node, offset) {
if (offset < 0 || offset > (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length)) {
throw new DOMException("INDEX_SIZE_ERR");
}
}
function assertSameDocumentOrFragment(node1, node2) {
if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) {
throw new DOMException("WRONG_DOCUMENT_ERR");
}
}
function assertNodeNotReadOnly(node) {
if (getReadonlyAncestor(node, true)) {
throw new DOMException("NO_MODIFICATION_ALLOWED_ERR");
}
}
function assertNode(node, codeName) {
if (!node) {
throw new DOMException(codeName);
}
}
function isOrphan(node) {
return !dom.arrayContains(rootContainerNodeTypes, node.nodeType) && !getDocumentOrFragmentContainer(node, true);
}
function isValidOffset(node, offset) {
return offset <= (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length);
}
function assertRangeValid(range) {
assertNotDetached(range);
if (isOrphan(range.startContainer) || isOrphan(range.endContainer) ||
!isValidOffset(range.startContainer, range.startOffset) ||
!isValidOffset(range.endContainer, range.endOffset)) {
throw new Error("Range error: Range is no longer valid after DOM mutation (" + range.inspect() + ")");
}
}
/*----------------------------------------------------------------------------------------------------------------*/
// Test the browser's innerHTML support to decide how to implement createContextualFragment
var styleEl = document.createElement("style");
var htmlParsingConforms = false;
try {
styleEl.innerHTML = "x ";
htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node
} catch (e) {
// IE 6 and 7 throw
}
api.features.htmlParsingConforms = htmlParsingConforms;
var createContextualFragment = htmlParsingConforms ?
// Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See
// discussion and base code for this implementation at issue 67.
// Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface
// Thanks to Aleks Williams.
function(fragmentStr) {
// "Let node the context object's start's node."
var node = this.startContainer;
var doc = dom.getDocument(node);
// "If the context object's start's node is null, raise an INVALID_STATE_ERR
// exception and abort these steps."
if (!node) {
throw new DOMException("INVALID_STATE_ERR");
}
// "Let element be as follows, depending on node's interface:"
// Document, Document Fragment: null
var el = null;
// "Element: node"
if (node.nodeType == 1) {
el = node;
// "Text, Comment: node's parentElement"
} else if (dom.isCharacterDataNode(node)) {
el = dom.parentElement(node);
}
// "If either element is null or element's ownerDocument is an HTML document
// and element's local name is "html" and element's namespace is the HTML
// namespace"
if (el === null || (
el.nodeName == "HTML"
&& dom.isHtmlNamespace(dom.getDocument(el).documentElement)
&& dom.isHtmlNamespace(el)
)) {
// "let element be a new Element with "body" as its local name and the HTML
// namespace as its namespace.""
el = doc.createElement("body");
} else {
el = el.cloneNode(false);
}
// "If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm."
// "If the node's document is an XML document: Invoke the XML fragment parsing algorithm."
// "In either case, the algorithm must be invoked with fragment as the input
// and element as the context element."
el.innerHTML = fragmentStr;
// "If this raises an exception, then abort these steps. Otherwise, let new
// children be the nodes returned."
// "Let fragment be a new DocumentFragment."
// "Append all new children to fragment."
// "Return fragment."
return dom.fragmentFromNodeChildren(el);
} :
// In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that
// previous versions of Rangy used (with the exception of using a body element rather than a div)
function(fragmentStr) {
assertNotDetached(this);
var doc = getRangeDocument(this);
var el = doc.createElement("body");
el.innerHTML = fragmentStr;
return dom.fragmentFromNodeChildren(el);
};
/*----------------------------------------------------------------------------------------------------------------*/
var rangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
"commonAncestorContainer"];
var s2s = 0, s2e = 1, e2e = 2, e2s = 3;
var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3;
function RangePrototype() {}
RangePrototype.prototype = {
attachListener: function(type, listener) {
this._listeners[type].push(listener);
},
compareBoundaryPoints: function(how, range) {
assertRangeValid(this);
assertSameDocumentOrFragment(this.startContainer, range.startContainer);
var nodeA, offsetA, nodeB, offsetB;
var prefixA = (how == e2s || how == s2s) ? "start" : "end";
var prefixB = (how == s2e || how == s2s) ? "start" : "end";
nodeA = this[prefixA + "Container"];
offsetA = this[prefixA + "Offset"];
nodeB = range[prefixB + "Container"];
offsetB = range[prefixB + "Offset"];
return dom.comparePoints(nodeA, offsetA, nodeB, offsetB);
},
insertNode: function(node) {
assertRangeValid(this);
assertValidNodeType(node, insertableNodeTypes);
assertNodeNotReadOnly(this.startContainer);
if (dom.isAncestorOf(node, this.startContainer, true)) {
throw new DOMException("HIERARCHY_REQUEST_ERR");
}
// No check for whether the container of the start of the Range is of a type that does not allow
// children of the type of node: the browser's DOM implementation should do this for us when we attempt
// to add the node
var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset);
this.setStartBefore(firstNodeInserted);
},
cloneContents: function() {
assertRangeValid(this);
var clone, frag;
if (this.collapsed) {
return getRangeDocument(this).createDocumentFragment();
} else {
if (this.startContainer === this.endContainer && dom.isCharacterDataNode(this.startContainer)) {
clone = this.startContainer.cloneNode(true);
clone.data = clone.data.slice(this.startOffset, this.endOffset);
frag = getRangeDocument(this).createDocumentFragment();
frag.appendChild(clone);
return frag;
} else {
var iterator = new RangeIterator(this, true);
clone = cloneSubtree(iterator);
iterator.detach();
}
return clone;
}
},
canSurroundContents: function() {
assertRangeValid(this);
assertNodeNotReadOnly(this.startContainer);
assertNodeNotReadOnly(this.endContainer);
// Check if the contents can be surrounded. Specifically, this means whether the range partially selects
// no non-text nodes.
var iterator = new RangeIterator(this, true);
var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||
(iterator._last && isNonTextPartiallySelected(iterator._last, this)));
iterator.detach();
return !boundariesInvalid;
},
surroundContents: function(node) {
assertValidNodeType(node, surroundNodeTypes);
if (!this.canSurroundContents()) {
throw new RangeException("BAD_BOUNDARYPOINTS_ERR");
}
// Extract the contents
var content = this.extractContents();
// Clear the children of the node
if (node.hasChildNodes()) {
while (node.lastChild) {
node.removeChild(node.lastChild);
}
}
// Insert the new node and add the extracted contents
insertNodeAtPosition(node, this.startContainer, this.startOffset);
node.appendChild(content);
this.selectNode(node);
},
cloneRange: function() {
assertRangeValid(this);
var range = new Range(getRangeDocument(this));
var i = rangeProperties.length, prop;
while (i--) {
prop = rangeProperties[i];
range[prop] = this[prop];
}
return range;
},
toString: function() {
assertRangeValid(this);
var sc = this.startContainer;
if (sc === this.endContainer && dom.isCharacterDataNode(sc)) {
return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : "";
} else {
var textBits = [], iterator = new RangeIterator(this, true);
iterateSubtree(iterator, function(node) {
// Accept only text or CDATA nodes, not comments
if (node.nodeType == 3 || node.nodeType == 4) {
textBits.push(node.data);
}
});
iterator.detach();
return textBits.join("");
}
},
// The methods below are all non-standard. The following batch were introduced by Mozilla but have since
// been removed from Mozilla.
compareNode: function(node) {
assertRangeValid(this);
var parent = node.parentNode;
var nodeIndex = dom.getNodeIndex(node);
if (!parent) {
throw new DOMException("NOT_FOUND_ERR");
}
var startComparison = this.comparePoint(parent, nodeIndex),
endComparison = this.comparePoint(parent, nodeIndex + 1);
if (startComparison < 0) { // Node starts before
return (endComparison > 0) ? n_b_a : n_b;
} else {
return (endComparison > 0) ? n_a : n_i;
}
},
comparePoint: function(node, offset) {
assertRangeValid(this);
assertNode(node, "HIERARCHY_REQUEST_ERR");
assertSameDocumentOrFragment(node, this.startContainer);
if (dom.comparePoints(node, offset, this.startContainer, this.startOffset) < 0) {
return -1;
} else if (dom.comparePoints(node, offset, this.endContainer, this.endOffset) > 0) {
return 1;
}
return 0;
},
createContextualFragment: createContextualFragment,
toHtml: function() {
assertRangeValid(this);
var container = getRangeDocument(this).createElement("div");
container.appendChild(this.cloneContents());
return container.innerHTML;
},
// touchingIsIntersecting determines whether this method considers a node that borders a range intersects
// with it (as in WebKit) or not (as in Gecko pre-1.9, and the default)
intersectsNode: function(node, touchingIsIntersecting) {
assertRangeValid(this);
assertNode(node, "NOT_FOUND_ERR");
if (dom.getDocument(node) !== getRangeDocument(this)) {
return false;
}
var parent = node.parentNode, offset = dom.getNodeIndex(node);
assertNode(parent, "NOT_FOUND_ERR");
var startComparison = dom.comparePoints(parent, offset, this.endContainer, this.endOffset),
endComparison = dom.comparePoints(parent, offset + 1, this.startContainer, this.startOffset);
return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
},
isPointInRange: function(node, offset) {
assertRangeValid(this);
assertNode(node, "HIERARCHY_REQUEST_ERR");
assertSameDocumentOrFragment(node, this.startContainer);
return (dom.comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) &&
(dom.comparePoints(node, offset, this.endContainer, this.endOffset) <= 0);
},
// The methods below are non-standard and invented by me.
// Sharing a boundary start-to-end or end-to-start does not count as intersection.
intersectsRange: function(range, touchingIsIntersecting) {
assertRangeValid(this);
if (getRangeDocument(range) != getRangeDocument(this)) {
throw new DOMException("WRONG_DOCUMENT_ERR");
}
var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.endContainer, range.endOffset),
endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.startContainer, range.startOffset);
return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
},
intersection: function(range) {
if (this.intersectsRange(range)) {
var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset),
endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset);
var intersectionRange = this.cloneRange();
if (startComparison == -1) {
intersectionRange.setStart(range.startContainer, range.startOffset);
}
if (endComparison == 1) {
intersectionRange.setEnd(range.endContainer, range.endOffset);
}
return intersectionRange;
}
return null;
},
union: function(range) {
if (this.intersectsRange(range, true)) {
var unionRange = this.cloneRange();
if (dom.comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) {
unionRange.setStart(range.startContainer, range.startOffset);
}
if (dom.comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) {
unionRange.setEnd(range.endContainer, range.endOffset);
}
return unionRange;
} else {
throw new RangeException("Ranges do not intersect");
}
},
containsNode: function(node, allowPartial) {
if (allowPartial) {
return this.intersectsNode(node, false);
} else {
return this.compareNode(node) == n_i;
}
},
containsNodeContents: function(node) {
return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, dom.getNodeLength(node)) <= 0;
},
containsRange: function(range) {
return this.intersection(range).equals(range);
},
containsNodeText: function(node) {
var nodeRange = this.cloneRange();
nodeRange.selectNode(node);
var textNodes = nodeRange.getNodes([3]);
if (textNodes.length > 0) {
nodeRange.setStart(textNodes[0], 0);
var lastTextNode = textNodes.pop();
nodeRange.setEnd(lastTextNode, lastTextNode.length);
var contains = this.containsRange(nodeRange);
nodeRange.detach();
return contains;
} else {
return this.containsNodeContents(node);
}
},
createNodeIterator: function(nodeTypes, filter) {
assertRangeValid(this);
return new RangeNodeIterator(this, nodeTypes, filter);
},
getNodes: function(nodeTypes, filter) {
assertRangeValid(this);
return getNodesInRange(this, nodeTypes, filter);
},
getDocument: function() {
return getRangeDocument(this);
},
collapseBefore: function(node) {
assertNotDetached(this);
this.setEndBefore(node);
this.collapse(false);
},
collapseAfter: function(node) {
assertNotDetached(this);
this.setStartAfter(node);
this.collapse(true);
},
getName: function() {
return "DomRange";
},
equals: function(range) {
return Range.rangesEqual(this, range);
},
inspect: function() {
return inspect(this);
}
};
function copyComparisonConstantsToObject(obj) {
obj.START_TO_START = s2s;
obj.START_TO_END = s2e;
obj.END_TO_END = e2e;
obj.END_TO_START = e2s;
obj.NODE_BEFORE = n_b;
obj.NODE_AFTER = n_a;
obj.NODE_BEFORE_AND_AFTER = n_b_a;
obj.NODE_INSIDE = n_i;
}
function copyComparisonConstants(constructor) {
copyComparisonConstantsToObject(constructor);
copyComparisonConstantsToObject(constructor.prototype);
}
function createRangeContentRemover(remover, boundaryUpdater) {
return function() {
assertRangeValid(this);
var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer;
var iterator = new RangeIterator(this, true);
// Work out where to position the range after content removal
var node, boundary;
if (sc !== root) {
node = dom.getClosestAncestorIn(sc, root, true);
boundary = getBoundaryAfterNode(node);
sc = boundary.node;
so = boundary.offset;
}
// Check none of the range is read-only
iterateSubtree(iterator, assertNodeNotReadOnly);
iterator.reset();
// Remove the content
var returnValue = remover(iterator);
iterator.detach();
// Move to the new position
boundaryUpdater(this, sc, so, sc, so);
return returnValue;
};
}
function createPrototypeRange(constructor, boundaryUpdater, detacher) {
function createBeforeAfterNodeSetter(isBefore, isStart) {
return function(node) {
assertNotDetached(this);
assertValidNodeType(node, beforeAfterNodeTypes);
assertValidNodeType(getRootContainer(node), rootContainerNodeTypes);
var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node);
(isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset);
};
}
function setRangeStart(range, node, offset) {
var ec = range.endContainer, eo = range.endOffset;
if (node !== range.startContainer || offset !== range.startOffset) {
// Check the root containers of the range and the new boundary, and also check whether the new boundary
// is after the current end. In either case, collapse the range to the new position
if (getRootContainer(node) != getRootContainer(ec) || dom.comparePoints(node, offset, ec, eo) == 1) {
ec = node;
eo = offset;
}
boundaryUpdater(range, node, offset, ec, eo);
}
}
function setRangeEnd(range, node, offset) {
var sc = range.startContainer, so = range.startOffset;
if (node !== range.endContainer || offset !== range.endOffset) {
// Check the root containers of the range and the new boundary, and also check whether the new boundary
// is after the current end. In either case, collapse the range to the new position
if (getRootContainer(node) != getRootContainer(sc) || dom.comparePoints(node, offset, sc, so) == -1) {
sc = node;
so = offset;
}
boundaryUpdater(range, sc, so, node, offset);
}
}
function setRangeStartAndEnd(range, node, offset) {
if (node !== range.startContainer || offset !== range.startOffset || node !== range.endContainer || offset !== range.endOffset) {
boundaryUpdater(range, node, offset, node, offset);
}
}
constructor.prototype = new RangePrototype();
api.util.extend(constructor.prototype, {
setStart: function(node, offset) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
assertValidOffset(node, offset);
setRangeStart(this, node, offset);
},
setEnd: function(node, offset) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
assertValidOffset(node, offset);
setRangeEnd(this, node, offset);
},
setStartBefore: createBeforeAfterNodeSetter(true, true),
setStartAfter: createBeforeAfterNodeSetter(false, true),
setEndBefore: createBeforeAfterNodeSetter(true, false),
setEndAfter: createBeforeAfterNodeSetter(false, false),
collapse: function(isStart) {
assertRangeValid(this);
if (isStart) {
boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset);
} else {
boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset);
}
},
selectNodeContents: function(node) {
// This doesn't seem well specified: the spec talks only about selecting the node's contents, which
// could be taken to mean only its children. However, browsers implement this the same as selectNode for
// text nodes, so I shall do likewise
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
boundaryUpdater(this, node, 0, node, dom.getNodeLength(node));
},
selectNode: function(node) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, false);
assertValidNodeType(node, beforeAfterNodeTypes);
var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node);
boundaryUpdater(this, start.node, start.offset, end.node, end.offset);
},
extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater),
deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater),
canSurroundContents: function() {
assertRangeValid(this);
assertNodeNotReadOnly(this.startContainer);
assertNodeNotReadOnly(this.endContainer);
// Check if the contents can be surrounded. Specifically, this means whether the range partially selects
// no non-text nodes.
var iterator = new RangeIterator(this, true);
var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||
(iterator._last && isNonTextPartiallySelected(iterator._last, this)));
iterator.detach();
return !boundariesInvalid;
},
detach: function() {
detacher(this);
},
splitBoundaries: function() {
assertRangeValid(this);
var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;
var startEndSame = (sc === ec);
if (dom.isCharacterDataNode(ec) && eo > 0 && eo < ec.length) {
dom.splitDataNode(ec, eo);
}
if (dom.isCharacterDataNode(sc) && so > 0 && so < sc.length) {
sc = dom.splitDataNode(sc, so);
if (startEndSame) {
eo -= so;
ec = sc;
} else if (ec == sc.parentNode && eo >= dom.getNodeIndex(sc)) {
eo++;
}
so = 0;
}
boundaryUpdater(this, sc, so, ec, eo);
},
normalizeBoundaries: function() {
assertRangeValid(this);
var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;
var mergeForward = function(node) {
var sibling = node.nextSibling;
if (sibling && sibling.nodeType == node.nodeType) {
ec = node;
eo = node.length;
node.appendData(sibling.data);
sibling.parentNode.removeChild(sibling);
}
};
var mergeBackward = function(node) {
var sibling = node.previousSibling;
if (sibling && sibling.nodeType == node.nodeType) {
sc = node;
var nodeLength = node.length;
so = sibling.length;
node.insertData(0, sibling.data);
sibling.parentNode.removeChild(sibling);
if (sc == ec) {
eo += so;
ec = sc;
} else if (ec == node.parentNode) {
var nodeIndex = dom.getNodeIndex(node);
if (eo == nodeIndex) {
ec = node;
eo = nodeLength;
} else if (eo > nodeIndex) {
eo--;
}
}
}
};
var normalizeStart = true;
if (dom.isCharacterDataNode(ec)) {
if (ec.length == eo) {
mergeForward(ec);
}
} else {
if (eo > 0) {
var endNode = ec.childNodes[eo - 1];
if (endNode && dom.isCharacterDataNode(endNode)) {
mergeForward(endNode);
}
}
normalizeStart = !this.collapsed;
}
if (normalizeStart) {
if (dom.isCharacterDataNode(sc)) {
if (so == 0) {
mergeBackward(sc);
}
} else {
if (so < sc.childNodes.length) {
var startNode = sc.childNodes[so];
if (startNode && dom.isCharacterDataNode(startNode)) {
mergeBackward(startNode);
}
}
}
} else {
sc = ec;
so = eo;
}
boundaryUpdater(this, sc, so, ec, eo);
},
collapseToPoint: function(node, offset) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
assertValidOffset(node, offset);
setRangeStartAndEnd(this, node, offset);
}
});
copyComparisonConstants(constructor);
}
/*----------------------------------------------------------------------------------------------------------------*/
// Updates commonAncestorContainer and collapsed after boundary change
function updateCollapsedAndCommonAncestor(range) {
range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
range.commonAncestorContainer = range.collapsed ?
range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer);
}
function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) {
var startMoved = (range.startContainer !== startContainer || range.startOffset !== startOffset);
var endMoved = (range.endContainer !== endContainer || range.endOffset !== endOffset);
range.startContainer = startContainer;
range.startOffset = startOffset;
range.endContainer = endContainer;
range.endOffset = endOffset;
updateCollapsedAndCommonAncestor(range);
dispatchEvent(range, "boundarychange", {startMoved: startMoved, endMoved: endMoved});
}
function detach(range) {
assertNotDetached(range);
range.startContainer = range.startOffset = range.endContainer = range.endOffset = null;
range.collapsed = range.commonAncestorContainer = null;
dispatchEvent(range, "detach", null);
range._listeners = null;
}
/**
* @constructor
*/
function Range(doc) {
this.startContainer = doc;
this.startOffset = 0;
this.endContainer = doc;
this.endOffset = 0;
this._listeners = {
boundarychange: [],
detach: []
};
updateCollapsedAndCommonAncestor(this);
}
createPrototypeRange(Range, updateBoundaries, detach);
api.rangePrototype = RangePrototype.prototype;
Range.rangeProperties = rangeProperties;
Range.RangeIterator = RangeIterator;
Range.copyComparisonConstants = copyComparisonConstants;
Range.createPrototypeRange = createPrototypeRange;
Range.inspect = inspect;
Range.getRangeDocument = getRangeDocument;
Range.rangesEqual = function(r1, r2) {
return r1.startContainer === r2.startContainer &&
r1.startOffset === r2.startOffset &&
r1.endContainer === r2.endContainer &&
r1.endOffset === r2.endOffset;
};
api.DomRange = Range;
api.RangeException = RangeException;
});rangy.createModule("WrappedRange", function(api, module) {
api.requireModules( ["DomUtil", "DomRange"] );
/**
* @constructor
*/
var WrappedRange;
var dom = api.dom;
var DomPosition = dom.DomPosition;
var DomRange = api.DomRange;
/*----------------------------------------------------------------------------------------------------------------*/
/*
This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement()
method. For example, in the following (where pipes denote the selection boundaries):
var range = document.selection.createRange();
alert(range.parentElement().id); // Should alert "ul" but alerts "b"
This method returns the common ancestor node of the following:
- the parentElement() of the textRange
- the parentElement() of the textRange after calling collapse(true)
- the parentElement() of the textRange after calling collapse(false)
*/
function getTextRangeContainerElement(textRange) {
var parentEl = textRange.parentElement();
var range = textRange.duplicate();
range.collapse(true);
var startEl = range.parentElement();
range = textRange.duplicate();
range.collapse(false);
var endEl = range.parentElement();
var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl);
return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer);
}
function textRangeIsCollapsed(textRange) {
return textRange.compareEndPoints("StartToEnd", textRange) == 0;
}
// Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started out as
// an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/) but has
// grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange bugs, handling
// for inputs and images, plus optimizations.
function getTextRangeBoundaryPosition(textRange, wholeRangeContainerElement, isStart, isCollapsed) {
var workingRange = textRange.duplicate();
workingRange.collapse(isStart);
var containerElement = workingRange.parentElement();
// Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so
// check for that
// TODO: Find out when. Workaround for wholeRangeContainerElement may break this
if (!dom.isAncestorOf(wholeRangeContainerElement, containerElement, true)) {
containerElement = wholeRangeContainerElement;
}
// Deal with nodes that cannot "contain rich HTML markup". In practice, this means form inputs, images and
// similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx
if (!containerElement.canHaveHTML) {
return new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement));
}
var workingNode = dom.getDocument(containerElement).createElement("span");
var comparison, workingComparisonType = isStart ? "StartToStart" : "StartToEnd";
var previousNode, nextNode, boundaryPosition, boundaryNode;
// Move the working range through the container's children, starting at the end and working backwards, until the
// working range reaches or goes past the boundary we're interested in
do {
containerElement.insertBefore(workingNode, workingNode.previousSibling);
workingRange.moveToElementText(workingNode);
} while ( (comparison = workingRange.compareEndPoints(workingComparisonType, textRange)) > 0 &&
workingNode.previousSibling);
// We've now reached or gone past the boundary of the text range we're interested in
// so have identified the node we want
boundaryNode = workingNode.nextSibling;
if (comparison == -1 && boundaryNode && dom.isCharacterDataNode(boundaryNode)) {
// This is a character data node (text, comment, cdata). The working range is collapsed at the start of the
// node containing the text range's boundary, so we move the end of the working range to the boundary point
// and measure the length of its text to get the boundary's offset within the node.
workingRange.setEndPoint(isStart ? "EndToStart" : "EndToEnd", textRange);
var offset;
if (/[\r\n]/.test(boundaryNode.data)) {
/*
For the particular case of a boundary within a text node containing line breaks (within a element,
for example), we need a slightly complicated approach to get the boundary's offset in IE. The facts:
- Each line break is represented as \r in the text node's data/nodeValue properties
- Each line break is represented as \r\n in the TextRange's 'text' property
- The 'text' property of the TextRange does not contain trailing line breaks
To get round the problem presented by the final fact above, we can use the fact that TextRange's
moveStart() and moveEnd() methods return the actual number of characters moved, which is not necessarily
the same as the number of characters it was instructed to move. The simplest approach is to use this to
store the characters moved when moving both the start and end of the range to the start of the document
body and subtracting the start offset from the end offset (the "move-negative-gazillion" method).
However, this is extremely slow when the document is large and the range is near the end of it. Clearly
doing the mirror image (i.e. moving the range boundaries to the end of the document) has the same
problem.
Another approach that works is to use moveStart() to move the start boundary of the range up to the end
boundary one character at a time and incrementing a counter with the value returned by the moveStart()
call. However, the check for whether the start boundary has reached the end boundary is expensive, so
this method is slow (although unlike "move-negative-gazillion" is largely unaffected by the location of
the range within the document).
The method below is a hybrid of the two methods above. It uses the fact that a string containing the
TextRange's 'text' property with each \r\n converted to a single \r character cannot be longer than the
text of the TextRange, so the start of the range is moved that length initially and then a character at
a time to make up for any trailing line breaks not contained in the 'text' property. This has good
performance in most situations compared to the previous two methods.
*/
var tempRange = workingRange.duplicate();
var rangeLength = tempRange.text.replace(/\r\n/g, "\r").length;
offset = tempRange.moveStart("character", rangeLength);
while ( (comparison = tempRange.compareEndPoints("StartToEnd", tempRange)) == -1) {
offset++;
tempRange.moveStart("character", 1);
}
} else {
offset = workingRange.text.length;
}
boundaryPosition = new DomPosition(boundaryNode, offset);
} else {
// If the boundary immediately follows a character data node and this is the end boundary, we should favour
// a position within that, and likewise for a start boundary preceding a character data node
previousNode = (isCollapsed || !isStart) && workingNode.previousSibling;
nextNode = (isCollapsed || isStart) && workingNode.nextSibling;
if (nextNode && dom.isCharacterDataNode(nextNode)) {
boundaryPosition = new DomPosition(nextNode, 0);
} else if (previousNode && dom.isCharacterDataNode(previousNode)) {
boundaryPosition = new DomPosition(previousNode, previousNode.length);
} else {
boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode));
}
}
// Clean up
workingNode.parentNode.removeChild(workingNode);
return boundaryPosition;
}
// Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that node.
// This function started out as an optimized version of code found in Tim Cameron Ryan's IERange
// (http://code.google.com/p/ierange/)
function createBoundaryTextRange(boundaryPosition, isStart) {
var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset;
var doc = dom.getDocument(boundaryPosition.node);
var workingNode, childNodes, workingRange = doc.body.createTextRange();
var nodeIsDataNode = dom.isCharacterDataNode(boundaryPosition.node);
if (nodeIsDataNode) {
boundaryNode = boundaryPosition.node;
boundaryParent = boundaryNode.parentNode;
} else {
childNodes = boundaryPosition.node.childNodes;
boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null;
boundaryParent = boundaryPosition.node;
}
// Position the range immediately before the node containing the boundary
workingNode = doc.createElement("span");
// Making the working element non-empty element persuades IE to consider the TextRange boundary to be within the
// element rather than immediately before or after it, which is what we want
workingNode.innerHTML = "feff;";
// insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report
// for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12
if (boundaryNode) {
boundaryParent.insertBefore(workingNode, boundaryNode);
} else {
boundaryParent.appendChild(workingNode);
}
workingRange.moveToElementText(workingNode);
workingRange.collapse(!isStart);
// Clean up
boundaryParent.removeChild(workingNode);
// Move the working range to the text offset, if required
if (nodeIsDataNode) {
workingRange[isStart ? "moveStart" : "moveEnd"]("character", boundaryOffset);
}
return workingRange;
}
/*----------------------------------------------------------------------------------------------------------------*/
if (api.features.implementsDomRange && (!api.features.implementsTextRange || !api.config.preferTextRange)) {
// This is a wrapper around the browser's native DOM Range. It has two aims:
// - Provide workarounds for specific browser bugs
// - provide convenient extensions, which are inherited from Rangy's DomRange
(function() {
var rangeProto;
var rangeProperties = DomRange.rangeProperties;
var canSetRangeStartAfterEnd;
function updateRangeProperties(range) {
var i = rangeProperties.length, prop;
while (i--) {
prop = rangeProperties[i];
range[prop] = range.nativeRange[prop];
}
}
function updateNativeRange(range, startContainer, startOffset, endContainer,endOffset) {
var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset);
var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset);
// Always set both boundaries for the benefit of IE9 (see issue 35)
if (startMoved || endMoved) {
range.setEnd(endContainer, endOffset);
range.setStart(startContainer, startOffset);
}
}
function detach(range) {
range.nativeRange.detach();
range.detached = true;
var i = rangeProperties.length, prop;
while (i--) {
prop = rangeProperties[i];
range[prop] = null;
}
}
var createBeforeAfterNodeSetter;
WrappedRange = function(range) {
if (!range) {
throw new Error("Range must be specified");
}
this.nativeRange = range;
updateRangeProperties(this);
};
DomRange.createPrototypeRange(WrappedRange, updateNativeRange, detach);
rangeProto = WrappedRange.prototype;
rangeProto.selectNode = function(node) {
this.nativeRange.selectNode(node);
updateRangeProperties(this);
};
rangeProto.deleteContents = function() {
this.nativeRange.deleteContents();
updateRangeProperties(this);
};
rangeProto.extractContents = function() {
var frag = this.nativeRange.extractContents();
updateRangeProperties(this);
return frag;
};
rangeProto.cloneContents = function() {
return this.nativeRange.cloneContents();
};
// TODO: Until I can find a way to programmatically trigger the Firefox bug (apparently long-standing, still
// present in 3.6.8) that throws "Index or size is negative or greater than the allowed amount" for
// insertNode in some circumstances, all browsers will have to use the Rangy's own implementation of
// insertNode, which works but is almost certainly slower than the native implementation.
/*
rangeProto.insertNode = function(node) {
this.nativeRange.insertNode(node);
updateRangeProperties(this);
};
*/
rangeProto.surroundContents = function(node) {
this.nativeRange.surroundContents(node);
updateRangeProperties(this);
};
rangeProto.collapse = function(isStart) {
this.nativeRange.collapse(isStart);
updateRangeProperties(this);
};
rangeProto.cloneRange = function() {
return new WrappedRange(this.nativeRange.cloneRange());
};
rangeProto.refresh = function() {
updateRangeProperties(this);
};
rangeProto.toString = function() {
return this.nativeRange.toString();
};
// Create test range and node for feature detection
var testTextNode = document.createTextNode("test");
dom.getBody(document).appendChild(testTextNode);
var range = document.createRange();
/*--------------------------------------------------------------------------------------------------------*/
// Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and
// correct for it
range.setStart(testTextNode, 0);
range.setEnd(testTextNode, 0);
try {
range.setStart(testTextNode, 1);
canSetRangeStartAfterEnd = true;
rangeProto.setStart = function(node, offset) {
this.nativeRange.setStart(node, offset);
updateRangeProperties(this);
};
rangeProto.setEnd = function(node, offset) {
this.nativeRange.setEnd(node, offset);
updateRangeProperties(this);
};
createBeforeAfterNodeSetter = function(name) {
return function(node) {
this.nativeRange[name](node);
updateRangeProperties(this);
};
};
} catch(ex) {
canSetRangeStartAfterEnd = false;
rangeProto.setStart = function(node, offset) {
try {
this.nativeRange.setStart(node, offset);
} catch (ex) {
this.nativeRange.setEnd(node, offset);
this.nativeRange.setStart(node, offset);
}
updateRangeProperties(this);
};
rangeProto.setEnd = function(node, offset) {
try {
this.nativeRange.setEnd(node, offset);
} catch (ex) {
this.nativeRange.setStart(node, offset);
this.nativeRange.setEnd(node, offset);
}
updateRangeProperties(this);
};
createBeforeAfterNodeSetter = function(name, oppositeName) {
return function(node) {
try {
this.nativeRange[name](node);
} catch (ex) {
this.nativeRange[oppositeName](node);
this.nativeRange[name](node);
}
updateRangeProperties(this);
};
};
}
rangeProto.setStartBefore = createBeforeAfterNodeSetter("setStartBefore", "setEndBefore");
rangeProto.setStartAfter = createBeforeAfterNodeSetter("setStartAfter", "setEndAfter");
rangeProto.setEndBefore = createBeforeAfterNodeSetter("setEndBefore", "setStartBefore");
rangeProto.setEndAfter = createBeforeAfterNodeSetter("setEndAfter", "setStartAfter");
/*--------------------------------------------------------------------------------------------------------*/
// Test for and correct Firefox 2 behaviour with selectNodeContents on text nodes: it collapses the range to
// the 0th character of the text node
range.selectNodeContents(testTextNode);
if (range.startContainer == testTextNode && range.endContainer == testTextNode &&
range.startOffset == 0 && range.endOffset == testTextNode.length) {
rangeProto.selectNodeContents = function(node) {
this.nativeRange.selectNodeContents(node);
updateRangeProperties(this);
};
} else {
rangeProto.selectNodeContents = function(node) {
this.setStart(node, 0);
this.setEnd(node, DomRange.getEndOffset(node));
};
}
/*--------------------------------------------------------------------------------------------------------*/
// Test for WebKit bug that has the beahviour of compareBoundaryPoints round the wrong way for constants
// START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738
range.selectNodeContents(testTextNode);
range.setEnd(testTextNode, 3);
var range2 = document.createRange();
range2.selectNodeContents(testTextNode);
range2.setEnd(testTextNode, 4);
range2.setStart(testTextNode, 2);
if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 &
range.compareBoundaryPoints(range.END_TO_START, range2) == 1) {
// This is the wrong way round, so correct for it
rangeProto.compareBoundaryPoints = function(type, range) {
range = range.nativeRange || range;
if (type == range.START_TO_END) {
type = range.END_TO_START;
} else if (type == range.END_TO_START) {
type = range.START_TO_END;
}
return this.nativeRange.compareBoundaryPoints(type, range);
};
} else {
rangeProto.compareBoundaryPoints = function(type, range) {
return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range);
};
}
/*--------------------------------------------------------------------------------------------------------*/
// Test for existence of createContextualFragment and delegate to it if it exists
if (api.util.isHostMethod(range, "createContextualFragment")) {
rangeProto.createContextualFragment = function(fragmentStr) {
return this.nativeRange.createContextualFragment(fragmentStr);
};
}
/*--------------------------------------------------------------------------------------------------------*/
// Clean up
dom.getBody(document).removeChild(testTextNode);
range.detach();
range2.detach();
})();
api.createNativeRange = function(doc) {
doc = doc || document;
return doc.createRange();
};
} else if (api.features.implementsTextRange) {
// This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a
// prototype
WrappedRange = function(textRange) {
this.textRange = textRange;
this.refresh();
};
WrappedRange.prototype = new DomRange(document);
WrappedRange.prototype.refresh = function() {
var start, end;
// TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that.
var rangeContainerElement = getTextRangeContainerElement(this.textRange);
if (textRangeIsCollapsed(this.textRange)) {
end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, true);
} else {
start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false);
end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false);
}
this.setStart(start.node, start.offset);
this.setEnd(end.node, end.offset);
};
DomRange.copyComparisonConstants(WrappedRange);
// Add WrappedRange as the Range property of the global object to allow expression like Range.END_TO_END to work
var globalObj = (function() { return this; })();
if (typeof globalObj.Range == "undefined") {
globalObj.Range = WrappedRange;
}
api.createNativeRange = function(doc) {
doc = doc || document;
return doc.body.createTextRange();
};
}
if (api.features.implementsTextRange) {
WrappedRange.rangeToTextRange = function(range) {
if (range.collapsed) {
var tr = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
return tr;
//return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
} else {
var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false);
var textRange = dom.getDocument(range.startContainer).body.createTextRange();
textRange.setEndPoint("StartToStart", startRange);
textRange.setEndPoint("EndToEnd", endRange);
return textRange;
}
};
}
WrappedRange.prototype.getName = function() {
return "WrappedRange";
};
api.WrappedRange = WrappedRange;
api.createRange = function(doc) {
doc = doc || document;
return new WrappedRange(api.createNativeRange(doc));
};
api.createRangyRange = function(doc) {
doc = doc || document;
return new DomRange(doc);
};
api.createIframeRange = function(iframeEl) {
return api.createRange(dom.getIframeDocument(iframeEl));
};
api.createIframeRangyRange = function(iframeEl) {
return api.createRangyRange(dom.getIframeDocument(iframeEl));
};
api.addCreateMissingNativeApiListener(function(win) {
var doc = win.document;
if (typeof doc.createRange == "undefined") {
doc.createRange = function() {
return api.createRange(this);
};
}
doc = win = null;
});
});rangy.createModule("WrappedSelection", function(api, module) {
// This will create a selection object wrapper that follows the Selection object found in the WHATWG draft DOM Range
// spec (http://html5.org/specs/dom-range.html)
api.requireModules( ["DomUtil", "DomRange", "WrappedRange"] );
api.config.checkSelectionRanges = true;
var BOOLEAN = "boolean",
windowPropertyName = "_rangySelection",
dom = api.dom,
util = api.util,
DomRange = api.DomRange,
WrappedRange = api.WrappedRange,
DOMException = api.DOMException,
DomPosition = dom.DomPosition,
getSelection,
selectionIsCollapsed,
CONTROL = "Control";
function getWinSelection(winParam) {
return (winParam || window).getSelection();
}
function getDocSelection(winParam) {
return (winParam || window).document.selection;
}
// Test for the Range/TextRange and Selection features required
// Test for ability to retrieve selection
var implementsWinGetSelection = api.util.isHostMethod(window, "getSelection"),
implementsDocSelection = api.util.isHostObject(document, "selection");
var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange);
if (useDocumentSelection) {
getSelection = getDocSelection;
api.isSelectionValid = function(winParam) {
var doc = (winParam || window).document, nativeSel = doc.selection;
// Check whether the selection TextRange is actually contained within the correct document
return (nativeSel.type != "None" || dom.getDocument(nativeSel.createRange().parentElement()) == doc);
};
} else if (implementsWinGetSelection) {
getSelection = getWinSelection;
api.isSelectionValid = function() {
return true;
};
} else {
module.fail("Neither document.selection or window.getSelection() detected.");
}
api.getNativeSelection = getSelection;
var testSelection = getSelection();
var testRange = api.createNativeRange(document);
var body = dom.getBody(document);
// Obtaining a range from a selection
var selectionHasAnchorAndFocus = util.areHostObjects(testSelection, ["anchorNode", "focusNode"] &&
util.areHostProperties(testSelection, ["anchorOffset", "focusOffset"]));
api.features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus;
// Test for existence of native selection extend() method
var selectionHasExtend = util.isHostMethod(testSelection, "extend");
api.features.selectionHasExtend = selectionHasExtend;
// Test if rangeCount exists
var selectionHasRangeCount = (typeof testSelection.rangeCount == "number");
api.features.selectionHasRangeCount = selectionHasRangeCount;
var selectionSupportsMultipleRanges = false;
var collapsedNonEditableSelectionsSupported = true;
if (util.areHostMethods(testSelection, ["addRange", "getRangeAt", "removeAllRanges"]) &&
typeof testSelection.rangeCount == "number" && api.features.implementsDomRange) {
(function() {
var iframe = document.createElement("iframe");
body.appendChild(iframe);
var iframeDoc = dom.getIframeDocument(iframe);
iframeDoc.open();
iframeDoc.write("12");
iframeDoc.close();
var sel = dom.getIframeWindow(iframe).getSelection();
var docEl = iframeDoc.documentElement;
var iframeBody = docEl.lastChild, textNode = iframeBody.firstChild;
// Test whether the native selection will allow a collapsed selection within a non-editable element
var r1 = iframeDoc.createRange();
r1.setStart(textNode, 1);
r1.collapse(true);
sel.addRange(r1);
collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1);
sel.removeAllRanges();
// Test whether the native selection is capable of supporting multiple ranges
var r2 = r1.cloneRange();
r1.setStart(textNode, 0);
r2.setEnd(textNode, 2);
sel.addRange(r1);
sel.addRange(r2);
selectionSupportsMultipleRanges = (sel.rangeCount == 2);
// Clean up
r1.detach();
r2.detach();
body.removeChild(iframe);
})();
}
api.features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges;
api.features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported;
// ControlRanges
var implementsControlRange = false, testControlRange;
if (body && util.isHostMethod(body, "createControlRange")) {
testControlRange = body.createControlRange();
if (util.areHostProperties(testControlRange, ["item", "add"])) {
implementsControlRange = true;
}
}
api.features.implementsControlRange = implementsControlRange;
// Selection collapsedness
if (selectionHasAnchorAndFocus) {
selectionIsCollapsed = function(sel) {
return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset;
};
} else {
selectionIsCollapsed = function(sel) {
return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false;
};
}
function updateAnchorAndFocusFromRange(sel, range, backwards) {
var anchorPrefix = backwards ? "end" : "start", focusPrefix = backwards ? "start" : "end";
sel.anchorNode = range[anchorPrefix + "Container"];
sel.anchorOffset = range[anchorPrefix + "Offset"];
sel.focusNode = range[focusPrefix + "Container"];
sel.focusOffset = range[focusPrefix + "Offset"];
}
function updateAnchorAndFocusFromNativeSelection(sel) {
var nativeSel = sel.nativeSelection;
sel.anchorNode = nativeSel.anchorNode;
sel.anchorOffset = nativeSel.anchorOffset;
sel.focusNode = nativeSel.focusNode;
sel.focusOffset = nativeSel.focusOffset;
}
function updateEmptySelection(sel) {
sel.anchorNode = sel.focusNode = null;
sel.anchorOffset = sel.focusOffset = 0;
sel.rangeCount = 0;
sel.isCollapsed = true;
sel._ranges.length = 0;
}
function getNativeRange(range) {
var nativeRange;
if (range instanceof DomRange) {
nativeRange = range._selectionNativeRange;
if (!nativeRange) {
nativeRange = api.createNativeRange(dom.getDocument(range.startContainer));
nativeRange.setEnd(range.endContainer, range.endOffset);
nativeRange.setStart(range.startContainer, range.startOffset);
range._selectionNativeRange = nativeRange;
range.attachListener("detach", function() {
this._selectionNativeRange = null;
});
}
} else if (range instanceof WrappedRange) {
nativeRange = range.nativeRange;
} else if (api.features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) {
nativeRange = range;
}
return nativeRange;
}
function rangeContainsSingleElement(rangeNodes) {
if (!rangeNodes.length || rangeNodes[0].nodeType != 1) {
return false;
}
for (var i = 1, len = rangeNodes.length; i < len; ++i) {
if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) {
return false;
}
}
return true;
}
function getSingleElementFromRange(range) {
var nodes = range.getNodes();
if (!rangeContainsSingleElement(nodes)) {
throw new Error("getSingleElementFromRange: range " + range.inspect() + " did not consist of a single element");
}
return nodes[0];
}
function isTextRange(range) {
return !!range && typeof range.text != "undefined";
}
function updateFromTextRange(sel, range) {
// Create a Range from the selected TextRange
var wrappedRange = new WrappedRange(range);
sel._ranges = [wrappedRange];
updateAnchorAndFocusFromRange(sel, wrappedRange, false);
sel.rangeCount = 1;
sel.isCollapsed = wrappedRange.collapsed;
}
function updateControlSelection(sel) {
// Update the wrapped selection based on what's now in the native selection
sel._ranges.length = 0;
if (sel.docSelection.type == "None") {
updateEmptySelection(sel);
} else {
var controlRange = sel.docSelection.createRange();
if (isTextRange(controlRange)) {
// This case (where the selection type is "Control" and calling createRange() on the selection returns
// a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected
// ControlRange have been removed from the ControlRange and removed from the document.
updateFromTextRange(sel, controlRange);
} else {
sel.rangeCount = controlRange.length;
var range, doc = dom.getDocument(controlRange.item(0));
for (var i = 0; i < sel.rangeCount; ++i) {
range = api.createRange(doc);
range.selectNode(controlRange.item(i));
sel._ranges.push(range);
}
sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed;
updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false);
}
}
}
function addRangeToControlSelection(sel, range) {
var controlRange = sel.docSelection.createRange();
var rangeElement = getSingleElementFromRange(range);
// Create a new ControlRange containing all the elements in the selected ControlRange plus the element
// contained by the supplied range
var doc = dom.getDocument(controlRange.item(0));
var newControlRange = dom.getBody(doc).createControlRange();
for (var i = 0, len = controlRange.length; i < len; ++i) {
newControlRange.add(controlRange.item(i));
}
try {
newControlRange.add(rangeElement);
} catch (ex) {
throw new Error("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)");
}
newControlRange.select();
// Update the wrapped selection based on what's now in the native selection
updateControlSelection(sel);
}
var getSelectionRangeAt;
if (util.isHostMethod(testSelection, "getRangeAt")) {
getSelectionRangeAt = function(sel, index) {
try {
return sel.getRangeAt(index);
} catch(ex) {
return null;
}
};
} else if (selectionHasAnchorAndFocus) {
getSelectionRangeAt = function(sel) {
var doc = dom.getDocument(sel.anchorNode);
var range = api.createRange(doc);
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
// Handle the case when the selection was selected backwards (from the end to the start in the
// document)
if (range.collapsed !== this.isCollapsed) {
range.setStart(sel.focusNode, sel.focusOffset);
range.setEnd(sel.anchorNode, sel.anchorOffset);
}
return range;
};
}
/**
* @constructor
*/
function WrappedSelection(selection, docSelection, win) {
this.nativeSelection = selection;
this.docSelection = docSelection;
this._ranges = [];
this.win = win;
this.refresh();
}
api.getSelection = function(win) {
win = win || window;
var sel = win[windowPropertyName];
var nativeSel = getSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null;
if (sel) {
sel.nativeSelection = nativeSel;
sel.docSelection = docSel;
sel.refresh(win);
} else {
sel = new WrappedSelection(nativeSel, docSel, win);
win[windowPropertyName] = sel;
}
return sel;
};
api.getIframeSelection = function(iframeEl) {
return api.getSelection(dom.getIframeWindow(iframeEl));
};
var selProto = WrappedSelection.prototype;
function createControlSelection(sel, ranges) {
// Ensure that the selection becomes of type "Control"
var doc = dom.getDocument(ranges[0].startContainer);
var controlRange = dom.getBody(doc).createControlRange();
for (var i = 0, el; i < rangeCount; ++i) {
el = getSingleElementFromRange(ranges[i]);
try {
controlRange.add(el);
} catch (ex) {
throw new Error("setRanges(): Element within the one of the specified Ranges could not be added to control selection (does it have layout?)");
}
}
controlRange.select();
// Update the wrapped selection based on what's now in the native selection
updateControlSelection(sel);
}
// Selecting a range
if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, ["removeAllRanges", "addRange"])) {
selProto.removeAllRanges = function() {
this.nativeSelection.removeAllRanges();
updateEmptySelection(this);
};
var addRangeBackwards = function(sel, range) {
var doc = DomRange.getRangeDocument(range);
var endRange = api.createRange(doc);
endRange.collapseToPoint(range.endContainer, range.endOffset);
sel.nativeSelection.addRange(getNativeRange(endRange));
sel.nativeSelection.extend(range.startContainer, range.startOffset);
sel.refresh();
};
if (selectionHasRangeCount) {
selProto.addRange = function(range, backwards) {
if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
addRangeToControlSelection(this, range);
} else {
if (backwards && selectionHasExtend) {
addRangeBackwards(this, range);
} else {
var previousRangeCount;
if (selectionSupportsMultipleRanges) {
previousRangeCount = this.rangeCount;
} else {
this.removeAllRanges();
previousRangeCount = 0;
}
this.nativeSelection.addRange(getNativeRange(range));
// Check whether adding the range was successful
this.rangeCount = this.nativeSelection.rangeCount;
if (this.rangeCount == previousRangeCount + 1) {
// The range was added successfully
// Check whether the range that we added to the selection is reflected in the last range extracted from
// the selection
if (api.config.checkSelectionRanges) {
var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1);
if (nativeRange && !DomRange.rangesEqual(nativeRange, range)) {
// Happens in WebKit with, for example, a selection placed at the start of a text node
range = new WrappedRange(nativeRange);
}
}
this._ranges[this.rangeCount - 1] = range;
updateAnchorAndFocusFromRange(this, range, selectionIsBackwards(this.nativeSelection));
this.isCollapsed = selectionIsCollapsed(this);
} else {
// The range was not added successfully. The simplest thing is to refresh
this.refresh();
}
}
}
};
} else {
selProto.addRange = function(range, backwards) {
if (backwards && selectionHasExtend) {
addRangeBackwards(this, range);
} else {
this.nativeSelection.addRange(getNativeRange(range));
this.refresh();
}
};
}
selProto.setRanges = function(ranges) {
if (implementsControlRange && ranges.length > 1) {
createControlSelection(this, ranges);
} else {
this.removeAllRanges();
for (var i = 0, len = ranges.length; i < len; ++i) {
this.addRange(ranges[i]);
}
}
};
} else if (util.isHostMethod(testSelection, "empty") && util.isHostMethod(testRange, "select") &&
implementsControlRange && useDocumentSelection) {
selProto.removeAllRanges = function() {
// Added try/catch as fix for issue #21
try {
this.docSelection.empty();
// Check for empty() not working (issue #24)
if (this.docSelection.type != "None") {
// Work around failure to empty a control selection by instead selecting a TextRange and then
// calling empty()
var doc;
if (this.anchorNode) {
doc = dom.getDocument(this.anchorNode);
} else if (this.docSelection.type == CONTROL) {
var controlRange = this.docSelection.createRange();
if (controlRange.length) {
doc = dom.getDocument(controlRange.item(0)).body.createTextRange();
}
}
if (doc) {
var textRange = doc.body.createTextRange();
textRange.select();
this.docSelection.empty();
}
}
} catch(ex) {}
updateEmptySelection(this);
};
selProto.addRange = function(range) {
if (this.docSelection.type == CONTROL) {
addRangeToControlSelection(this, range);
} else {
WrappedRange.rangeToTextRange(range).select();
this._ranges[0] = range;
this.rangeCount = 1;
this.isCollapsed = this._ranges[0].collapsed;
updateAnchorAndFocusFromRange(this, range, false);
}
};
selProto.setRanges = function(ranges) {
this.removeAllRanges();
var rangeCount = ranges.length;
if (rangeCount > 1) {
createControlSelection(this, ranges);
} else if (rangeCount) {
this.addRange(ranges[0]);
}
};
} else {
module.fail("No means of selecting a Range or TextRange was found");
return false;
}
selProto.getRangeAt = function(index) {
if (index < 0 || index >= this.rangeCount) {
throw new DOMException("INDEX_SIZE_ERR");
} else {
return this._ranges[index];
}
};
var refreshSelection;
if (useDocumentSelection) {
refreshSelection = function(sel) {
var range;
if (api.isSelectionValid(sel.win)) {
range = sel.docSelection.createRange();
} else {
range = dom.getBody(sel.win.document).createTextRange();
range.collapse(true);
}
if (sel.docSelection.type == CONTROL) {
updateControlSelection(sel);
} else if (isTextRange(range)) {
updateFromTextRange(sel, range);
} else {
updateEmptySelection(sel);
}
};
} else if (util.isHostMethod(testSelection, "getRangeAt") && typeof testSelection.rangeCount == "number") {
refreshSelection = function(sel) {
if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) {
updateControlSelection(sel);
} else {
sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount;
if (sel.rangeCount) {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i));
}
updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackwards(sel.nativeSelection));
sel.isCollapsed = selectionIsCollapsed(sel);
} else {
updateEmptySelection(sel);
}
}
};
} else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && api.features.implementsDomRange) {
refreshSelection = function(sel) {
var range, nativeSel = sel.nativeSelection;
if (nativeSel.anchorNode) {
range = getSelectionRangeAt(nativeSel, 0);
sel._ranges = [range];
sel.rangeCount = 1;
updateAnchorAndFocusFromNativeSelection(sel);
sel.isCollapsed = selectionIsCollapsed(sel);
} else {
updateEmptySelection(sel);
}
};
} else {
module.fail("No means of obtaining a Range or TextRange from the user's selection was found");
return false;
}
selProto.refresh = function(checkForChanges) {
var oldRanges = checkForChanges ? this._ranges.slice(0) : null;
refreshSelection(this);
if (checkForChanges) {
var i = oldRanges.length;
if (i != this._ranges.length) {
return false;
}
while (i--) {
if (!DomRange.rangesEqual(oldRanges[i], this._ranges[i])) {
return false;
}
}
return true;
}
};
// Removal of a single range
var removeRangeManually = function(sel, range) {
var ranges = sel.getAllRanges(), removed = false;
sel.removeAllRanges();
for (var i = 0, len = ranges.length; i < len; ++i) {
if (removed || range !== ranges[i]) {
sel.addRange(ranges[i]);
} else {
// According to the draft WHATWG Range spec, the same range may be added to the selection multiple
// times. removeRange should only remove the first instance, so the following ensures only the first
// instance is removed
removed = true;
}
}
if (!sel.rangeCount) {
updateEmptySelection(sel);
}
};
if (implementsControlRange) {
selProto.removeRange = function(range) {
if (this.docSelection.type == CONTROL) {
var controlRange = this.docSelection.createRange();
var rangeElement = getSingleElementFromRange(range);
// Create a new ControlRange containing all the elements in the selected ControlRange minus the
// element contained by the supplied range
var doc = dom.getDocument(controlRange.item(0));
var newControlRange = dom.getBody(doc).createControlRange();
var el, removed = false;
for (var i = 0, len = controlRange.length; i < len; ++i) {
el = controlRange.item(i);
if (el !== rangeElement || removed) {
newControlRange.add(controlRange.item(i));
} else {
removed = true;
}
}
newControlRange.select();
// Update the wrapped selection based on what's now in the native selection
updateControlSelection(this);
} else {
removeRangeManually(this, range);
}
};
} else {
selProto.removeRange = function(range) {
removeRangeManually(this, range);
};
}
// Detecting if a selection is backwards
var selectionIsBackwards;
if (!useDocumentSelection && selectionHasAnchorAndFocus && api.features.implementsDomRange) {
selectionIsBackwards = function(sel) {
var backwards = false;
if (sel.anchorNode) {
backwards = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1);
}
return backwards;
};
selProto.isBackwards = function() {
return selectionIsBackwards(this);
};
} else {
selectionIsBackwards = selProto.isBackwards = function() {
return false;
};
}
// Selection text
// This is conformant to the new WHATWG DOM Range draft spec but differs from WebKit and Mozilla's implementation
selProto.toString = function() {
var rangeTexts = [];
for (var i = 0, len = this.rangeCount; i < len; ++i) {
rangeTexts[i] = "" + this._ranges[i];
}
return rangeTexts.join("");
};
function assertNodeInSameDocument(sel, node) {
if (sel.anchorNode && (dom.getDocument(sel.anchorNode) !== dom.getDocument(node))) {
throw new DOMException("WRONG_DOCUMENT_ERR");
}
}
// No current browsers conform fully to the HTML 5 draft spec for this method, so Rangy's own method is always used
selProto.collapse = function(node, offset) {
assertNodeInSameDocument(this, node);
var range = api.createRange(dom.getDocument(node));
range.collapseToPoint(node, offset);
this.removeAllRanges();
this.addRange(range);
this.isCollapsed = true;
};
selProto.collapseToStart = function() {
if (this.rangeCount) {
var range = this._ranges[0];
this.collapse(range.startContainer, range.startOffset);
} else {
throw new DOMException("INVALID_STATE_ERR");
}
};
selProto.collapseToEnd = function() {
if (this.rangeCount) {
var range = this._ranges[this.rangeCount - 1];
this.collapse(range.endContainer, range.endOffset);
} else {
throw new DOMException("INVALID_STATE_ERR");
}
};
// The HTML 5 spec is very specific on how selectAllChildren should be implemented so the native implementation is
// never used by Rangy.
selProto.selectAllChildren = function(node) {
assertNodeInSameDocument(this, node);
var range = api.createRange(dom.getDocument(node));
range.selectNodeContents(node);
this.removeAllRanges();
this.addRange(range);
};
selProto.deleteFromDocument = function() {
// Sepcial behaviour required for Control selections
if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
var controlRange = this.docSelection.createRange();
var element;
while (controlRange.length) {
element = controlRange.item(0);
controlRange.remove(element);
element.parentNode.removeChild(element);
}
this.refresh();
} else if (this.rangeCount) {
var ranges = this.getAllRanges();
this.removeAllRanges();
for (var i = 0, len = ranges.length; i < len; ++i) {
ranges[i].deleteContents();
}
// The HTML5 spec says nothing about what the selection should contain after calling deleteContents on each
// range. Firefox moves the selection to where the final selected range was, so we emulate that
this.addRange(ranges[len - 1]);
}
};
// The following are non-standard extensions
selProto.getAllRanges = function() {
return this._ranges.slice(0);
};
selProto.setSingleRange = function(range) {
this.setRanges( [range] );
};
selProto.containsNode = function(node, allowPartial) {
for (var i = 0, len = this._ranges.length; i < len; ++i) {
if (this._ranges[i].containsNode(node, allowPartial)) {
return true;
}
}
return false;
};
selProto.toHtml = function() {
var html = "";
if (this.rangeCount) {
var container = DomRange.getRangeDocument(this._ranges[0]).createElement("div");
for (var i = 0, len = this._ranges.length; i < len; ++i) {
container.appendChild(this._ranges[i].cloneContents());
}
html = container.innerHTML;
}
return html;
};
function inspect(sel) {
var rangeInspects = [];
var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset);
var focus = new DomPosition(sel.focusNode, sel.focusOffset);
var name = (typeof sel.getName == "function") ? sel.getName() : "Selection";
if (typeof sel.rangeCount != "undefined") {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i));
}
}
return "[" + name + "(Ranges: " + rangeInspects.join(", ") +
")(anchor: " + anchor.inspect() + ", focus: " + focus.inspect() + "]";
}
selProto.getName = function() {
return "WrappedSelection";
};
selProto.inspect = function() {
return inspect(this);
};
selProto.detach = function() {
this.win[windowPropertyName] = null;
this.win = this.anchorNode = this.focusNode = null;
};
WrappedSelection.inspect = inspect;
api.Selection = WrappedSelection;
api.selectionPrototype = selProto;
api.addCreateMissingNativeApiListener(function(win) {
if (typeof win.getSelection == "undefined") {
win.getSelection = function() {
return api.getSelection(this);
};
}
win = null;
});
});
/*
Base.js, version 1.1a
Copyright 2006-2010, Dean Edwards
License: http://www.opensource.org/licenses/mit-license.php
*/
var Base = function() {
// dummy
};
Base.extend = function(_instance, _static) { // subclass
var extend = Base.prototype.extend;
// build the prototype
Base._prototyping = true;
var proto = new this;
extend.call(proto, _instance);
proto.base = function() {
// call this method from any other method to invoke that method's ancestor
};
delete Base._prototyping;
// create the wrapper for the constructor function
//var constructor = proto.constructor.valueOf(); //-dean
var constructor = proto.constructor;
var klass = proto.constructor = function() {
if (!Base._prototyping) {
if (this._constructing || this.constructor == klass) { // instantiation
this._constructing = true;
constructor.apply(this, arguments);
delete this._constructing;
} else if (arguments[0] != null) { // casting
return (arguments[0].extend || extend).call(arguments[0], proto);
}
}
};
// build the class interface
klass.ancestor = this;
klass.extend = this.extend;
klass.forEach = this.forEach;
klass.implement = this.implement;
klass.prototype = proto;
klass.toString = this.toString;
klass.valueOf = function(type) {
//return (type == "object") ? klass : constructor; //-dean
return (type == "object") ? klass : constructor.valueOf();
};
extend.call(klass, _static);
// class initialisation
if (typeof klass.init == "function") klass.init();
return klass;
};
Base.prototype = {
extend: function(source, value) {
if (arguments.length > 1) { // extending with a name/value pair
var ancestor = this[source];
if (ancestor && (typeof value == "function") && // overriding a method?
// the valueOf() comparison is to avoid circular references
(!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) &&
/\bbase\b/.test(value)) {
// get the underlying method
var method = value.valueOf();
// override
value = function() {
var previous = this.base || Base.prototype.base;
this.base = ancestor;
var returnValue = method.apply(this, arguments);
this.base = previous;
return returnValue;
};
// point to the underlying method
value.valueOf = function(type) {
return (type == "object") ? value : method;
};
value.toString = Base.toString;
}
this[source] = value;
} else if (source) { // extending with an object literal
var extend = Base.prototype.extend;
// if this object has a customised extend method then use it
if (!Base._prototyping && typeof this != "function") {
extend = this.extend || extend;
}
var proto = {toSource: null};
// do the "toString" and other methods manually
var hidden = ["constructor", "toString", "valueOf"];
// if we are prototyping then include the constructor
var i = Base._prototyping ? 0 : 1;
while (key = hidden[i++]) {
if (source[key] != proto[key]) {
extend.call(this, key, source[key]);
}
}
// copy each of the source object's properties to this object
for (var key in source) {
if (!proto[key]) extend.call(this, key, source[key]);
}
}
return this;
}
};
// initialise
Base = Base.extend({
constructor: function() {
this.extend(arguments[0]);
}
}, {
ancestor: Object,
version: "1.1",
forEach: function(object, block, context) {
for (var key in object) {
if (this.prototype[key] === undefined) {
block.call(context, object[key], key, object);
}
}
},
implement: function() {
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == "function") {
// if it's a function, call it
arguments[i](this.prototype);
} else {
// add the interface using the extend method
this.prototype.extend(arguments[i]);
}
}
return this;
},
toString: function() {
return String(this.valueOf());
}
});/**
* Detect browser support for specific features
*/
wysihtml5.browser = (function() {
var userAgent = navigator.userAgent,
testElement = document.createElement("div"),
// Browser sniffing is unfortunately needed since some behaviors are impossible to feature detect
isIE = userAgent.indexOf("MSIE") !== -1 && userAgent.indexOf("Opera") === -1,
isGecko = userAgent.indexOf("Gecko") !== -1 && userAgent.indexOf("KHTML") === -1,
isWebKit = userAgent.indexOf("AppleWebKit/") !== -1,
isChrome = userAgent.indexOf("Chrome/") !== -1,
isOpera = userAgent.indexOf("Opera/") !== -1;
function iosVersion(userAgent) {
return ((/ipad|iphone|ipod/.test(userAgent) && userAgent.match(/ os (\d+).+? like mac os x/)) || [, 0])[1];
}
return {
// Static variable needed, publicly accessible, to be able override it in unit tests
USER_AGENT: userAgent,
/**
* Exclude browsers that are not capable of displaying and handling
* contentEditable as desired:
* - iPhone, iPad (tested iOS 4.2.2) and Android (tested 2.2) refuse to make contentEditables focusable
* - IE < 8 create invalid markup and crash randomly from time to time
*
* @return {Boolean}
*/
supported: function() {
var userAgent = this.USER_AGENT.toLowerCase(),
// Essential for making html elements editable
hasContentEditableSupport = "contentEditable" in testElement,
// Following methods are needed in order to interact with the contentEditable area
hasEditingApiSupport = document.execCommand && document.queryCommandSupported && document.queryCommandState,
// document selector apis are only supported by IE 8+, Safari 4+, Chrome and Firefox 3.5+
hasQuerySelectorSupport = document.querySelector && document.querySelectorAll,
// contentEditable is unusable in mobile browsers (tested iOS 4.2.2, Android 2.2, Opera Mobile, WebOS 3.05)
isIncompatibleMobileBrowser = (this.isIos() && iosVersion(userAgent) < 5) || userAgent.indexOf("opera mobi") !== -1 || userAgent.indexOf("hpwos/") !== -1;
return hasContentEditableSupport
&& hasEditingApiSupport
&& hasQuerySelectorSupport
&& !isIncompatibleMobileBrowser;
},
isTouchDevice: function() {
return this.supportsEvent("touchmove");
},
isIos: function() {
var userAgent = this.USER_AGENT.toLowerCase();
return userAgent.indexOf("webkit") !== -1 && userAgent.indexOf("mobile") !== -1;
},
/**
* Whether the browser supports sandboxed iframes
* Currently only IE 6+ offers such feature