twitter-typeahead-rails 0.10.5 → 0.11.1.pre.corejavascript

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,7 +1,8 @@
1
1
  /*!
2
- * typeahead.js 0.10.5
2
+ * typeahead.js 0.11.1
3
3
  * https://github.com/twitter/typeahead.js
4
- * Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
4
+ * Copyright 2013-2015 Twitter, Inc. and other contributors; Licensed MIT
5
5
  */
6
6
 
7
- !function(a){var b=function(){"use strict";return{isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:!1},isBlankString:function(a){return!a||/^\s*$/.test(a)},escapeRegExChars:function(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isArray:a.isArray,isFunction:a.isFunction,isObject:a.isPlainObject,isUndefined:function(a){return"undefined"==typeof a},toStr:function(a){return b.isUndefined(a)||null===a?"":a+""},bind:a.proxy,each:function(b,c){function d(a,b){return c(b,a)}a.each(b,d)},map:a.map,filter:a.grep,every:function(b,c){var d=!0;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?void 0:!1}),!!d):d},some:function(b,c){var d=!1;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?!1:void 0}),!!d):d},mixin:a.extend,getUniqueId:function(){var a=0;return function(){return a++}}(),templatify:function(b){function c(){return String(b)}return a.isFunction(b)?b:c},defer:function(a){setTimeout(a,0)},debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},throttle:function(a,b){var c,d,e,f,g,h;return g=0,h=function(){g=new Date,e=null,f=a.apply(c,d)},function(){var i=new Date,j=b-(i-g);return c=this,d=arguments,0>=j?(clearTimeout(e),e=null,g=i,f=a.apply(c,d)):e||(e=setTimeout(h,j)),f}},noop:function(){}}}(),c="0.10.5",d=function(){"use strict";function a(a){return a=b.toStr(a),a?a.split(/\s+/):[]}function c(a){return a=b.toStr(a),a?a.split(/\W+/):[]}function d(a){return function(){var c=[].slice.call(arguments,0);return function(d){var e=[];return b.each(c,function(c){e=e.concat(a(b.toStr(d[c])))}),e}}}return{nonword:c,whitespace:a,obj:{nonword:d(c),whitespace:d(a)}}}(),e=function(){"use strict";function c(c){this.maxSize=b.isNumber(c)?c:100,this.reset(),this.maxSize<=0&&(this.set=this.get=a.noop)}function d(){this.head=this.tail=null}function e(a,b){this.key=a,this.val=b,this.prev=this.next=null}return b.mixin(c.prototype,{set:function(a,b){var c,d=this.list.tail;this.size>=this.maxSize&&(this.list.remove(d),delete this.hash[d.key]),(c=this.hash[a])?(c.val=b,this.list.moveToFront(c)):(c=new e(a,b),this.list.add(c),this.hash[a]=c,this.size++)},get:function(a){var b=this.hash[a];return b?(this.list.moveToFront(b),b.val):void 0},reset:function(){this.size=0,this.hash={},this.list=new d}}),b.mixin(d.prototype,{add:function(a){this.head&&(a.next=this.head,this.head.prev=a),this.head=a,this.tail=this.tail||a},remove:function(a){a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev},moveToFront:function(a){this.remove(a),this.add(a)}}),c}(),f=function(){"use strict";function a(a){this.prefix=["__",a,"__"].join(""),this.ttlKey="__ttl__",this.keyMatcher=new RegExp("^"+b.escapeRegExChars(this.prefix))}function c(){return(new Date).getTime()}function d(a){return JSON.stringify(b.isUndefined(a)?null:a)}function e(a){return JSON.parse(a)}var f,g;try{f=window.localStorage,f.setItem("~~~","!"),f.removeItem("~~~")}catch(h){f=null}return g=f&&window.JSON?{_prefix:function(a){return this.prefix+a},_ttlKey:function(a){return this._prefix(a)+this.ttlKey},get:function(a){return this.isExpired(a)&&this.remove(a),e(f.getItem(this._prefix(a)))},set:function(a,e,g){return b.isNumber(g)?f.setItem(this._ttlKey(a),d(c()+g)):f.removeItem(this._ttlKey(a)),f.setItem(this._prefix(a),d(e))},remove:function(a){return f.removeItem(this._ttlKey(a)),f.removeItem(this._prefix(a)),this},clear:function(){var a,b,c=[],d=f.length;for(a=0;d>a;a++)(b=f.key(a)).match(this.keyMatcher)&&c.push(b.replace(this.keyMatcher,""));for(a=c.length;a--;)this.remove(c[a]);return this},isExpired:function(a){var d=e(f.getItem(this._ttlKey(a)));return b.isNumber(d)&&c()>d?!0:!1}}:{get:b.noop,set:b.noop,remove:b.noop,clear:b.noop,isExpired:b.noop},b.mixin(a.prototype,g),a}(),g=function(){"use strict";function c(b){b=b||{},this.cancelled=!1,this.lastUrl=null,this._send=b.transport?d(b.transport):a.ajax,this._get=b.rateLimiter?b.rateLimiter(this._get):this._get,this._cache=b.cache===!1?new e(0):i}function d(c){return function(d,e){function f(a){b.defer(function(){h.resolve(a)})}function g(a){b.defer(function(){h.reject(a)})}var h=a.Deferred();return c(d,e,f,g),h}}var f=0,g={},h=6,i=new e(10);return c.setMaxPendingRequests=function(a){h=a},c.resetCache=function(){i.reset()},b.mixin(c.prototype,{_get:function(a,b,c){function d(b){c&&c(null,b),k._cache.set(a,b)}function e(){c&&c(!0)}function i(){f--,delete g[a],k.onDeckRequestArgs&&(k._get.apply(k,k.onDeckRequestArgs),k.onDeckRequestArgs=null)}var j,k=this;this.cancelled||a!==this.lastUrl||((j=g[a])?j.done(d).fail(e):h>f?(f++,g[a]=this._send(a,b).done(d).fail(e).always(i)):this.onDeckRequestArgs=[].slice.call(arguments,0))},get:function(a,c,d){var e;return b.isFunction(c)&&(d=c,c={}),this.cancelled=!1,this.lastUrl=a,(e=this._cache.get(a))?b.defer(function(){d&&d(null,e)}):this._get(a,c,d),!!e},cancel:function(){this.cancelled=!0}}),c}(),h=function(){"use strict";function c(b){b=b||{},b.datumTokenizer&&b.queryTokenizer||a.error("datumTokenizer and queryTokenizer are both required"),this.datumTokenizer=b.datumTokenizer,this.queryTokenizer=b.queryTokenizer,this.reset()}function d(a){return a=b.filter(a,function(a){return!!a}),a=b.map(a,function(a){return a.toLowerCase()})}function e(){return{ids:[],children:{}}}function f(a){for(var b={},c=[],d=0,e=a.length;e>d;d++)b[a[d]]||(b[a[d]]=!0,c.push(a[d]));return c}function g(a,b){function c(a,b){return a-b}var d=0,e=0,f=[];a=a.sort(c),b=b.sort(c);for(var g=a.length,h=b.length;g>d&&h>e;)a[d]<b[e]?d++:a[d]>b[e]?e++:(f.push(a[d]),d++,e++);return f}return b.mixin(c.prototype,{bootstrap:function(a){this.datums=a.datums,this.trie=a.trie},add:function(a){var c=this;a=b.isArray(a)?a:[a],b.each(a,function(a){var f,g;f=c.datums.push(a)-1,g=d(c.datumTokenizer(a)),b.each(g,function(a){var b,d,g;for(b=c.trie,d=a.split("");g=d.shift();)b=b.children[g]||(b.children[g]=e()),b.ids.push(f)})})},get:function(a){var c,e,h=this;return c=d(this.queryTokenizer(a)),b.each(c,function(a){var b,c,d,f;if(e&&0===e.length)return!1;for(b=h.trie,c=a.split("");b&&(d=c.shift());)b=b.children[d];return b&&0===c.length?(f=b.ids.slice(0),void(e=e?g(e,f):f)):(e=[],!1)}),e?b.map(f(e),function(a){return h.datums[a]}):[]},reset:function(){this.datums=[],this.trie=e()},serialize:function(){return{datums:this.datums,trie:this.trie}}}),c}(),i=function(){"use strict";function d(a){return a.local||null}function e(d){var e,f;return f={url:null,thumbprint:"",ttl:864e5,filter:null,ajax:{}},(e=d.prefetch||null)&&(e=b.isString(e)?{url:e}:e,e=b.mixin(f,e),e.thumbprint=c+e.thumbprint,e.ajax.type=e.ajax.type||"GET",e.ajax.dataType=e.ajax.dataType||"json",!e.url&&a.error("prefetch requires url to be set")),e}function f(c){function d(a){return function(c){return b.debounce(c,a)}}function e(a){return function(c){return b.throttle(c,a)}}var f,g;return g={url:null,cache:!0,wildcard:"%QUERY",replace:null,rateLimitBy:"debounce",rateLimitWait:300,send:null,filter:null,ajax:{}},(f=c.remote||null)&&(f=b.isString(f)?{url:f}:f,f=b.mixin(g,f),f.rateLimiter=/^throttle$/i.test(f.rateLimitBy)?e(f.rateLimitWait):d(f.rateLimitWait),f.ajax.type=f.ajax.type||"GET",f.ajax.dataType=f.ajax.dataType||"json",delete f.rateLimitBy,delete f.rateLimitWait,!f.url&&a.error("remote requires url to be set")),f}return{local:d,prefetch:e,remote:f}}();!function(c){"use strict";function e(b){b&&(b.local||b.prefetch||b.remote)||a.error("one of local, prefetch, or remote is required"),this.limit=b.limit||5,this.sorter=j(b.sorter),this.dupDetector=b.dupDetector||k,this.local=i.local(b),this.prefetch=i.prefetch(b),this.remote=i.remote(b),this.cacheKey=this.prefetch?this.prefetch.cacheKey||this.prefetch.url:null,this.index=new h({datumTokenizer:b.datumTokenizer,queryTokenizer:b.queryTokenizer}),this.storage=this.cacheKey?new f(this.cacheKey):null}function j(a){function c(b){return b.sort(a)}function d(a){return a}return b.isFunction(a)?c:d}function k(){return!1}var l,m;return l=c.Bloodhound,m={data:"data",protocol:"protocol",thumbprint:"thumbprint"},c.Bloodhound=e,e.noConflict=function(){return c.Bloodhound=l,e},e.tokenizers=d,b.mixin(e.prototype,{_loadPrefetch:function(b){function c(a){f.clear(),f.add(b.filter?b.filter(a):a),f._saveToStorage(f.index.serialize(),b.thumbprint,b.ttl)}var d,e,f=this;return(d=this._readFromStorage(b.thumbprint))?(this.index.bootstrap(d),e=a.Deferred().resolve()):e=a.ajax(b.url,b.ajax).done(c),e},_getFromRemote:function(a,b){function c(a,c){b(a?[]:f.remote.filter?f.remote.filter(c):c)}var d,e,f=this;if(this.transport)return a=a||"",e=encodeURIComponent(a),d=this.remote.replace?this.remote.replace(this.remote.url,a):this.remote.url.replace(this.remote.wildcard,e),this.transport.get(d,this.remote.ajax,c)},_cancelLastRemoteRequest:function(){this.transport&&this.transport.cancel()},_saveToStorage:function(a,b,c){this.storage&&(this.storage.set(m.data,a,c),this.storage.set(m.protocol,location.protocol,c),this.storage.set(m.thumbprint,b,c))},_readFromStorage:function(a){var b,c={};return this.storage&&(c.data=this.storage.get(m.data),c.protocol=this.storage.get(m.protocol),c.thumbprint=this.storage.get(m.thumbprint)),b=c.thumbprint!==a||c.protocol!==location.protocol,c.data&&!b?c.data:null},_initialize:function(){function c(){e.add(b.isFunction(f)?f():f)}var d,e=this,f=this.local;return d=this.prefetch?this._loadPrefetch(this.prefetch):a.Deferred().resolve(),f&&d.done(c),this.transport=this.remote?new g(this.remote):null,this.initPromise=d.promise()},initialize:function(a){return!this.initPromise||a?this._initialize():this.initPromise},add:function(a){this.index.add(a)},get:function(a,c){function d(a){var d=f.slice(0);b.each(a,function(a){var c;return c=b.some(d,function(b){return e.dupDetector(a,b)}),!c&&d.push(a),d.length<e.limit}),c&&c(e.sorter(d))}var e=this,f=[],g=!1;f=this.index.get(a),f=this.sorter(f).slice(0,this.limit),f.length<this.limit?g=this._getFromRemote(a,d):this._cancelLastRemoteRequest(),g||(f.length>0||!this.transport)&&c&&c(f)},clear:function(){this.index.reset()},clearPrefetchCache:function(){this.storage&&this.storage.clear()},clearRemoteCache:function(){this.transport&&g.resetCache()},ttAdapter:function(){return b.bind(this.get,this)}}),e}(this);var j=function(){return{wrapper:'<span class="twitter-typeahead"></span>',dropdown:'<span class="tt-dropdown-menu"></span>',dataset:'<div class="tt-dataset-%CLASS%"></div>',suggestions:'<span class="tt-suggestions"></span>',suggestion:'<div class="tt-suggestion"></div>'}}(),k=function(){"use strict";var a={wrapper:{position:"relative",display:"inline-block"},hint:{position:"absolute",top:"0",left:"0",borderColor:"transparent",boxShadow:"none",opacity:"1"},input:{position:"relative",verticalAlign:"top",backgroundColor:"transparent"},inputWithNoHint:{position:"relative",verticalAlign:"top"},dropdown:{position:"absolute",top:"100%",left:"0",zIndex:"100",display:"none"},suggestions:{display:"block"},suggestion:{whiteSpace:"nowrap",cursor:"pointer"},suggestionChild:{whiteSpace:"normal"},ltr:{left:"0",right:"auto"},rtl:{left:"auto",right:" 0"}};return b.isMsie()&&b.mixin(a.input,{backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"}),b.isMsie()&&b.isMsie()<=7&&b.mixin(a.input,{marginTop:"-1px"}),a}(),l=function(){"use strict";function c(b){b&&b.el||a.error("EventBus initialized without el"),this.$el=a(b.el)}var d="typeahead:";return b.mixin(c.prototype,{trigger:function(a){var b=[].slice.call(arguments,1);this.$el.trigger(d+a,b)}}),c}(),m=function(){"use strict";function a(a,b,c,d){var e;if(!c)return this;for(b=b.split(i),c=d?h(c,d):c,this._callbacks=this._callbacks||{};e=b.shift();)this._callbacks[e]=this._callbacks[e]||{sync:[],async:[]},this._callbacks[e][a].push(c);return this}function b(b,c,d){return a.call(this,"async",b,c,d)}function c(b,c,d){return a.call(this,"sync",b,c,d)}function d(a){var b;if(!this._callbacks)return this;for(a=a.split(i);b=a.shift();)delete this._callbacks[b];return this}function e(a){var b,c,d,e,g;if(!this._callbacks)return this;for(a=a.split(i),d=[].slice.call(arguments,1);(b=a.shift())&&(c=this._callbacks[b]);)e=f(c.sync,this,[b].concat(d)),g=f(c.async,this,[b].concat(d)),e()&&j(g);return this}function f(a,b,c){function d(){for(var d,e=0,f=a.length;!d&&f>e;e+=1)d=a[e].apply(b,c)===!1;return!d}return d}function g(){var a;return a=window.setImmediate?function(a){setImmediate(function(){a()})}:function(a){setTimeout(function(){a()},0)}}function h(a,b){return a.bind?a.bind(b):function(){a.apply(b,[].slice.call(arguments,0))}}var i=/\s+/,j=g();return{onSync:c,onAsync:b,off:d,trigger:e}}(),n=function(a){"use strict";function c(a,c,d){for(var e,f=[],g=0,h=a.length;h>g;g++)f.push(b.escapeRegExChars(a[g]));return e=d?"\\b("+f.join("|")+")\\b":"("+f.join("|")+")",c?new RegExp(e):new RegExp(e,"i")}var d={node:null,pattern:null,tagName:"strong",className:null,wordsOnly:!1,caseSensitive:!1};return function(e){function f(b){var c,d,f;return(c=h.exec(b.data))&&(f=a.createElement(e.tagName),e.className&&(f.className=e.className),d=b.splitText(c.index),d.splitText(c[0].length),f.appendChild(d.cloneNode(!0)),b.parentNode.replaceChild(f,d)),!!c}function g(a,b){for(var c,d=3,e=0;e<a.childNodes.length;e++)c=a.childNodes[e],c.nodeType===d?e+=b(c)?1:0:g(c,b)}var h;e=b.mixin({},d,e),e.node&&e.pattern&&(e.pattern=b.isArray(e.pattern)?e.pattern:[e.pattern],h=c(e.pattern,e.caseSensitive,e.wordsOnly),g(e.node,f))}}(window.document),o=function(){"use strict";function c(c){var e,f,h,i,j=this;c=c||{},c.input||a.error("input is missing"),e=b.bind(this._onBlur,this),f=b.bind(this._onFocus,this),h=b.bind(this._onKeydown,this),i=b.bind(this._onInput,this),this.$hint=a(c.hint),this.$input=a(c.input).on("blur.tt",e).on("focus.tt",f).on("keydown.tt",h),0===this.$hint.length&&(this.setHint=this.getHint=this.clearHint=this.clearHintIfInvalid=b.noop),b.isMsie()?this.$input.on("keydown.tt keypress.tt cut.tt paste.tt",function(a){g[a.which||a.keyCode]||b.defer(b.bind(j._onInput,j,a))}):this.$input.on("input.tt",i),this.query=this.$input.val(),this.$overflowHelper=d(this.$input)}function d(b){return a('<pre aria-hidden="true"></pre>').css({position:"absolute",visibility:"hidden",whiteSpace:"pre",fontFamily:b.css("font-family"),fontSize:b.css("font-size"),fontStyle:b.css("font-style"),fontVariant:b.css("font-variant"),fontWeight:b.css("font-weight"),wordSpacing:b.css("word-spacing"),letterSpacing:b.css("letter-spacing"),textIndent:b.css("text-indent"),textRendering:b.css("text-rendering"),textTransform:b.css("text-transform")}).insertAfter(b)}function e(a,b){return c.normalizeQuery(a)===c.normalizeQuery(b)}function f(a){return a.altKey||a.ctrlKey||a.metaKey||a.shiftKey}var g;return g={9:"tab",27:"esc",37:"left",39:"right",13:"enter",38:"up",40:"down"},c.normalizeQuery=function(a){return(a||"").replace(/^\s*/g,"").replace(/\s{2,}/g," ")},b.mixin(c.prototype,m,{_onBlur:function(){this.resetInputValue(),this.trigger("blurred")},_onFocus:function(){this.trigger("focused")},_onKeydown:function(a){var b=g[a.which||a.keyCode];this._managePreventDefault(b,a),b&&this._shouldTrigger(b,a)&&this.trigger(b+"Keyed",a)},_onInput:function(){this._checkInputValue()},_managePreventDefault:function(a,b){var c,d,e;switch(a){case"tab":d=this.getHint(),e=this.getInputValue(),c=d&&d!==e&&!f(b);break;case"up":case"down":c=!f(b);break;default:c=!1}c&&b.preventDefault()},_shouldTrigger:function(a,b){var c;switch(a){case"tab":c=!f(b);break;default:c=!0}return c},_checkInputValue:function(){var a,b,c;a=this.getInputValue(),b=e(a,this.query),c=b?this.query.length!==a.length:!1,this.query=a,b?c&&this.trigger("whitespaceChanged",this.query):this.trigger("queryChanged",this.query)},focus:function(){this.$input.focus()},blur:function(){this.$input.blur()},getQuery:function(){return this.query},setQuery:function(a){this.query=a},getInputValue:function(){return this.$input.val()},setInputValue:function(a,b){this.$input.val(a),b?this.clearHint():this._checkInputValue()},resetInputValue:function(){this.setInputValue(this.query,!0)},getHint:function(){return this.$hint.val()},setHint:function(a){this.$hint.val(a)},clearHint:function(){this.setHint("")},clearHintIfInvalid:function(){var a,b,c,d;a=this.getInputValue(),b=this.getHint(),c=a!==b&&0===b.indexOf(a),d=""!==a&&c&&!this.hasOverflow(),!d&&this.clearHint()},getLanguageDirection:function(){return(this.$input.css("direction")||"ltr").toLowerCase()},hasOverflow:function(){var a=this.$input.width()-2;return this.$overflowHelper.text(this.getInputValue()),this.$overflowHelper.width()>=a},isCursorAtEnd:function(){var a,c,d;return a=this.$input.val().length,c=this.$input[0].selectionStart,b.isNumber(c)?c===a:document.selection?(d=document.selection.createRange(),d.moveStart("character",-a),a===d.text.length):!0},destroy:function(){this.$hint.off(".tt"),this.$input.off(".tt"),this.$hint=this.$input=this.$overflowHelper=null}}),c}(),p=function(){"use strict";function c(c){c=c||{},c.templates=c.templates||{},c.source||a.error("missing source"),c.name&&!f(c.name)&&a.error("invalid dataset name: "+c.name),this.query=null,this.highlight=!!c.highlight,this.name=c.name||b.getUniqueId(),this.source=c.source,this.displayFn=d(c.display||c.displayKey),this.templates=e(c.templates,this.displayFn),this.$el=a(j.dataset.replace("%CLASS%",this.name))}function d(a){function c(b){return b[a]}return a=a||"value",b.isFunction(a)?a:c}function e(a,c){function d(a){return"<p>"+c(a)+"</p>"}return{empty:a.empty&&b.templatify(a.empty),header:a.header&&b.templatify(a.header),footer:a.footer&&b.templatify(a.footer),suggestion:a.suggestion||d}}function f(a){return/^[_a-zA-Z0-9-]+$/.test(a)}var g="ttDataset",h="ttValue",i="ttDatum";return c.extractDatasetName=function(b){return a(b).data(g)},c.extractValue=function(b){return a(b).data(h)},c.extractDatum=function(b){return a(b).data(i)},b.mixin(c.prototype,m,{_render:function(c,d){function e(){return p.templates.empty({query:c,isEmpty:!0})}function f(){function e(b){var c;return c=a(j.suggestion).append(p.templates.suggestion(b)).data(g,p.name).data(h,p.displayFn(b)).data(i,b),c.children().each(function(){a(this).css(k.suggestionChild)}),c}var f,l;return f=a(j.suggestions).css(k.suggestions),l=b.map(d,e),f.append.apply(f,l),p.highlight&&n({className:"tt-highlight",node:f[0],pattern:c}),f}function l(){return p.templates.header({query:c,isEmpty:!o})}function m(){return p.templates.footer({query:c,isEmpty:!o})}if(this.$el){var o,p=this;this.$el.empty(),o=d&&d.length,!o&&this.templates.empty?this.$el.html(e()).prepend(p.templates.header?l():null).append(p.templates.footer?m():null):o&&this.$el.html(f()).prepend(p.templates.header?l():null).append(p.templates.footer?m():null),this.trigger("rendered")}},getRoot:function(){return this.$el},update:function(a){function b(b){c.canceled||a!==c.query||c._render(a,b)}var c=this;this.query=a,this.canceled=!1,this.source(a,b)},cancel:function(){this.canceled=!0},clear:function(){this.cancel(),this.$el.empty(),this.trigger("rendered")},isEmpty:function(){return this.$el.is(":empty")},destroy:function(){this.$el=null}}),c}(),q=function(){"use strict";function c(c){var e,f,g,h=this;c=c||{},c.menu||a.error("menu is required"),this.isOpen=!1,this.isEmpty=!0,this.datasets=b.map(c.datasets,d),e=b.bind(this._onSuggestionClick,this),f=b.bind(this._onSuggestionMouseEnter,this),g=b.bind(this._onSuggestionMouseLeave,this),this.$menu=a(c.menu).on("click.tt",".tt-suggestion",e).on("mouseenter.tt",".tt-suggestion",f).on("mouseleave.tt",".tt-suggestion",g),b.each(this.datasets,function(a){h.$menu.append(a.getRoot()),a.onSync("rendered",h._onRendered,h)})}function d(a){return new p(a)}return b.mixin(c.prototype,m,{_onSuggestionClick:function(b){this.trigger("suggestionClicked",a(b.currentTarget))},_onSuggestionMouseEnter:function(b){this._removeCursor(),this._setCursor(a(b.currentTarget),!0)},_onSuggestionMouseLeave:function(){this._removeCursor()},_onRendered:function(){function a(a){return a.isEmpty()}this.isEmpty=b.every(this.datasets,a),this.isEmpty?this._hide():this.isOpen&&this._show(),this.trigger("datasetRendered")},_hide:function(){this.$menu.hide()},_show:function(){this.$menu.css("display","block")},_getSuggestions:function(){return this.$menu.find(".tt-suggestion")},_getCursor:function(){return this.$menu.find(".tt-cursor").first()},_setCursor:function(a,b){a.first().addClass("tt-cursor"),!b&&this.trigger("cursorMoved")},_removeCursor:function(){this._getCursor().removeClass("tt-cursor")},_moveCursor:function(a){var b,c,d,e;if(this.isOpen){if(c=this._getCursor(),b=this._getSuggestions(),this._removeCursor(),d=b.index(c)+a,d=(d+1)%(b.length+1)-1,-1===d)return void this.trigger("cursorRemoved");-1>d&&(d=b.length-1),this._setCursor(e=b.eq(d)),this._ensureVisible(e)}},_ensureVisible:function(a){var b,c,d,e;b=a.position().top,c=b+a.outerHeight(!0),d=this.$menu.scrollTop(),e=this.$menu.height()+parseInt(this.$menu.css("paddingTop"),10)+parseInt(this.$menu.css("paddingBottom"),10),0>b?this.$menu.scrollTop(d+b):c>e&&this.$menu.scrollTop(d+(c-e))},close:function(){this.isOpen&&(this.isOpen=!1,this._removeCursor(),this._hide(),this.trigger("closed"))},open:function(){this.isOpen||(this.isOpen=!0,!this.isEmpty&&this._show(),this.trigger("opened"))},setLanguageDirection:function(a){this.$menu.css("ltr"===a?k.ltr:k.rtl)},moveCursorUp:function(){this._moveCursor(-1)},moveCursorDown:function(){this._moveCursor(1)},getDatumForSuggestion:function(a){var b=null;return a.length&&(b={raw:p.extractDatum(a),value:p.extractValue(a),datasetName:p.extractDatasetName(a)}),b},getDatumForCursor:function(){return this.getDatumForSuggestion(this._getCursor().first())},getDatumForTopSuggestion:function(){return this.getDatumForSuggestion(this._getSuggestions().first())},update:function(a){function c(b){b.update(a)}b.each(this.datasets,c)},empty:function(){function a(a){a.clear()}b.each(this.datasets,a),this.isEmpty=!0},isVisible:function(){return this.isOpen&&!this.isEmpty},destroy:function(){function a(a){a.destroy()}this.$menu.off(".tt"),this.$menu=null,b.each(this.datasets,a)}}),c}(),r=function(){"use strict";function c(c){var e,f,g;c=c||{},c.input||a.error("missing input"),this.isActivated=!1,this.autoselect=!!c.autoselect,this.minLength=b.isNumber(c.minLength)?c.minLength:1,this.$node=d(c.input,c.withHint),e=this.$node.find(".tt-dropdown-menu"),f=this.$node.find(".tt-input"),g=this.$node.find(".tt-hint"),f.on("blur.tt",function(a){var c,d,g;c=document.activeElement,d=e.is(c),g=e.has(c).length>0,b.isMsie()&&(d||g)&&(a.preventDefault(),a.stopImmediatePropagation(),b.defer(function(){f.focus()}))}),e.on("mousedown.tt",function(a){a.preventDefault()}),this.eventBus=c.eventBus||new l({el:f}),this.dropdown=new q({menu:e,datasets:c.datasets}).onSync("suggestionClicked",this._onSuggestionClicked,this).onSync("cursorMoved",this._onCursorMoved,this).onSync("cursorRemoved",this._onCursorRemoved,this).onSync("opened",this._onOpened,this).onSync("closed",this._onClosed,this).onAsync("datasetRendered",this._onDatasetRendered,this),this.input=new o({input:f,hint:g}).onSync("focused",this._onFocused,this).onSync("blurred",this._onBlurred,this).onSync("enterKeyed",this._onEnterKeyed,this).onSync("tabKeyed",this._onTabKeyed,this).onSync("escKeyed",this._onEscKeyed,this).onSync("upKeyed",this._onUpKeyed,this).onSync("downKeyed",this._onDownKeyed,this).onSync("leftKeyed",this._onLeftKeyed,this).onSync("rightKeyed",this._onRightKeyed,this).onSync("queryChanged",this._onQueryChanged,this).onSync("whitespaceChanged",this._onWhitespaceChanged,this),this._setLanguageDirection()}function d(b,c){var d,f,h,i;d=a(b),f=a(j.wrapper).css(k.wrapper),h=a(j.dropdown).css(k.dropdown),i=d.clone().css(k.hint).css(e(d)),i.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder required").prop("readonly",!0).attr({autocomplete:"off",spellcheck:"false",tabindex:-1}),d.data(g,{dir:d.attr("dir"),autocomplete:d.attr("autocomplete"),spellcheck:d.attr("spellcheck"),style:d.attr("style")}),d.addClass("tt-input").attr({autocomplete:"off",spellcheck:!1}).css(c?k.input:k.inputWithNoHint);try{!d.attr("dir")&&d.attr("dir","auto")}catch(l){}return d.wrap(f).parent().prepend(c?i:null).append(h)}function e(a){return{backgroundAttachment:a.css("background-attachment"),backgroundClip:a.css("background-clip"),backgroundColor:a.css("background-color"),backgroundImage:a.css("background-image"),backgroundOrigin:a.css("background-origin"),backgroundPosition:a.css("background-position"),backgroundRepeat:a.css("background-repeat"),backgroundSize:a.css("background-size")}}function f(a){var c=a.find(".tt-input");b.each(c.data(g),function(a,d){b.isUndefined(a)?c.removeAttr(d):c.attr(d,a)}),c.detach().removeData(g).removeClass("tt-input").insertAfter(a),a.remove()}var g="ttAttrs";return b.mixin(c.prototype,{_onSuggestionClicked:function(a,b){var c;(c=this.dropdown.getDatumForSuggestion(b))&&this._select(c)},_onCursorMoved:function(){var a=this.dropdown.getDatumForCursor();this.input.setInputValue(a.value,!0),this.eventBus.trigger("cursorchanged",a.raw,a.datasetName)},_onCursorRemoved:function(){this.input.resetInputValue(),this._updateHint()},_onDatasetRendered:function(){this._updateHint()},_onOpened:function(){this._updateHint(),this.eventBus.trigger("opened")},_onClosed:function(){this.input.clearHint(),this.eventBus.trigger("closed")},_onFocused:function(){this.isActivated=!0,this.dropdown.open()},_onBlurred:function(){this.isActivated=!1,this.dropdown.empty(),this.dropdown.close()},_onEnterKeyed:function(a,b){var c,d;c=this.dropdown.getDatumForCursor(),d=this.dropdown.getDatumForTopSuggestion(),c?(this._select(c),b.preventDefault()):this.autoselect&&d&&(this._select(d),b.preventDefault())},_onTabKeyed:function(a,b){var c;(c=this.dropdown.getDatumForCursor())?(this._select(c),b.preventDefault()):this._autocomplete(!0)},_onEscKeyed:function(){this.dropdown.close(),this.input.resetInputValue()},_onUpKeyed:function(){var a=this.input.getQuery();this.dropdown.isEmpty&&a.length>=this.minLength?this.dropdown.update(a):this.dropdown.moveCursorUp(),this.dropdown.open()},_onDownKeyed:function(){var a=this.input.getQuery();this.dropdown.isEmpty&&a.length>=this.minLength?this.dropdown.update(a):this.dropdown.moveCursorDown(),this.dropdown.open()},_onLeftKeyed:function(){"rtl"===this.dir&&this._autocomplete()},_onRightKeyed:function(){"ltr"===this.dir&&this._autocomplete()},_onQueryChanged:function(a,b){this.input.clearHintIfInvalid(),b.length>=this.minLength?this.dropdown.update(b):this.dropdown.empty(),this.dropdown.open(),this._setLanguageDirection()},_onWhitespaceChanged:function(){this._updateHint(),this.dropdown.open()},_setLanguageDirection:function(){var a;this.dir!==(a=this.input.getLanguageDirection())&&(this.dir=a,this.$node.css("direction",a),this.dropdown.setLanguageDirection(a))},_updateHint:function(){var a,c,d,e,f,g;a=this.dropdown.getDatumForTopSuggestion(),a&&this.dropdown.isVisible()&&!this.input.hasOverflow()?(c=this.input.getInputValue(),d=o.normalizeQuery(c),e=b.escapeRegExChars(d),f=new RegExp("^(?:"+e+")(.+$)","i"),g=f.exec(a.value),g?this.input.setHint(c+g[1]):this.input.clearHint()):this.input.clearHint()},_autocomplete:function(a){var b,c,d,e;b=this.input.getHint(),c=this.input.getQuery(),d=a||this.input.isCursorAtEnd(),b&&c!==b&&d&&(e=this.dropdown.getDatumForTopSuggestion(),e&&this.input.setInputValue(e.value),this.eventBus.trigger("autocompleted",e.raw,e.datasetName))},_select:function(a){this.input.setQuery(a.value),this.input.setInputValue(a.value,!0),this._setLanguageDirection(),this.eventBus.trigger("selected",a.raw,a.datasetName),this.dropdown.close(),b.defer(b.bind(this.dropdown.empty,this.dropdown))},open:function(){this.dropdown.open()},close:function(){this.dropdown.close()},setVal:function(a){a=b.toStr(a),this.isActivated?this.input.setInputValue(a):(this.input.setQuery(a),this.input.setInputValue(a,!0)),this._setLanguageDirection()},getVal:function(){return this.input.getQuery()},destroy:function(){this.input.destroy(),this.dropdown.destroy(),f(this.$node),this.$node=null}}),c}();!function(){"use strict";var c,d,e;c=a.fn.typeahead,d="ttTypeahead",e={initialize:function(c,e){function f(){var f,g,h=a(this);b.each(e,function(a){a.highlight=!!c.highlight}),g=new r({input:h,eventBus:f=new l({el:h}),withHint:b.isUndefined(c.hint)?!0:!!c.hint,minLength:c.minLength,autoselect:c.autoselect,datasets:e}),h.data(d,g)}return e=b.isArray(e)?e:[].slice.call(arguments,1),c=c||{},this.each(f)},open:function(){function b(){var b,c=a(this);(b=c.data(d))&&b.open()}return this.each(b)},close:function(){function b(){var b,c=a(this);(b=c.data(d))&&b.close()}return this.each(b)},val:function(b){function c(){var c,e=a(this);(c=e.data(d))&&c.setVal(b)}function e(a){var b,c;return(b=a.data(d))&&(c=b.getVal()),c}return arguments.length?this.each(c):e(this.first())},destroy:function(){function b(){var b,c=a(this);(b=c.data(d))&&(b.destroy(),c.removeData(d))}return this.each(b)}},a.fn.typeahead=function(b){var c;return e[b]&&"initialize"!==b?(c=this.filter(function(){return!!a(this).data(d)}),e[b].apply(c,[].slice.call(arguments,1))):e.initialize.apply(this,arguments)},a.fn.typeahead.noConflict=function(){return a.fn.typeahead=c,this}}()}(window.jQuery);
7
+ !function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(c){return a.Bloodhound=b(c)}):"object"==typeof exports?module.exports=b(require("jquery")):a.Bloodhound=b(jQuery)}(this,function(a){var b=function(){"use strict";return{isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:!1},isBlankString:function(a){return!a||/^\s*$/.test(a)},escapeRegExChars:function(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isArray:a.isArray,isFunction:a.isFunction,isObject:a.isPlainObject,isUndefined:function(a){return"undefined"==typeof a},isElement:function(a){return!(!a||1!==a.nodeType)},isJQuery:function(b){return b instanceof a},toStr:function(a){return b.isUndefined(a)||null===a?"":a+""},bind:a.proxy,each:function(b,c){function d(a,b){return c(b,a)}a.each(b,d)},map:a.map,filter:a.grep,every:function(b,c){var d=!0;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?void 0:!1}),!!d):d},some:function(b,c){var d=!1;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?!1:void 0}),!!d):d},mixin:a.extend,identity:function(a){return a},clone:function(b){return a.extend(!0,{},b)},getIdGenerator:function(){var a=0;return function(){return a++}},templatify:function(b){function c(){return String(b)}return a.isFunction(b)?b:c},defer:function(a){setTimeout(a,0)},debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},throttle:function(a,b){var c,d,e,f,g,h;return g=0,h=function(){g=new Date,e=null,f=a.apply(c,d)},function(){var i=new Date,j=b-(i-g);return c=this,d=arguments,0>=j?(clearTimeout(e),e=null,g=i,f=a.apply(c,d)):e||(e=setTimeout(h,j)),f}},stringify:function(a){return b.isString(a)?a:JSON.stringify(a)},noop:function(){}}}(),c="0.11.1",d=function(){"use strict";function a(a){return a=b.toStr(a),a?a.split(/\s+/):[]}function c(a){return a=b.toStr(a),a?a.split(/\W+/):[]}function d(a){return function(c){return c=b.isArray(c)?c:[].slice.call(arguments,0),function(d){var e=[];return b.each(c,function(c){e=e.concat(a(b.toStr(d[c])))}),e}}}return{nonword:c,whitespace:a,obj:{nonword:d(c),whitespace:d(a)}}}(),e=function(){"use strict";function c(c){this.maxSize=b.isNumber(c)?c:100,this.reset(),this.maxSize<=0&&(this.set=this.get=a.noop)}function d(){this.head=this.tail=null}function e(a,b){this.key=a,this.val=b,this.prev=this.next=null}return b.mixin(c.prototype,{set:function(a,b){var c,d=this.list.tail;this.size>=this.maxSize&&(this.list.remove(d),delete this.hash[d.key],this.size--),(c=this.hash[a])?(c.val=b,this.list.moveToFront(c)):(c=new e(a,b),this.list.add(c),this.hash[a]=c,this.size++)},get:function(a){var b=this.hash[a];return b?(this.list.moveToFront(b),b.val):void 0},reset:function(){this.size=0,this.hash={},this.list=new d}}),b.mixin(d.prototype,{add:function(a){this.head&&(a.next=this.head,this.head.prev=a),this.head=a,this.tail=this.tail||a},remove:function(a){a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev},moveToFront:function(a){this.remove(a),this.add(a)}}),c}(),f=function(){"use strict";function c(a,c){this.prefix=["__",a,"__"].join(""),this.ttlKey="__ttl__",this.keyMatcher=new RegExp("^"+b.escapeRegExChars(this.prefix)),this.ls=c||h,!this.ls&&this._noop()}function d(){return(new Date).getTime()}function e(a){return JSON.stringify(b.isUndefined(a)?null:a)}function f(b){return a.parseJSON(b)}function g(a){var b,c,d=[],e=h.length;for(b=0;e>b;b++)(c=h.key(b)).match(a)&&d.push(c.replace(a,""));return d}var h;try{h=window.localStorage,h.setItem("~~~","!"),h.removeItem("~~~")}catch(i){h=null}return b.mixin(c.prototype,{_prefix:function(a){return this.prefix+a},_ttlKey:function(a){return this._prefix(a)+this.ttlKey},_noop:function(){this.get=this.set=this.remove=this.clear=this.isExpired=b.noop},_safeSet:function(a,b){try{this.ls.setItem(a,b)}catch(c){"QuotaExceededError"===c.name&&(this.clear(),this._noop())}},get:function(a){return this.isExpired(a)&&this.remove(a),f(this.ls.getItem(this._prefix(a)))},set:function(a,c,f){return b.isNumber(f)?this._safeSet(this._ttlKey(a),e(d()+f)):this.ls.removeItem(this._ttlKey(a)),this._safeSet(this._prefix(a),e(c))},remove:function(a){return this.ls.removeItem(this._ttlKey(a)),this.ls.removeItem(this._prefix(a)),this},clear:function(){var a,b=g(this.keyMatcher);for(a=b.length;a--;)this.remove(b[a]);return this},isExpired:function(a){var c=f(this.ls.getItem(this._ttlKey(a)));return b.isNumber(c)&&d()>c?!0:!1}}),c}(),g=function(){"use strict";function c(a){a=a||{},this.cancelled=!1,this.lastReq=null,this._send=a.transport,this._get=a.limiter?a.limiter(this._get):this._get,this._cache=a.cache===!1?new e(0):h}var d=0,f={},g=6,h=new e(10);return c.setMaxPendingRequests=function(a){g=a},c.resetCache=function(){h.reset()},b.mixin(c.prototype,{_fingerprint:function(b){return b=b||{},b.url+b.type+a.param(b.data||{})},_get:function(a,b){function c(a){b(null,a),k._cache.set(i,a)}function e(){b(!0)}function h(){d--,delete f[i],k.onDeckRequestArgs&&(k._get.apply(k,k.onDeckRequestArgs),k.onDeckRequestArgs=null)}var i,j,k=this;i=this._fingerprint(a),this.cancelled||i!==this.lastReq||((j=f[i])?j.done(c).fail(e):g>d?(d++,f[i]=this._send(a).done(c).fail(e).always(h)):this.onDeckRequestArgs=[].slice.call(arguments,0))},get:function(c,d){var e,f;d=d||a.noop,c=b.isString(c)?{url:c}:c||{},f=this._fingerprint(c),this.cancelled=!1,this.lastReq=f,(e=this._cache.get(f))?d(null,e):this._get(c,d)},cancel:function(){this.cancelled=!0}}),c}(),h=window.SearchIndex=function(){"use strict";function c(c){c=c||{},c.datumTokenizer&&c.queryTokenizer||a.error("datumTokenizer and queryTokenizer are both required"),this.identify=c.identify||b.stringify,this.datumTokenizer=c.datumTokenizer,this.queryTokenizer=c.queryTokenizer,this.matchAnyQueryToken=c.matchAnyQueryToken,this.reset()}function d(a){return a=b.filter(a,function(a){return!!a}),a=b.map(a,function(a){return a.toLowerCase()})}function e(){var a={};return a[i]=[],a[h]={},a}function f(a){for(var b={},c=[],d=0,e=a.length;e>d;d++)b[a[d]]||(b[a[d]]=!0,c.push(a[d]));return c}function g(a,b){var c=0,d=0,e=[];a=a.sort(),b=b.sort();for(var f=a.length,g=b.length;f>c&&g>d;)a[c]<b[d]?c++:a[c]>b[d]?d++:(e.push(a[c]),c++,d++);return e}var h="c",i="i";return b.mixin(c.prototype,{bootstrap:function(a){this.datums=a.datums,this.trie=a.trie},add:function(a){var c=this;a=b.isArray(a)?a:[a],b.each(a,function(a){var f,g;c.datums[f=c.identify(a)]=a,g=d(c.datumTokenizer(a)),b.each(g,function(a){var b,d,g;for(b=c.trie,d=a.split("");g=d.shift();)b=b[h][g]||(b[h][g]=e()),b[i].push(f)})})},get:function(a){var c=this;return b.map(a,function(a){return c.datums[a]})},search:function(a){var c,e,j=this;return c=d(this.queryTokenizer(a)),b.each(c,function(a){var b,c,d,f;if(e&&0===e.length&&!j.matchAnyQueryToken)return!1;for(b=j.trie,c=a.split("");b&&(d=c.shift());)b=b[h][d];if(b&&0===c.length)f=b[i].slice(0),e=e?g(e,f):f;else if(!j.matchAnyQueryToken)return e=[],!1}),e?b.map(f(e),function(a){return j.datums[a]}):[]},all:function(){var a=[];for(var b in this.datums)a.push(this.datums[b]);return a},reset:function(){this.datums={},this.trie=e()},serialize:function(){return{datums:this.datums,trie:this.trie}}}),c}(),i=function(){"use strict";function a(a){this.url=a.url,this.ttl=a.ttl,this.cache=a.cache,this.prepare=a.prepare,this.transform=a.transform,this.transport=a.transport,this.thumbprint=a.thumbprint,this.storage=new f(a.cacheKey)}var c;return c={data:"data",protocol:"protocol",thumbprint:"thumbprint"},b.mixin(a.prototype,{_settings:function(){return{url:this.url,type:"GET",dataType:"json"}},store:function(a){this.cache&&(this.storage.set(c.data,a,this.ttl),this.storage.set(c.protocol,location.protocol,this.ttl),this.storage.set(c.thumbprint,this.thumbprint,this.ttl))},fromCache:function(){var a,b={};return this.cache?(b.data=this.storage.get(c.data),b.protocol=this.storage.get(c.protocol),b.thumbprint=this.storage.get(c.thumbprint),a=b.thumbprint!==this.thumbprint||b.protocol!==location.protocol,b.data&&!a?b.data:null):null},fromNetwork:function(a){function b(){a(!0)}function c(b){a(null,e.transform(b))}var d,e=this;a&&(d=this.prepare(this._settings()),this.transport(d).fail(b).done(c))},clear:function(){return this.storage.clear(),this}}),a}(),j=function(){"use strict";function a(a){this.url=a.url,this.prepare=a.prepare,this.transform=a.transform,this.indexResponse=a.indexResponse,this.transport=new g({cache:a.cache,limiter:a.limiter,transport:a.transport})}return b.mixin(a.prototype,{_settings:function(){return{url:this.url,type:"GET",dataType:"json"}},get:function(a,b){function c(a,c){b(a?[]:e.transform(c))}var d,e=this;if(b)return a=a||"",d=this.prepare(a,this._settings()),this.transport.get(d,c)},cancelLastRequest:function(){this.transport.cancel()}}),a}(),k=function(){"use strict";function d(d){var e;return d?(e={url:null,ttl:864e5,cache:!0,cacheKey:null,thumbprint:"",prepare:b.identity,transform:b.identity,transport:null},d=b.isString(d)?{url:d}:d,d=b.mixin(e,d),!d.url&&a.error("prefetch requires url to be set"),d.transform=d.filter||d.transform,d.cacheKey=d.cacheKey||d.url,d.thumbprint=c+d.thumbprint,d.transport=d.transport?h(d.transport):a.ajax,d):null}function e(c){var d;if(c)return d={url:null,cache:!0,prepare:null,replace:null,wildcard:null,limiter:null,rateLimitBy:"debounce",rateLimitWait:300,transform:b.identity,transport:null},c=b.isString(c)?{url:c}:c,c=b.mixin(d,c),!c.url&&a.error("remote requires url to be set"),c.transform=c.filter||c.transform,c.prepare=f(c),c.limiter=g(c),c.transport=c.transport?h(c.transport):a.ajax,delete c.replace,delete c.wildcard,delete c.rateLimitBy,delete c.rateLimitWait,c}function f(a){function b(a,b){return b.url=f(b.url,a),b}function c(a,b){return b.url=b.url.replace(g,encodeURIComponent(a)),b}function d(a,b){return b}var e,f,g;return e=a.prepare,f=a.replace,g=a.wildcard,e?e:e=f?b:a.wildcard?c:d}function g(a){function c(a){return function(c){return b.debounce(c,a)}}function d(a){return function(c){return b.throttle(c,a)}}var e,f,g;return e=a.limiter,f=a.rateLimitBy,g=a.rateLimitWait,e||(e=/^throttle$/i.test(f)?d(g):c(g)),e}function h(c){return function(d){function e(a){b.defer(function(){g.resolve(a)})}function f(a){b.defer(function(){g.reject(a)})}var g=a.Deferred();return c(d,e,f),g}}return function(c){var f,g;return f={initialize:!0,identify:b.stringify,datumTokenizer:null,queryTokenizer:null,matchAnyQueryToken:!1,sufficient:5,indexRemote:!1,sorter:null,local:[],prefetch:null,remote:null},c=b.mixin(f,c||{}),!c.datumTokenizer&&a.error("datumTokenizer is required"),!c.queryTokenizer&&a.error("queryTokenizer is required"),g=c.sorter,c.sorter=g?function(a){return a.sort(g)}:b.identity,c.local=b.isFunction(c.local)?c.local():c.local,c.prefetch=d(c.prefetch),c.remote=e(c.remote),c}}(),l=function(){"use strict";function c(a){a=k(a),this.sorter=a.sorter,this.identify=a.identify,this.sufficient=a.sufficient,this.indexRemote=a.indexRemote,this.local=a.local,this.remote=a.remote?new j(a.remote):null,this.prefetch=a.prefetch?new i(a.prefetch):null,this.index=new h({identify:this.identify,datumTokenizer:a.datumTokenizer,queryTokenizer:a.queryTokenizer}),a.initialize!==!1&&this.initialize()}var e;return e=window&&window.Bloodhound,c.noConflict=function(){return window&&(window.Bloodhound=e),c},c.tokenizers=d,b.mixin(c.prototype,{__ttAdapter:function(){function a(a,b,d){return c.search(a,b,d)}function b(a,b){return c.search(a,b)}var c=this;return this.remote?a:b},_loadPrefetch:function(){function b(a,b){return a?c.reject():(e.add(b),e.prefetch.store(e.index.serialize()),void c.resolve())}var c,d,e=this;return c=a.Deferred(),this.prefetch?(d=this.prefetch.fromCache())?(this.index.bootstrap(d),c.resolve()):this.prefetch.fromNetwork(b):c.resolve(),c.promise()},_initialize:function(){function a(){b.add(b.local)}var b=this;return this.clear(),(this.initPromise=this._loadPrefetch()).done(a),this.initPromise},initialize:function(a){return!this.initPromise||a?this._initialize():this.initPromise},add:function(a){return this.index.add(a),this},get:function(a){return a=b.isArray(a)?a:[].slice.call(arguments),this.index.get(a)},search:function(a,c,d){function e(a){var c=[];b.each(a,function(a){!b.some(f,function(b){return g.identify(a)===g.identify(b)})&&c.push(a)}),g.indexRemote&&g.add(c),d(c)}var f,g=this;return c=c||b.noop,d=d||b.noop,f=this.sorter(this.index.search(a)),c(this.remote?f.slice():f),this.remote&&f.length<this.sufficient?this.remote.get(a,e):this.remote&&this.remote.cancelLastRequest(),this},all:function(){return this.index.all()},clear:function(){return this.index.reset(),this},clearPrefetchCache:function(){return this.prefetch&&this.prefetch.clear(),this},clearRemoteCache:function(){return g.resetCache(),this},ttAdapter:function(){return this.__ttAdapter()}}),c}();return l}),function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,function(a){var b=function(){"use strict";return{isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:!1},isBlankString:function(a){return!a||/^\s*$/.test(a)},escapeRegExChars:function(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isArray:a.isArray,isFunction:a.isFunction,isObject:a.isPlainObject,isUndefined:function(a){return"undefined"==typeof a},isElement:function(a){return!(!a||1!==a.nodeType)},isJQuery:function(b){return b instanceof a},toStr:function(a){return b.isUndefined(a)||null===a?"":a+""},bind:a.proxy,each:function(b,c){function d(a,b){return c(b,a)}a.each(b,d)},map:a.map,filter:a.grep,every:function(b,c){var d=!0;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?void 0:!1}),!!d):d},some:function(b,c){var d=!1;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?!1:void 0}),!!d):d},mixin:a.extend,identity:function(a){return a},clone:function(b){return a.extend(!0,{},b)},getIdGenerator:function(){var a=0;return function(){return a++}},templatify:function(b){function c(){return String(b)}return a.isFunction(b)?b:c},defer:function(a){setTimeout(a,0)},debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},throttle:function(a,b){var c,d,e,f,g,h;return g=0,h=function(){g=new Date,e=null,f=a.apply(c,d)},function(){var i=new Date,j=b-(i-g);return c=this,d=arguments,0>=j?(clearTimeout(e),e=null,g=i,f=a.apply(c,d)):e||(e=setTimeout(h,j)),f}},stringify:function(a){return b.isString(a)?a:JSON.stringify(a)},noop:function(){}}}(),c=function(){"use strict";function a(a){var g,h;return h=b.mixin({},f,a),g={css:e(),classes:h,html:c(h),selectors:d(h)},{css:g.css,html:g.html,classes:g.classes,selectors:g.selectors,mixin:function(a){b.mixin(a,g)}}}function c(a){return{wrapper:'<span class="'+a.wrapper+'"></span>',menu:'<div class="'+a.menu+'"></div>'}}function d(a){var c={};return b.each(a,function(a,b){c[b]="."+a}),c}function e(){var a={wrapper:{position:"relative",display:"inline-block"},hint:{position:"absolute",top:"0",left:"0",borderColor:"transparent",boxShadow:"none",opacity:"1"},input:{position:"relative",verticalAlign:"top",backgroundColor:"transparent"},inputWithNoHint:{position:"relative",verticalAlign:"top"},menu:{position:"absolute",top:"100%",left:"0",zIndex:"100",display:"none"},ltr:{left:"0",right:"auto"},rtl:{left:"auto",right:" 0"}};return b.isMsie()&&b.mixin(a.input,{backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"}),a}var f={wrapper:"twitter-typeahead",input:"tt-input",hint:"tt-hint",menu:"tt-menu",dataset:"tt-dataset",suggestion:"tt-suggestion",selectable:"tt-selectable",empty:"tt-empty",open:"tt-open",cursor:"tt-cursor",highlight:"tt-highlight"};return a}(),d=function(){"use strict";function c(b){b&&b.el||a.error("EventBus initialized without el"),this.$el=a(b.el)}var d,e;return d="typeahead:",e={render:"rendered",cursorchange:"cursorchanged",select:"selected",autocomplete:"autocompleted"},b.mixin(c.prototype,{_trigger:function(b,c){var e;return e=a.Event(d+b),(c=c||[]).unshift(e),this.$el.trigger.apply(this.$el,c),e},before:function(a){var b,c;return b=[].slice.call(arguments,1),c=this._trigger("before"+a,b),c.isDefaultPrevented()},trigger:function(a){var b;this._trigger(a,[].slice.call(arguments,1)),(b=e[a])&&this._trigger(b,[].slice.call(arguments,1))}}),c}(),e=function(){"use strict";function a(a,b,c,d){var e;if(!c)return this;for(b=b.split(i),c=d?h(c,d):c,this._callbacks=this._callbacks||{};e=b.shift();)this._callbacks[e]=this._callbacks[e]||{sync:[],async:[]},this._callbacks[e][a].push(c);return this}function b(b,c,d){return a.call(this,"async",b,c,d)}function c(b,c,d){return a.call(this,"sync",b,c,d)}function d(a){var b;if(!this._callbacks)return this;for(a=a.split(i);b=a.shift();)delete this._callbacks[b];return this}function e(a){var b,c,d,e,g;if(!this._callbacks)return this;for(a=a.split(i),d=[].slice.call(arguments,1);(b=a.shift())&&(c=this._callbacks[b]);)e=f(c.sync,this,[b].concat(d)),g=f(c.async,this,[b].concat(d)),e()&&j(g);return this}function f(a,b,c){function d(){for(var d,e=0,f=a.length;!d&&f>e;e+=1)d=a[e].apply(b,c)===!1;return!d}return d}function g(){var a;return a=window.setImmediate?function(a){setImmediate(function(){a()})}:function(a){setTimeout(function(){a()},0)}}function h(a,b){return a.bind?a.bind(b):function(){a.apply(b,[].slice.call(arguments,0))}}var i=/\s+/,j=g();return{onSync:c,onAsync:b,off:d,trigger:e}}(),f=function(a){"use strict";function c(a,c,d){for(var e,f=[],g=0,h=a.length;h>g;g++)f.push(b.escapeRegExChars(a[g]));return e=d?"\\b("+f.join("|")+")\\b":"("+f.join("|")+")",c?new RegExp(e):new RegExp(e,"i")}var d={node:null,pattern:null,tagName:"strong",className:null,wordsOnly:!1,caseSensitive:!1};return function(e){function f(b){var c,d,f;return(c=h.exec(b.data))&&(f=a.createElement(e.tagName),e.className&&(f.className=e.className),d=b.splitText(c.index),d.splitText(c[0].length),f.appendChild(d.cloneNode(!0)),b.parentNode.replaceChild(f,d)),!!c}function g(a,b){for(var c,d=3,e=0;e<a.childNodes.length;e++)c=a.childNodes[e],c.nodeType===d?e+=b(c)?1:0:g(c,b)}var h;e=b.mixin({},d,e),e.node&&e.pattern&&(e.pattern=b.isArray(e.pattern)?e.pattern:[e.pattern],h=c(e.pattern,e.caseSensitive,e.wordsOnly),g(e.node,f))}}(window.document),g=function(){"use strict";function c(c,e){c=c||{},c.input||a.error("input is missing"),e.mixin(this),this.$hint=a(c.hint),this.$input=a(c.input),this.query=this.$input.val(),this.queryWhenFocused=this.hasFocus()?this.query:null,this.$overflowHelper=d(this.$input),this._checkLanguageDirection(),0===this.$hint.length&&(this.setHint=this.getHint=this.clearHint=this.clearHintIfInvalid=b.noop)}function d(b){return a('<pre aria-hidden="true"></pre>').css({position:"absolute",visibility:"hidden",whiteSpace:"pre",fontFamily:b.css("font-family"),fontSize:b.css("font-size"),fontStyle:b.css("font-style"),fontVariant:b.css("font-variant"),fontWeight:b.css("font-weight"),wordSpacing:b.css("word-spacing"),letterSpacing:b.css("letter-spacing"),textIndent:b.css("text-indent"),textRendering:b.css("text-rendering"),textTransform:b.css("text-transform")}).insertAfter(b)}function f(a,b){return c.normalizeQuery(a)===c.normalizeQuery(b)}function g(a){return a.altKey||a.ctrlKey||a.metaKey||a.shiftKey}var h;return h={9:"tab",27:"esc",37:"left",39:"right",13:"enter",38:"up",40:"down"},c.normalizeQuery=function(a){return b.toStr(a).replace(/^\s*/g,"").replace(/\s{2,}/g," ")},b.mixin(c.prototype,e,{_onBlur:function(){this.resetInputValue(),this.trigger("blurred")},_onFocus:function(){this.queryWhenFocused=this.query,this.trigger("focused")},_onKeydown:function(a){var b=h[a.which||a.keyCode];this._managePreventDefault(b,a),b&&this._shouldTrigger(b,a)&&this.trigger(b+"Keyed",a)},_onInput:function(){this._setQuery(this.getInputValue()),this.clearHintIfInvalid(),this._checkLanguageDirection()},_managePreventDefault:function(a,b){var c;switch(a){case"up":case"down":c=!g(b);break;default:c=!1}c&&b.preventDefault()},_shouldTrigger:function(a,b){var c;switch(a){case"tab":c=!g(b);break;default:c=!0}return c},_checkLanguageDirection:function(){var a=(this.$input.css("direction")||"ltr").toLowerCase();this.dir!==a&&(this.dir=a,this.$hint.attr("dir",a),this.trigger("langDirChanged",a))},_setQuery:function(a,b){var c,d;c=f(a,this.query),d=c?this.query.length!==a.length:!1,this.query=a,b||c?!b&&d&&this.trigger("whitespaceChanged",this.query):this.trigger("queryChanged",this.query)},bind:function(){var a,c,d,e,f=this;return a=b.bind(this._onBlur,this),c=b.bind(this._onFocus,this),d=b.bind(this._onKeydown,this),e=b.bind(this._onInput,this),this.$input.on("blur.tt",a).on("focus.tt",c).on("keydown.tt",d),!b.isMsie()||b.isMsie()>9?this.$input.on("input.tt",e):this.$input.on("keydown.tt keypress.tt cut.tt paste.tt",function(a){h[a.which||a.keyCode]||b.defer(b.bind(f._onInput,f,a))}),this},focus:function(){this.$input.focus()},blur:function(){this.$input.blur()},getLangDir:function(){return this.dir},getQuery:function(){return this.query||""},setQuery:function(a,b){this.setInputValue(a),this._setQuery(a,b)},hasQueryChangedSinceLastFocus:function(){return this.query!==this.queryWhenFocused},getInputValue:function(){return this.$input.val()},setInputValue:function(a){this.$input.val(a),this.clearHintIfInvalid(),this._checkLanguageDirection()},resetInputValue:function(){this.setInputValue(this.query)},getHint:function(){return this.$hint.val()},setHint:function(a){this.$hint.val(a)},clearHint:function(){this.setHint("")},clearHintIfInvalid:function(){var a,b,c,d;a=this.getInputValue(),b=this.getHint(),c=a!==b&&0===b.indexOf(a),d=""!==a&&c&&!this.hasOverflow(),!d&&this.clearHint()},hasFocus:function(){return this.$input.is(":focus")},hasOverflow:function(){var a=this.$input.width()-2;return this.$overflowHelper.text(this.getInputValue()),this.$overflowHelper.width()>=a},isCursorAtEnd:function(){var a,c,d;return a=this.$input.val().length,c=this.$input[0].selectionStart,b.isNumber(c)?c===a:document.selection?(d=document.selection.createRange(),d.moveStart("character",-a),a===d.text.length):!0},destroy:function(){this.$hint.off(".tt"),this.$input.off(".tt"),this.$overflowHelper.remove(),this.$hint=this.$input=this.$overflowHelper=a("<div>")}}),c}(),h=function(){"use strict";function c(c,e){c=c||{},c.templates=c.templates||{},c.templates.notFound=c.templates.notFound||c.templates.empty,c.source||a.error("missing source"),c.node||a.error("missing node"),c.name&&!h(c.name)&&a.error("invalid dataset name: "+c.name),e.mixin(this),this.highlight=!!c.highlight,this.name=c.name||j(),this.limit=c.limit||5,this.displayFn=d(c.display||c.displayKey),this.templates=g(c.templates,this.displayFn),this.source=c.source.__ttAdapter?c.source.__ttAdapter():c.source,this.async=b.isUndefined(c.async)?this.source.length>2:!!c.async,this._resetLastSuggestion(),this.$el=a(c.node).addClass(this.classes.dataset).addClass(this.classes.dataset+"-"+this.name)}function d(a){function c(b){return b[a]}return a=a||b.stringify,b.isFunction(a)?a:c}function g(c,d){function e(b){return a("<div>").text(d(b))}return{notFound:c.notFound&&b.templatify(c.notFound),pending:c.pending&&b.templatify(c.pending),header:c.header&&b.templatify(c.header),footer:c.footer&&b.templatify(c.footer),suggestion:c.suggestion||e}}function h(a){return/^[_a-zA-Z0-9-]+$/.test(a)}var i,j;return i={val:"tt-selectable-display",obj:"tt-selectable-object"},j=b.getIdGenerator(),c.extractData=function(b){var c=a(b);return c.data(i.obj)?{val:c.data(i.val)||"",obj:c.data(i.obj)||null}:null},b.mixin(c.prototype,e,{_overwrite:function(a,b){b=b||[],b.length?this._renderSuggestions(a,b):this.async&&this.templates.pending?this._renderPending(a):!this.async&&this.templates.notFound?this._renderNotFound(a):this._empty(),this.trigger("rendered",this.name,b,!1)},_append:function(a,b){b=b||[],b.length&&this.$lastSuggestion.length?this._appendSuggestions(a,b):b.length?this._renderSuggestions(a,b):!this.$lastSuggestion.length&&this.templates.notFound&&this._renderNotFound(a),this.trigger("rendered",this.name,b,!0)},_renderSuggestions:function(a,b){var c;c=this._getSuggestionsFragment(a,b),this.$lastSuggestion=c.children().last(),this.$el.html(c).prepend(this._getHeader(a,b)).append(this._getFooter(a,b))},_appendSuggestions:function(a,b){var c,d;c=this._getSuggestionsFragment(a,b),d=c.children().last(),this.$lastSuggestion.after(c),this.$lastSuggestion=d},_renderPending:function(a){var b=this.templates.pending;this._resetLastSuggestion(),b&&this.$el.html(b({query:a,dataset:this.name}))},_renderNotFound:function(a){var b=this.templates.notFound;this._resetLastSuggestion(),b&&this.$el.html(b({query:a,dataset:this.name}))},_empty:function(){this.$el.empty(),this._resetLastSuggestion()},_getSuggestionsFragment:function(c,d){var e,g=this;return e=document.createDocumentFragment(),b.each(d,function(b){var d,f;f=g._injectQuery(c,b),d=a(g.templates.suggestion(f)).data(i.obj,b).data(i.val,g.displayFn(b)).addClass(g.classes.suggestion+" "+g.classes.selectable),e.appendChild(d[0])}),this.highlight&&f({className:this.classes.highlight,node:e,pattern:c}),a(e)},_getFooter:function(a,b){return this.templates.footer?this.templates.footer({query:a,suggestions:b,dataset:this.name}):null},_getHeader:function(a,b){return this.templates.header?this.templates.header({query:a,suggestions:b,dataset:this.name}):null},_resetLastSuggestion:function(){this.$lastSuggestion=a()},_injectQuery:function(a,c){return b.isObject(c)?b.mixin({_query:a},c):c},update:function(b){function c(a){g||(g=!0,a=(a||[]).slice(0,e.limit),h=a.length,e._overwrite(b,a),h<e.limit&&e.async&&e.trigger("asyncRequested",b))}function d(c){c=c||[],!f&&h<e.limit&&(e.cancel=a.noop,e._append(b,c.slice(0,e.limit-h)),h+=c.length,e.async&&e.trigger("asyncReceived",b))}var e=this,f=!1,g=!1,h=0;this.cancel(),this.cancel=function(){f=!0,e.cancel=a.noop,e.async&&e.trigger("asyncCanceled",b)},this.source(b,c,d),!g&&c([])},cancel:a.noop,clear:function(){this._empty(),this.cancel(),this.trigger("cleared")},isEmpty:function(){return this.$el.is(":empty")},destroy:function(){this.$el=a("<div>")}}),c}(),i=function(){"use strict";function c(c,d){function e(b){var c=f.$node.find(b.node).first();return b.node=c.length?c:a("<div>").appendTo(f.$node),new h(b,d)}var f=this;c=c||{},c.node||a.error("node is required"),d.mixin(this),this.$node=a(c.node),this.query=null,this.datasets=b.map(c.datasets,e)}return b.mixin(c.prototype,e,{_onSelectableClick:function(b){this.trigger("selectableClicked",a(b.currentTarget))},_onRendered:function(a,b,c,d){this.$node.toggleClass(this.classes.empty,this._allDatasetsEmpty()),this.trigger("datasetRendered",b,c,d)},_onCleared:function(){this.$node.toggleClass(this.classes.empty,this._allDatasetsEmpty()),this.trigger("datasetCleared")},_propagate:function(){this.trigger.apply(this,arguments)},_allDatasetsEmpty:function(){function a(a){return a.isEmpty()}return b.every(this.datasets,a)},_getSelectables:function(){return this.$node.find(this.selectors.selectable)},_removeCursor:function(){var a=this.getActiveSelectable();a&&a.removeClass(this.classes.cursor)},_ensureVisible:function(a){var b,c,d,e;b=a.position().top,c=b+a.outerHeight(!0),d=this.$node.scrollTop(),e=this.$node.height()+parseInt(this.$node.css("paddingTop"),10)+parseInt(this.$node.css("paddingBottom"),10),0>b?this.$node.scrollTop(d+b):c>e&&this.$node.scrollTop(d+(c-e))},bind:function(){var a,c=this;return a=b.bind(this._onSelectableClick,this),this.$node.on("click.tt",this.selectors.selectable,a),b.each(this.datasets,function(a){a.onSync("asyncRequested",c._propagate,c).onSync("asyncCanceled",c._propagate,c).onSync("asyncReceived",c._propagate,c).onSync("rendered",c._onRendered,c).onSync("cleared",c._onCleared,c)}),this},isOpen:function(){return this.$node.hasClass(this.classes.open)},open:function(){this.$node.scrollTop(0),this.$node.addClass(this.classes.open)},close:function(){this.$node.removeClass(this.classes.open),this._removeCursor()},setLanguageDirection:function(a){this.$node.attr("dir",a)},selectableRelativeToCursor:function(a){var b,c,d,e;return c=this.getActiveSelectable(),b=this._getSelectables(),d=c?b.index(c):-1,e=d+a,e=(e+1)%(b.length+1)-1,e=-1>e?b.length-1:e,-1===e?null:b.eq(e)},setCursor:function(a){this._removeCursor(),(a=a&&a.first())&&(a.addClass(this.classes.cursor),this._ensureVisible(a))},getSelectableData:function(a){return a&&a.length?h.extractData(a):null},getActiveSelectable:function(){var a=this._getSelectables().filter(this.selectors.cursor).first();return a.length?a:null},getTopSelectable:function(){var a=this._getSelectables().first();return a.length?a:null},update:function(a){function c(b){b.update(a)}var d=a!==this.query;return d&&(this.query=a,b.each(this.datasets,c)),d},empty:function(){function a(a){a.clear()}b.each(this.datasets,a),this.query=null,this.$node.addClass(this.classes.empty)},destroy:function(){function c(a){a.destroy()}this.$node.off(".tt"),this.$node=a("<div>"),b.each(this.datasets,c)}}),c}(),j=function(){"use strict";function a(){i.apply(this,[].slice.call(arguments,0))}var c=i.prototype;return b.mixin(a.prototype,i.prototype,{open:function(){return!this._allDatasetsEmpty()&&this._show(),c.open.apply(this,[].slice.call(arguments,0))},close:function(){return this._hide(),c.close.apply(this,[].slice.call(arguments,0))},_onRendered:function(){return this._allDatasetsEmpty()?this._hide():this.isOpen()&&this._show(),c._onRendered.apply(this,[].slice.call(arguments,0))},_onCleared:function(){return this._allDatasetsEmpty()?this._hide():this.isOpen()&&this._show(),c._onCleared.apply(this,[].slice.call(arguments,0))},setLanguageDirection:function(a){return this.$node.css("ltr"===a?this.css.ltr:this.css.rtl),c.setLanguageDirection.apply(this,[].slice.call(arguments,0))},_hide:function(){this.$node.hide()},_show:function(){this.$node.css("display","block")}}),a}(),k=function(){"use strict";function c(c,e){var f,g,h,i,j,k,l,m,n,o,p;c=c||{},c.input||a.error("missing input"),c.menu||a.error("missing menu"),c.eventBus||a.error("missing event bus"),e.mixin(this),this.eventBus=c.eventBus,this.minLength=b.isNumber(c.minLength)?c.minLength:1,this.input=c.input,this.menu=c.menu,this.enabled=!0,this.active=!1,this.input.hasFocus()&&this.activate(),this.dir=this.input.getLangDir(),this._hacks(),this.menu.bind().onSync("selectableClicked",this._onSelectableClicked,this).onSync("asyncRequested",this._onAsyncRequested,this).onSync("asyncCanceled",this._onAsyncCanceled,this).onSync("asyncReceived",this._onAsyncReceived,this).onSync("datasetRendered",this._onDatasetRendered,this).onSync("datasetCleared",this._onDatasetCleared,this),f=d(this,"activate","open","_onFocused"),g=d(this,"deactivate","_onBlurred"),h=d(this,"isActive","isOpen","_onEnterKeyed"),i=d(this,"isActive","isOpen","_onTabKeyed"),j=d(this,"isActive","_onEscKeyed"),k=d(this,"isActive","open","_onUpKeyed"),l=d(this,"isActive","open","_onDownKeyed"),m=d(this,"isActive","isOpen","_onLeftKeyed"),n=d(this,"isActive","isOpen","_onRightKeyed"),o=d(this,"_openIfActive","_onQueryChanged"),p=d(this,"_openIfActive","_onWhitespaceChanged"),this.input.bind().onSync("focused",f,this).onSync("blurred",g,this).onSync("enterKeyed",h,this).onSync("tabKeyed",i,this).onSync("escKeyed",j,this).onSync("upKeyed",k,this).onSync("downKeyed",l,this).onSync("leftKeyed",m,this).onSync("rightKeyed",n,this).onSync("queryChanged",o,this).onSync("whitespaceChanged",p,this).onSync("langDirChanged",this._onLangDirChanged,this);
8
+ }function d(a){var c=[].slice.call(arguments,1);return function(){var d=[].slice.call(arguments);b.each(c,function(b){return a[b].apply(a,d)})}}return b.mixin(c.prototype,{_hacks:function(){var c,d;c=this.input.$input||a("<div>"),d=this.menu.$node||a("<div>"),c.on("blur.tt",function(a){var e,f,g;e=document.activeElement,f=d.is(e),g=d.has(e).length>0,b.isMsie()&&(f||g)&&(a.preventDefault(),a.stopImmediatePropagation(),b.defer(function(){c.focus()}))}),d.on("mousedown.tt",function(a){a.preventDefault()})},_onSelectableClicked:function(a,b){this.select(b)},_onDatasetCleared:function(){this._updateHint()},_onDatasetRendered:function(a,b,c,d){this._updateHint(),this.eventBus.trigger("render",c,d,b)},_onAsyncRequested:function(a,b,c){this.eventBus.trigger("asyncrequest",c,b)},_onAsyncCanceled:function(a,b,c){this.eventBus.trigger("asynccancel",c,b)},_onAsyncReceived:function(a,b,c){this.eventBus.trigger("asyncreceive",c,b)},_onFocused:function(){this._minLengthMet()&&this.menu.update(this.input.getQuery())},_onBlurred:function(){this.input.hasQueryChangedSinceLastFocus()&&this.eventBus.trigger("change",this.input.getQuery())},_onEnterKeyed:function(a,b){var c;(c=this.menu.getActiveSelectable())&&this.select(c)&&b.preventDefault()},_onTabKeyed:function(a,b){var c;(c=this.menu.getActiveSelectable())?this.select(c)&&b.preventDefault():(c=this.menu.getTopSelectable())&&this.autocomplete(c)&&b.preventDefault()},_onEscKeyed:function(){this.close()},_onUpKeyed:function(){this.moveCursor(-1)},_onDownKeyed:function(){this.moveCursor(1)},_onLeftKeyed:function(){"rtl"===this.dir&&this.input.isCursorAtEnd()&&this.autocomplete(this.menu.getTopSelectable())},_onRightKeyed:function(){"ltr"===this.dir&&this.input.isCursorAtEnd()&&this.autocomplete(this.menu.getTopSelectable())},_onQueryChanged:function(a,b){this._minLengthMet(b)?this.menu.update(b):this.menu.empty()},_onWhitespaceChanged:function(){this._updateHint()},_onLangDirChanged:function(a,b){this.dir!==b&&(this.dir=b,this.menu.setLanguageDirection(b))},_openIfActive:function(){this.isActive()&&this.open()},_minLengthMet:function(a){return a=b.isString(a)?a:this.input.getQuery()||"",a.length>=this.minLength},_updateHint:function(){var a,c,d,e,f,h,i;a=this.menu.getTopSelectable(),c=this.menu.getSelectableData(a),d=this.input.getInputValue(),!c||b.isBlankString(d)||this.input.hasOverflow()?this.input.clearHint():(e=g.normalizeQuery(d),f=b.escapeRegExChars(e),h=new RegExp("^(?:"+f+")(.+$)","i"),i=h.exec(c.val),i&&this.input.setHint(d+i[1]))},isEnabled:function(){return this.enabled},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},isActive:function(){return this.active},activate:function(){return this.isActive()?!0:!this.isEnabled()||this.eventBus.before("active")?!1:(this.active=!0,this.eventBus.trigger("active"),!0)},deactivate:function(){return this.isActive()?this.eventBus.before("idle")?!1:(this.active=!1,this.close(),this.eventBus.trigger("idle"),!0):!0},isOpen:function(){return this.menu.isOpen()},open:function(){return this.isOpen()||this.eventBus.before("open")||(this.menu.open(),this._updateHint(),this.eventBus.trigger("open")),this.isOpen()},close:function(){return this.isOpen()&&!this.eventBus.before("close")&&(this.menu.close(),this.input.clearHint(),this.input.resetInputValue(),this.eventBus.trigger("close")),!this.isOpen()},setVal:function(a){this.input.setQuery(b.toStr(a))},getVal:function(){return this.input.getQuery()},select:function(a){var b=this.menu.getSelectableData(a);return b&&!this.eventBus.before("select",b.obj)?(this.input.setQuery(b.val,!0),this.eventBus.trigger("select",b.obj),this.close(),!0):!1},autocomplete:function(a){var b,c,d;return b=this.input.getQuery(),c=this.menu.getSelectableData(a),d=c&&b!==c.val,d&&!this.eventBus.before("autocomplete",c.obj)?(this.input.setQuery(c.val),this.eventBus.trigger("autocomplete",c.obj),!0):!1},moveCursor:function(a){var b,c,d,e,f;return b=this.input.getQuery(),c=this.menu.selectableRelativeToCursor(a),d=this.menu.getSelectableData(c),e=d?d.obj:null,f=this._minLengthMet()&&this.menu.update(b),f||this.eventBus.before("cursorchange",e)?!1:(this.menu.setCursor(c),d?this.input.setInputValue(d.val):(this.input.resetInputValue(),this._updateHint()),this.eventBus.trigger("cursorchange",e),!0)},destroy:function(){this.input.destroy(),this.menu.destroy()}}),c}();!function(){"use strict";function e(b,c){b.each(function(){var b,d=a(this);(b=d.data(p.typeahead))&&c(b,d)})}function f(a,b){return a.clone().addClass(b.classes.hint).removeData().css(b.css.hint).css(l(a)).prop("readonly",!0).removeAttr("id name placeholder required").attr({autocomplete:"off",spellcheck:"false",tabindex:-1})}function h(a,b){a.data(p.attrs,{dir:a.attr("dir"),autocomplete:a.attr("autocomplete"),spellcheck:a.attr("spellcheck"),style:a.attr("style")}),a.addClass(b.classes.input).attr({autocomplete:"off",spellcheck:!1});try{!a.attr("dir")&&a.attr("dir","auto")}catch(c){}return a}function l(a){return{backgroundAttachment:a.css("background-attachment"),backgroundClip:a.css("background-clip"),backgroundColor:a.css("background-color"),backgroundImage:a.css("background-image"),backgroundOrigin:a.css("background-origin"),backgroundPosition:a.css("background-position"),backgroundRepeat:a.css("background-repeat"),backgroundSize:a.css("background-size")}}function m(a){var c,d;c=a.data(p.www),d=a.parent().filter(c.selectors.wrapper),b.each(a.data(p.attrs),function(c,d){b.isUndefined(c)?a.removeAttr(d):a.attr(d,c)}),a.removeData(p.typeahead).removeData(p.www).removeData(p.attr).removeClass(c.classes.input),d.length&&(a.detach().insertAfter(d),d.remove())}function n(c){var d,e;return d=b.isJQuery(c)||b.isElement(c),e=d?a(c).first():[],e.length?e:null}var o,p,q;o=a.fn.typeahead,p={www:"tt-www",attrs:"tt-attrs",typeahead:"tt-typeahead"},q={initialize:function(e,l){function m(){var c,m,q,r,s,t,u,v,w,x,y;b.each(l,function(a){a.highlight=!!e.highlight}),c=a(this),m=a(o.html.wrapper),q=n(e.hint),r=n(e.menu),s=e.hint!==!1&&!q,t=e.menu!==!1&&!r,s&&(q=f(c,o)),t&&(r=a(o.html.menu).css(o.css.menu)),q&&q.val(""),c=h(c,o),(s||t)&&(m.css(o.css.wrapper),c.css(s?o.css.input:o.css.inputWithNoHint),c.wrap(m).parent().prepend(s?q:null).append(t?r:null)),y=t?j:i,u=new d({el:c}),v=new g({hint:q,input:c},o),w=new y({node:r,datasets:l},o),x=new k({input:v,menu:w,eventBus:u,minLength:e.minLength},o),c.data(p.www,o),c.data(p.typeahead,x)}var o;return l=b.isArray(l)?l:[].slice.call(arguments,1),e=e||{},o=c(e.classNames),this.each(m)},isEnabled:function(){var a;return e(this.first(),function(b){a=b.isEnabled()}),a},enable:function(){return e(this,function(a){a.enable()}),this},disable:function(){return e(this,function(a){a.disable()}),this},isActive:function(){var a;return e(this.first(),function(b){a=b.isActive()}),a},activate:function(){return e(this,function(a){a.activate()}),this},deactivate:function(){return e(this,function(a){a.deactivate()}),this},isOpen:function(){var a;return e(this.first(),function(b){a=b.isOpen()}),a},open:function(){return e(this,function(a){a.open()}),this},close:function(){return e(this,function(a){a.close()}),this},select:function(b){var c=!1,d=a(b);return e(this.first(),function(a){c=a.select(d)}),c},autocomplete:function(b){var c=!1,d=a(b);return e(this.first(),function(a){c=a.autocomplete(d)}),c},moveCursor:function(a){var b=!1;return e(this.first(),function(c){b=c.moveCursor(a)}),b},val:function(a){var c;return arguments.length?(e(this,function(c){c.setVal(b.toStr(a))}),this):(e(this.first(),function(a){c=a.getVal()}),c)},destroy:function(){return e(this,function(a,b){m(b),a.destroy()}),this}},a.fn.typeahead=function(a){return q[a]?q[a].apply(this,[].slice.call(arguments,1)):q.initialize.apply(this,arguments)},a.fn.typeahead.noConflict=function(){return a.fn.typeahead=o,this}}()});
@@ -1,10 +1,20 @@
1
1
  /*!
2
- * typeahead.js 0.10.5
2
+ * typeahead.js 0.11.1
3
3
  * https://github.com/twitter/typeahead.js
4
- * Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
4
+ * Copyright 2013-2015 Twitter, Inc. and other contributors; Licensed MIT
5
5
  */
6
6
 
7
- (function($) {
7
+ (function(root, factory) {
8
+ if (typeof define === "function" && define.amd) {
9
+ define([ "jquery" ], function(a0) {
10
+ return factory(a0);
11
+ });
12
+ } else if (typeof exports === "object") {
13
+ module.exports = factory(require("jquery"));
14
+ } else {
15
+ factory(jQuery);
16
+ }
17
+ })(this, function($) {
8
18
  var _ = function() {
9
19
  "use strict";
10
20
  return {
@@ -29,6 +39,12 @@
29
39
  isUndefined: function(obj) {
30
40
  return typeof obj === "undefined";
31
41
  },
42
+ isElement: function(obj) {
43
+ return !!(obj && obj.nodeType === 1);
44
+ },
45
+ isJQuery: function(obj) {
46
+ return obj instanceof $;
47
+ },
32
48
  toStr: function toStr(s) {
33
49
  return _.isUndefined(s) || s === null ? "" : s + "";
34
50
  },
@@ -66,12 +82,18 @@
66
82
  return !!result;
67
83
  },
68
84
  mixin: $.extend,
69
- getUniqueId: function() {
85
+ identity: function(x) {
86
+ return x;
87
+ },
88
+ clone: function(obj) {
89
+ return $.extend(true, {}, obj);
90
+ },
91
+ getIdGenerator: function() {
70
92
  var counter = 0;
71
93
  return function() {
72
94
  return counter++;
73
95
  };
74
- }(),
96
+ },
75
97
  templatify: function templatify(obj) {
76
98
  return $.isFunction(obj) ? obj : template;
77
99
  function template() {
@@ -123,83 +145,117 @@
123
145
  return result;
124
146
  };
125
147
  },
148
+ stringify: function(val) {
149
+ return _.isString(val) ? val : JSON.stringify(val);
150
+ },
126
151
  noop: function() {}
127
152
  };
128
153
  }();
129
- var html = function() {
130
- return {
131
- wrapper: '<span class="twitter-typeahead"></span>',
132
- dropdown: '<span class="tt-dropdown-menu"></span>',
133
- dataset: '<div class="tt-dataset-%CLASS%"></div>',
134
- suggestions: '<span class="tt-suggestions"></span>',
135
- suggestion: '<div class="tt-suggestion"></div>'
136
- };
137
- }();
138
- var css = function() {
154
+ var WWW = function() {
139
155
  "use strict";
140
- var css = {
141
- wrapper: {
142
- position: "relative",
143
- display: "inline-block"
144
- },
145
- hint: {
146
- position: "absolute",
147
- top: "0",
148
- left: "0",
149
- borderColor: "transparent",
150
- boxShadow: "none",
151
- opacity: "1"
152
- },
153
- input: {
154
- position: "relative",
155
- verticalAlign: "top",
156
- backgroundColor: "transparent"
157
- },
158
- inputWithNoHint: {
159
- position: "relative",
160
- verticalAlign: "top"
161
- },
162
- dropdown: {
163
- position: "absolute",
164
- top: "100%",
165
- left: "0",
166
- zIndex: "100",
167
- display: "none"
168
- },
169
- suggestions: {
170
- display: "block"
171
- },
172
- suggestion: {
173
- whiteSpace: "nowrap",
174
- cursor: "pointer"
175
- },
176
- suggestionChild: {
177
- whiteSpace: "normal"
178
- },
179
- ltr: {
180
- left: "0",
181
- right: "auto"
182
- },
183
- rtl: {
184
- left: "auto",
185
- right: " 0"
186
- }
156
+ var defaultClassNames = {
157
+ wrapper: "twitter-typeahead",
158
+ input: "tt-input",
159
+ hint: "tt-hint",
160
+ menu: "tt-menu",
161
+ dataset: "tt-dataset",
162
+ suggestion: "tt-suggestion",
163
+ selectable: "tt-selectable",
164
+ empty: "tt-empty",
165
+ open: "tt-open",
166
+ cursor: "tt-cursor",
167
+ highlight: "tt-highlight"
187
168
  };
188
- if (_.isMsie()) {
189
- _.mixin(css.input, {
190
- backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
191
- });
169
+ return build;
170
+ function build(o) {
171
+ var www, classes;
172
+ classes = _.mixin({}, defaultClassNames, o);
173
+ www = {
174
+ css: buildCss(),
175
+ classes: classes,
176
+ html: buildHtml(classes),
177
+ selectors: buildSelectors(classes)
178
+ };
179
+ return {
180
+ css: www.css,
181
+ html: www.html,
182
+ classes: www.classes,
183
+ selectors: www.selectors,
184
+ mixin: function(o) {
185
+ _.mixin(o, www);
186
+ }
187
+ };
188
+ }
189
+ function buildHtml(c) {
190
+ return {
191
+ wrapper: '<span class="' + c.wrapper + '"></span>',
192
+ menu: '<div class="' + c.menu + '"></div>'
193
+ };
192
194
  }
193
- if (_.isMsie() && _.isMsie() <= 7) {
194
- _.mixin(css.input, {
195
- marginTop: "-1px"
195
+ function buildSelectors(classes) {
196
+ var selectors = {};
197
+ _.each(classes, function(v, k) {
198
+ selectors[k] = "." + v;
196
199
  });
200
+ return selectors;
201
+ }
202
+ function buildCss() {
203
+ var css = {
204
+ wrapper: {
205
+ position: "relative",
206
+ display: "inline-block"
207
+ },
208
+ hint: {
209
+ position: "absolute",
210
+ top: "0",
211
+ left: "0",
212
+ borderColor: "transparent",
213
+ boxShadow: "none",
214
+ opacity: "1"
215
+ },
216
+ input: {
217
+ position: "relative",
218
+ verticalAlign: "top",
219
+ backgroundColor: "transparent"
220
+ },
221
+ inputWithNoHint: {
222
+ position: "relative",
223
+ verticalAlign: "top"
224
+ },
225
+ menu: {
226
+ position: "absolute",
227
+ top: "100%",
228
+ left: "0",
229
+ zIndex: "100",
230
+ display: "none"
231
+ },
232
+ ltr: {
233
+ left: "0",
234
+ right: "auto"
235
+ },
236
+ rtl: {
237
+ left: "auto",
238
+ right: " 0"
239
+ }
240
+ };
241
+ if (_.isMsie()) {
242
+ _.mixin(css.input, {
243
+ backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
244
+ });
245
+ }
246
+ return css;
197
247
  }
198
- return css;
199
248
  }();
200
249
  var EventBus = function() {
201
250
  "use strict";
202
- var namespace = "typeahead:";
251
+ var namespace, deprecationMap;
252
+ namespace = "typeahead:";
253
+ deprecationMap = {
254
+ render: "rendered",
255
+ cursorchange: "cursorchanged",
256
+ select: "selected",
257
+ autocomplete: "autocompleted"
258
+ };
203
259
  function EventBus(o) {
204
260
  if (!o || !o.el) {
205
261
  $.error("EventBus initialized without el");
@@ -207,9 +263,25 @@
207
263
  this.$el = $(o.el);
208
264
  }
209
265
  _.mixin(EventBus.prototype, {
266
+ _trigger: function(type, args) {
267
+ var $e;
268
+ $e = $.Event(namespace + type);
269
+ (args = args || []).unshift($e);
270
+ this.$el.trigger.apply(this.$el, args);
271
+ return $e;
272
+ },
273
+ before: function(type) {
274
+ var args, $e;
275
+ args = [].slice.call(arguments, 1);
276
+ $e = this._trigger("before" + type, args);
277
+ return $e.isDefaultPrevented();
278
+ },
210
279
  trigger: function(type) {
211
- var args = [].slice.call(arguments, 1);
212
- this.$el.trigger(namespace + type, args);
280
+ var deprecatedType;
281
+ this._trigger(type, [].slice.call(arguments, 1));
282
+ if (deprecatedType = deprecationMap[type]) {
283
+ this._trigger(deprecatedType, [].slice.call(arguments, 1));
284
+ }
213
285
  }
214
286
  });
215
287
  return EventBus;
@@ -368,36 +440,24 @@
368
440
  38: "up",
369
441
  40: "down"
370
442
  };
371
- function Input(o) {
372
- var that = this, onBlur, onFocus, onKeydown, onInput;
443
+ function Input(o, www) {
373
444
  o = o || {};
374
445
  if (!o.input) {
375
446
  $.error("input is missing");
376
447
  }
377
- onBlur = _.bind(this._onBlur, this);
378
- onFocus = _.bind(this._onFocus, this);
379
- onKeydown = _.bind(this._onKeydown, this);
380
- onInput = _.bind(this._onInput, this);
448
+ www.mixin(this);
381
449
  this.$hint = $(o.hint);
382
- this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
450
+ this.$input = $(o.input);
451
+ this.query = this.$input.val();
452
+ this.queryWhenFocused = this.hasFocus() ? this.query : null;
453
+ this.$overflowHelper = buildOverflowHelper(this.$input);
454
+ this._checkLanguageDirection();
383
455
  if (this.$hint.length === 0) {
384
456
  this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
385
457
  }
386
- if (!_.isMsie()) {
387
- this.$input.on("input.tt", onInput);
388
- } else {
389
- this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
390
- if (specialKeyCodeMap[$e.which || $e.keyCode]) {
391
- return;
392
- }
393
- _.defer(_.bind(that._onInput, that, $e));
394
- });
395
- }
396
- this.query = this.$input.val();
397
- this.$overflowHelper = buildOverflowHelper(this.$input);
398
458
  }
399
459
  Input.normalizeQuery = function(str) {
400
- return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
460
+ return _.toStr(str).replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
401
461
  };
402
462
  _.mixin(Input.prototype, EventEmitter, {
403
463
  _onBlur: function onBlur() {
@@ -405,6 +465,7 @@
405
465
  this.trigger("blurred");
406
466
  },
407
467
  _onFocus: function onFocus() {
468
+ this.queryWhenFocused = this.query;
408
469
  this.trigger("focused");
409
470
  },
410
471
  _onKeydown: function onKeydown($e) {
@@ -415,17 +476,13 @@
415
476
  }
416
477
  },
417
478
  _onInput: function onInput() {
418
- this._checkInputValue();
479
+ this._setQuery(this.getInputValue());
480
+ this.clearHintIfInvalid();
481
+ this._checkLanguageDirection();
419
482
  },
420
483
  _managePreventDefault: function managePreventDefault(keyName, $e) {
421
- var preventDefault, hintValue, inputValue;
484
+ var preventDefault;
422
485
  switch (keyName) {
423
- case "tab":
424
- hintValue = this.getHint();
425
- inputValue = this.getInputValue();
426
- preventDefault = hintValue && hintValue !== inputValue && !withModifier($e);
427
- break;
428
-
429
486
  case "up":
430
487
  case "down":
431
488
  preventDefault = !withModifier($e);
@@ -448,39 +505,73 @@
448
505
  }
449
506
  return trigger;
450
507
  },
451
- _checkInputValue: function checkInputValue() {
452
- var inputValue, areEquivalent, hasDifferentWhitespace;
453
- inputValue = this.getInputValue();
454
- areEquivalent = areQueriesEquivalent(inputValue, this.query);
455
- hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false;
456
- this.query = inputValue;
457
- if (!areEquivalent) {
508
+ _checkLanguageDirection: function checkLanguageDirection() {
509
+ var dir = (this.$input.css("direction") || "ltr").toLowerCase();
510
+ if (this.dir !== dir) {
511
+ this.dir = dir;
512
+ this.$hint.attr("dir", dir);
513
+ this.trigger("langDirChanged", dir);
514
+ }
515
+ },
516
+ _setQuery: function setQuery(val, silent) {
517
+ var areEquivalent, hasDifferentWhitespace;
518
+ areEquivalent = areQueriesEquivalent(val, this.query);
519
+ hasDifferentWhitespace = areEquivalent ? this.query.length !== val.length : false;
520
+ this.query = val;
521
+ if (!silent && !areEquivalent) {
458
522
  this.trigger("queryChanged", this.query);
459
- } else if (hasDifferentWhitespace) {
523
+ } else if (!silent && hasDifferentWhitespace) {
460
524
  this.trigger("whitespaceChanged", this.query);
461
525
  }
462
526
  },
527
+ bind: function() {
528
+ var that = this, onBlur, onFocus, onKeydown, onInput;
529
+ onBlur = _.bind(this._onBlur, this);
530
+ onFocus = _.bind(this._onFocus, this);
531
+ onKeydown = _.bind(this._onKeydown, this);
532
+ onInput = _.bind(this._onInput, this);
533
+ this.$input.on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
534
+ if (!_.isMsie() || _.isMsie() > 9) {
535
+ this.$input.on("input.tt", onInput);
536
+ } else {
537
+ this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
538
+ if (specialKeyCodeMap[$e.which || $e.keyCode]) {
539
+ return;
540
+ }
541
+ _.defer(_.bind(that._onInput, that, $e));
542
+ });
543
+ }
544
+ return this;
545
+ },
463
546
  focus: function focus() {
464
547
  this.$input.focus();
465
548
  },
466
549
  blur: function blur() {
467
550
  this.$input.blur();
468
551
  },
552
+ getLangDir: function getLangDir() {
553
+ return this.dir;
554
+ },
469
555
  getQuery: function getQuery() {
470
- return this.query;
556
+ return this.query || "";
557
+ },
558
+ setQuery: function setQuery(val, silent) {
559
+ this.setInputValue(val);
560
+ this._setQuery(val, silent);
471
561
  },
472
- setQuery: function setQuery(query) {
473
- this.query = query;
562
+ hasQueryChangedSinceLastFocus: function hasQueryChangedSinceLastFocus() {
563
+ return this.query !== this.queryWhenFocused;
474
564
  },
475
565
  getInputValue: function getInputValue() {
476
566
  return this.$input.val();
477
567
  },
478
- setInputValue: function setInputValue(value, silent) {
568
+ setInputValue: function setInputValue(value) {
479
569
  this.$input.val(value);
480
- silent ? this.clearHint() : this._checkInputValue();
570
+ this.clearHintIfInvalid();
571
+ this._checkLanguageDirection();
481
572
  },
482
573
  resetInputValue: function resetInputValue() {
483
- this.setInputValue(this.query, true);
574
+ this.setInputValue(this.query);
484
575
  },
485
576
  getHint: function getHint() {
486
577
  return this.$hint.val();
@@ -499,8 +590,8 @@
499
590
  isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
500
591
  !isValid && this.clearHint();
501
592
  },
502
- getLanguageDirection: function getLanguageDirection() {
503
- return (this.$input.css("direction") || "ltr").toLowerCase();
593
+ hasFocus: function hasFocus() {
594
+ return this.$input.is(":focus");
504
595
  },
505
596
  hasOverflow: function hasOverflow() {
506
597
  var constraint = this.$input.width() - 2;
@@ -523,7 +614,8 @@
523
614
  destroy: function destroy() {
524
615
  this.$hint.off(".tt");
525
616
  this.$input.off(".tt");
526
- this.$hint = this.$input = this.$overflowHelper = null;
617
+ this.$overflowHelper.remove();
618
+ this.$hint = this.$input = this.$overflowHelper = $("<div>");
527
619
  }
528
620
  });
529
621
  return Input;
@@ -553,118 +645,190 @@
553
645
  }();
554
646
  var Dataset = function() {
555
647
  "use strict";
556
- var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum";
557
- function Dataset(o) {
648
+ var keys, nameGenerator;
649
+ keys = {
650
+ val: "tt-selectable-display",
651
+ obj: "tt-selectable-object"
652
+ };
653
+ nameGenerator = _.getIdGenerator();
654
+ function Dataset(o, www) {
558
655
  o = o || {};
559
656
  o.templates = o.templates || {};
657
+ o.templates.notFound = o.templates.notFound || o.templates.empty;
560
658
  if (!o.source) {
561
659
  $.error("missing source");
562
660
  }
661
+ if (!o.node) {
662
+ $.error("missing node");
663
+ }
563
664
  if (o.name && !isValidName(o.name)) {
564
665
  $.error("invalid dataset name: " + o.name);
565
666
  }
566
- this.query = null;
667
+ www.mixin(this);
567
668
  this.highlight = !!o.highlight;
568
- this.name = o.name || _.getUniqueId();
569
- this.source = o.source;
669
+ this.name = o.name || nameGenerator();
670
+ this.limit = o.limit || 5;
570
671
  this.displayFn = getDisplayFn(o.display || o.displayKey);
571
672
  this.templates = getTemplates(o.templates, this.displayFn);
572
- this.$el = $(html.dataset.replace("%CLASS%", this.name));
673
+ this.source = o.source.__ttAdapter ? o.source.__ttAdapter() : o.source;
674
+ this.async = _.isUndefined(o.async) ? this.source.length > 2 : !!o.async;
675
+ this._resetLastSuggestion();
676
+ this.$el = $(o.node).addClass(this.classes.dataset).addClass(this.classes.dataset + "-" + this.name);
573
677
  }
574
- Dataset.extractDatasetName = function extractDatasetName(el) {
575
- return $(el).data(datasetKey);
576
- };
577
- Dataset.extractValue = function extractDatum(el) {
578
- return $(el).data(valueKey);
579
- };
580
- Dataset.extractDatum = function extractDatum(el) {
581
- return $(el).data(datumKey);
678
+ Dataset.extractData = function extractData(el) {
679
+ var $el = $(el);
680
+ if ($el.data(keys.obj)) {
681
+ return {
682
+ val: $el.data(keys.val) || "",
683
+ obj: $el.data(keys.obj) || null
684
+ };
685
+ }
686
+ return null;
582
687
  };
583
688
  _.mixin(Dataset.prototype, EventEmitter, {
584
- _render: function render(query, suggestions) {
585
- if (!this.$el) {
586
- return;
587
- }
588
- var that = this, hasSuggestions;
589
- this.$el.empty();
590
- hasSuggestions = suggestions && suggestions.length;
591
- if (!hasSuggestions && this.templates.empty) {
592
- this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
593
- } else if (hasSuggestions) {
594
- this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
595
- }
596
- this.trigger("rendered");
597
- function getEmptyHtml() {
598
- return that.templates.empty({
599
- query: query,
600
- isEmpty: true
601
- });
602
- }
603
- function getSuggestionsHtml() {
604
- var $suggestions, nodes;
605
- $suggestions = $(html.suggestions).css(css.suggestions);
606
- nodes = _.map(suggestions, getSuggestionNode);
607
- $suggestions.append.apply($suggestions, nodes);
608
- that.highlight && highlight({
609
- className: "tt-highlight",
610
- node: $suggestions[0],
611
- pattern: query
612
- });
613
- return $suggestions;
614
- function getSuggestionNode(suggestion) {
615
- var $el;
616
- $el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion);
617
- $el.children().each(function() {
618
- $(this).css(css.suggestionChild);
619
- });
620
- return $el;
621
- }
622
- }
623
- function getHeaderHtml() {
624
- return that.templates.header({
625
- query: query,
626
- isEmpty: !hasSuggestions
627
- });
689
+ _overwrite: function overwrite(query, suggestions) {
690
+ suggestions = suggestions || [];
691
+ if (suggestions.length) {
692
+ this._renderSuggestions(query, suggestions);
693
+ } else if (this.async && this.templates.pending) {
694
+ this._renderPending(query);
695
+ } else if (!this.async && this.templates.notFound) {
696
+ this._renderNotFound(query);
697
+ } else {
698
+ this._empty();
628
699
  }
629
- function getFooterHtml() {
630
- return that.templates.footer({
631
- query: query,
632
- isEmpty: !hasSuggestions
633
- });
700
+ this.trigger("rendered", this.name, suggestions, false);
701
+ },
702
+ _append: function append(query, suggestions) {
703
+ suggestions = suggestions || [];
704
+ if (suggestions.length && this.$lastSuggestion.length) {
705
+ this._appendSuggestions(query, suggestions);
706
+ } else if (suggestions.length) {
707
+ this._renderSuggestions(query, suggestions);
708
+ } else if (!this.$lastSuggestion.length && this.templates.notFound) {
709
+ this._renderNotFound(query);
634
710
  }
635
- },
636
- getRoot: function getRoot() {
637
- return this.$el;
711
+ this.trigger("rendered", this.name, suggestions, true);
712
+ },
713
+ _renderSuggestions: function renderSuggestions(query, suggestions) {
714
+ var $fragment;
715
+ $fragment = this._getSuggestionsFragment(query, suggestions);
716
+ this.$lastSuggestion = $fragment.children().last();
717
+ this.$el.html($fragment).prepend(this._getHeader(query, suggestions)).append(this._getFooter(query, suggestions));
718
+ },
719
+ _appendSuggestions: function appendSuggestions(query, suggestions) {
720
+ var $fragment, $lastSuggestion;
721
+ $fragment = this._getSuggestionsFragment(query, suggestions);
722
+ $lastSuggestion = $fragment.children().last();
723
+ this.$lastSuggestion.after($fragment);
724
+ this.$lastSuggestion = $lastSuggestion;
725
+ },
726
+ _renderPending: function renderPending(query) {
727
+ var template = this.templates.pending;
728
+ this._resetLastSuggestion();
729
+ template && this.$el.html(template({
730
+ query: query,
731
+ dataset: this.name
732
+ }));
733
+ },
734
+ _renderNotFound: function renderNotFound(query) {
735
+ var template = this.templates.notFound;
736
+ this._resetLastSuggestion();
737
+ template && this.$el.html(template({
738
+ query: query,
739
+ dataset: this.name
740
+ }));
741
+ },
742
+ _empty: function empty() {
743
+ this.$el.empty();
744
+ this._resetLastSuggestion();
745
+ },
746
+ _getSuggestionsFragment: function getSuggestionsFragment(query, suggestions) {
747
+ var that = this, fragment;
748
+ fragment = document.createDocumentFragment();
749
+ _.each(suggestions, function getSuggestionNode(suggestion) {
750
+ var $el, context;
751
+ context = that._injectQuery(query, suggestion);
752
+ $el = $(that.templates.suggestion(context)).data(keys.obj, suggestion).data(keys.val, that.displayFn(suggestion)).addClass(that.classes.suggestion + " " + that.classes.selectable);
753
+ fragment.appendChild($el[0]);
754
+ });
755
+ this.highlight && highlight({
756
+ className: this.classes.highlight,
757
+ node: fragment,
758
+ pattern: query
759
+ });
760
+ return $(fragment);
761
+ },
762
+ _getFooter: function getFooter(query, suggestions) {
763
+ return this.templates.footer ? this.templates.footer({
764
+ query: query,
765
+ suggestions: suggestions,
766
+ dataset: this.name
767
+ }) : null;
768
+ },
769
+ _getHeader: function getHeader(query, suggestions) {
770
+ return this.templates.header ? this.templates.header({
771
+ query: query,
772
+ suggestions: suggestions,
773
+ dataset: this.name
774
+ }) : null;
775
+ },
776
+ _resetLastSuggestion: function resetLastSuggestion() {
777
+ this.$lastSuggestion = $();
778
+ },
779
+ _injectQuery: function injectQuery(query, obj) {
780
+ return _.isObject(obj) ? _.mixin({
781
+ _query: query
782
+ }, obj) : obj;
638
783
  },
639
784
  update: function update(query) {
640
- var that = this;
641
- this.query = query;
642
- this.canceled = false;
643
- this.source(query, render);
644
- function render(suggestions) {
645
- if (!that.canceled && query === that.query) {
646
- that._render(query, suggestions);
785
+ var that = this, canceled = false, syncCalled = false, rendered = 0;
786
+ this.cancel();
787
+ this.cancel = function cancel() {
788
+ canceled = true;
789
+ that.cancel = $.noop;
790
+ that.async && that.trigger("asyncCanceled", query);
791
+ };
792
+ this.source(query, sync, async);
793
+ !syncCalled && sync([]);
794
+ function sync(suggestions) {
795
+ if (syncCalled) {
796
+ return;
797
+ }
798
+ syncCalled = true;
799
+ suggestions = (suggestions || []).slice(0, that.limit);
800
+ rendered = suggestions.length;
801
+ that._overwrite(query, suggestions);
802
+ if (rendered < that.limit && that.async) {
803
+ that.trigger("asyncRequested", query);
804
+ }
805
+ }
806
+ function async(suggestions) {
807
+ suggestions = suggestions || [];
808
+ if (!canceled && rendered < that.limit) {
809
+ that.cancel = $.noop;
810
+ that._append(query, suggestions.slice(0, that.limit - rendered));
811
+ rendered += suggestions.length;
812
+ that.async && that.trigger("asyncReceived", query);
647
813
  }
648
814
  }
649
815
  },
650
- cancel: function cancel() {
651
- this.canceled = true;
652
- },
816
+ cancel: $.noop,
653
817
  clear: function clear() {
818
+ this._empty();
654
819
  this.cancel();
655
- this.$el.empty();
656
- this.trigger("rendered");
820
+ this.trigger("cleared");
657
821
  },
658
822
  isEmpty: function isEmpty() {
659
823
  return this.$el.is(":empty");
660
824
  },
661
825
  destroy: function destroy() {
662
- this.$el = null;
826
+ this.$el = $("<div>");
663
827
  }
664
828
  });
665
829
  return Dataset;
666
830
  function getDisplayFn(display) {
667
- display = display || "value";
831
+ display = display || _.stringify;
668
832
  return _.isFunction(display) ? display : displayFn;
669
833
  function displayFn(obj) {
670
834
  return obj[display];
@@ -672,506 +836,637 @@
672
836
  }
673
837
  function getTemplates(templates, displayFn) {
674
838
  return {
675
- empty: templates.empty && _.templatify(templates.empty),
839
+ notFound: templates.notFound && _.templatify(templates.notFound),
840
+ pending: templates.pending && _.templatify(templates.pending),
676
841
  header: templates.header && _.templatify(templates.header),
677
842
  footer: templates.footer && _.templatify(templates.footer),
678
843
  suggestion: templates.suggestion || suggestionTemplate
679
844
  };
680
845
  function suggestionTemplate(context) {
681
- return "<p>" + displayFn(context) + "</p>";
846
+ return $("<div>").text(displayFn(context));
682
847
  }
683
848
  }
684
849
  function isValidName(str) {
685
850
  return /^[_a-zA-Z0-9-]+$/.test(str);
686
851
  }
687
852
  }();
688
- var Dropdown = function() {
853
+ var Menu = function() {
689
854
  "use strict";
690
- function Dropdown(o) {
691
- var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave;
855
+ function Menu(o, www) {
856
+ var that = this;
692
857
  o = o || {};
693
- if (!o.menu) {
694
- $.error("menu is required");
858
+ if (!o.node) {
859
+ $.error("node is required");
695
860
  }
696
- this.isOpen = false;
697
- this.isEmpty = true;
861
+ www.mixin(this);
862
+ this.$node = $(o.node);
863
+ this.query = null;
698
864
  this.datasets = _.map(o.datasets, initializeDataset);
699
- onSuggestionClick = _.bind(this._onSuggestionClick, this);
700
- onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this);
701
- onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this);
702
- this.$menu = $(o.menu).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave);
703
- _.each(this.datasets, function(dataset) {
704
- that.$menu.append(dataset.getRoot());
705
- dataset.onSync("rendered", that._onRendered, that);
706
- });
865
+ function initializeDataset(oDataset) {
866
+ var node = that.$node.find(oDataset.node).first();
867
+ oDataset.node = node.length ? node : $("<div>").appendTo(that.$node);
868
+ return new Dataset(oDataset, www);
869
+ }
707
870
  }
708
- _.mixin(Dropdown.prototype, EventEmitter, {
709
- _onSuggestionClick: function onSuggestionClick($e) {
710
- this.trigger("suggestionClicked", $($e.currentTarget));
871
+ _.mixin(Menu.prototype, EventEmitter, {
872
+ _onSelectableClick: function onSelectableClick($e) {
873
+ this.trigger("selectableClicked", $($e.currentTarget));
711
874
  },
712
- _onSuggestionMouseEnter: function onSuggestionMouseEnter($e) {
713
- this._removeCursor();
714
- this._setCursor($($e.currentTarget), true);
875
+ _onRendered: function onRendered(type, dataset, suggestions, async) {
876
+ this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty());
877
+ this.trigger("datasetRendered", dataset, suggestions, async);
715
878
  },
716
- _onSuggestionMouseLeave: function onSuggestionMouseLeave() {
717
- this._removeCursor();
879
+ _onCleared: function onCleared() {
880
+ this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty());
881
+ this.trigger("datasetCleared");
718
882
  },
719
- _onRendered: function onRendered() {
720
- this.isEmpty = _.every(this.datasets, isDatasetEmpty);
721
- this.isEmpty ? this._hide() : this.isOpen && this._show();
722
- this.trigger("datasetRendered");
883
+ _propagate: function propagate() {
884
+ this.trigger.apply(this, arguments);
885
+ },
886
+ _allDatasetsEmpty: function allDatasetsEmpty() {
887
+ return _.every(this.datasets, isDatasetEmpty);
723
888
  function isDatasetEmpty(dataset) {
724
889
  return dataset.isEmpty();
725
890
  }
726
891
  },
727
- _hide: function() {
728
- this.$menu.hide();
892
+ _getSelectables: function getSelectables() {
893
+ return this.$node.find(this.selectors.selectable);
729
894
  },
730
- _show: function() {
731
- this.$menu.css("display", "block");
732
- },
733
- _getSuggestions: function getSuggestions() {
734
- return this.$menu.find(".tt-suggestion");
735
- },
736
- _getCursor: function getCursor() {
737
- return this.$menu.find(".tt-cursor").first();
738
- },
739
- _setCursor: function setCursor($el, silent) {
740
- $el.first().addClass("tt-cursor");
741
- !silent && this.trigger("cursorMoved");
742
- },
743
- _removeCursor: function removeCursor() {
744
- this._getCursor().removeClass("tt-cursor");
745
- },
746
- _moveCursor: function moveCursor(increment) {
747
- var $suggestions, $oldCursor, newCursorIndex, $newCursor;
748
- if (!this.isOpen) {
749
- return;
750
- }
751
- $oldCursor = this._getCursor();
752
- $suggestions = this._getSuggestions();
753
- this._removeCursor();
754
- newCursorIndex = $suggestions.index($oldCursor) + increment;
755
- newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1;
756
- if (newCursorIndex === -1) {
757
- this.trigger("cursorRemoved");
758
- return;
759
- } else if (newCursorIndex < -1) {
760
- newCursorIndex = $suggestions.length - 1;
761
- }
762
- this._setCursor($newCursor = $suggestions.eq(newCursorIndex));
763
- this._ensureVisible($newCursor);
895
+ _removeCursor: function _removeCursor() {
896
+ var $selectable = this.getActiveSelectable();
897
+ $selectable && $selectable.removeClass(this.classes.cursor);
764
898
  },
765
899
  _ensureVisible: function ensureVisible($el) {
766
- var elTop, elBottom, menuScrollTop, menuHeight;
900
+ var elTop, elBottom, nodeScrollTop, nodeHeight;
767
901
  elTop = $el.position().top;
768
902
  elBottom = elTop + $el.outerHeight(true);
769
- menuScrollTop = this.$menu.scrollTop();
770
- menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10);
903
+ nodeScrollTop = this.$node.scrollTop();
904
+ nodeHeight = this.$node.height() + parseInt(this.$node.css("paddingTop"), 10) + parseInt(this.$node.css("paddingBottom"), 10);
771
905
  if (elTop < 0) {
772
- this.$menu.scrollTop(menuScrollTop + elTop);
773
- } else if (menuHeight < elBottom) {
774
- this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
906
+ this.$node.scrollTop(nodeScrollTop + elTop);
907
+ } else if (nodeHeight < elBottom) {
908
+ this.$node.scrollTop(nodeScrollTop + (elBottom - nodeHeight));
775
909
  }
776
910
  },
777
- close: function close() {
778
- if (this.isOpen) {
779
- this.isOpen = false;
780
- this._removeCursor();
781
- this._hide();
782
- this.trigger("closed");
783
- }
784
- },
785
- open: function open() {
786
- if (!this.isOpen) {
787
- this.isOpen = true;
788
- !this.isEmpty && this._show();
789
- this.trigger("opened");
790
- }
911
+ bind: function() {
912
+ var that = this, onSelectableClick;
913
+ onSelectableClick = _.bind(this._onSelectableClick, this);
914
+ this.$node.on("click.tt", this.selectors.selectable, onSelectableClick);
915
+ _.each(this.datasets, function(dataset) {
916
+ dataset.onSync("asyncRequested", that._propagate, that).onSync("asyncCanceled", that._propagate, that).onSync("asyncReceived", that._propagate, that).onSync("rendered", that._onRendered, that).onSync("cleared", that._onCleared, that);
917
+ });
918
+ return this;
791
919
  },
792
- setLanguageDirection: function setLanguageDirection(dir) {
793
- this.$menu.css(dir === "ltr" ? css.ltr : css.rtl);
920
+ isOpen: function isOpen() {
921
+ return this.$node.hasClass(this.classes.open);
794
922
  },
795
- moveCursorUp: function moveCursorUp() {
796
- this._moveCursor(-1);
923
+ open: function open() {
924
+ this.$node.scrollTop(0);
925
+ this.$node.addClass(this.classes.open);
797
926
  },
798
- moveCursorDown: function moveCursorDown() {
799
- this._moveCursor(+1);
927
+ close: function close() {
928
+ this.$node.removeClass(this.classes.open);
929
+ this._removeCursor();
800
930
  },
801
- getDatumForSuggestion: function getDatumForSuggestion($el) {
802
- var datum = null;
803
- if ($el.length) {
804
- datum = {
805
- raw: Dataset.extractDatum($el),
806
- value: Dataset.extractValue($el),
807
- datasetName: Dataset.extractDatasetName($el)
808
- };
931
+ setLanguageDirection: function setLanguageDirection(dir) {
932
+ this.$node.attr("dir", dir);
933
+ },
934
+ selectableRelativeToCursor: function selectableRelativeToCursor(delta) {
935
+ var $selectables, $oldCursor, oldIndex, newIndex;
936
+ $oldCursor = this.getActiveSelectable();
937
+ $selectables = this._getSelectables();
938
+ oldIndex = $oldCursor ? $selectables.index($oldCursor) : -1;
939
+ newIndex = oldIndex + delta;
940
+ newIndex = (newIndex + 1) % ($selectables.length + 1) - 1;
941
+ newIndex = newIndex < -1 ? $selectables.length - 1 : newIndex;
942
+ return newIndex === -1 ? null : $selectables.eq(newIndex);
943
+ },
944
+ setCursor: function setCursor($selectable) {
945
+ this._removeCursor();
946
+ if ($selectable = $selectable && $selectable.first()) {
947
+ $selectable.addClass(this.classes.cursor);
948
+ this._ensureVisible($selectable);
809
949
  }
810
- return datum;
811
950
  },
812
- getDatumForCursor: function getDatumForCursor() {
813
- return this.getDatumForSuggestion(this._getCursor().first());
951
+ getSelectableData: function getSelectableData($el) {
952
+ return $el && $el.length ? Dataset.extractData($el) : null;
953
+ },
954
+ getActiveSelectable: function getActiveSelectable() {
955
+ var $selectable = this._getSelectables().filter(this.selectors.cursor).first();
956
+ return $selectable.length ? $selectable : null;
814
957
  },
815
- getDatumForTopSuggestion: function getDatumForTopSuggestion() {
816
- return this.getDatumForSuggestion(this._getSuggestions().first());
958
+ getTopSelectable: function getTopSelectable() {
959
+ var $selectable = this._getSelectables().first();
960
+ return $selectable.length ? $selectable : null;
817
961
  },
818
962
  update: function update(query) {
819
- _.each(this.datasets, updateDataset);
963
+ var isValidUpdate = query !== this.query;
964
+ if (isValidUpdate) {
965
+ this.query = query;
966
+ _.each(this.datasets, updateDataset);
967
+ }
968
+ return isValidUpdate;
820
969
  function updateDataset(dataset) {
821
970
  dataset.update(query);
822
971
  }
823
972
  },
824
973
  empty: function empty() {
825
974
  _.each(this.datasets, clearDataset);
826
- this.isEmpty = true;
975
+ this.query = null;
976
+ this.$node.addClass(this.classes.empty);
827
977
  function clearDataset(dataset) {
828
978
  dataset.clear();
829
979
  }
830
980
  },
831
- isVisible: function isVisible() {
832
- return this.isOpen && !this.isEmpty;
833
- },
834
981
  destroy: function destroy() {
835
- this.$menu.off(".tt");
836
- this.$menu = null;
982
+ this.$node.off(".tt");
983
+ this.$node = $("<div>");
837
984
  _.each(this.datasets, destroyDataset);
838
985
  function destroyDataset(dataset) {
839
986
  dataset.destroy();
840
987
  }
841
988
  }
842
989
  });
843
- return Dropdown;
844
- function initializeDataset(oDataset) {
845
- return new Dataset(oDataset);
990
+ return Menu;
991
+ }();
992
+ var DefaultMenu = function() {
993
+ "use strict";
994
+ var s = Menu.prototype;
995
+ function DefaultMenu() {
996
+ Menu.apply(this, [].slice.call(arguments, 0));
846
997
  }
998
+ _.mixin(DefaultMenu.prototype, Menu.prototype, {
999
+ open: function open() {
1000
+ !this._allDatasetsEmpty() && this._show();
1001
+ return s.open.apply(this, [].slice.call(arguments, 0));
1002
+ },
1003
+ close: function close() {
1004
+ this._hide();
1005
+ return s.close.apply(this, [].slice.call(arguments, 0));
1006
+ },
1007
+ _onRendered: function onRendered() {
1008
+ if (this._allDatasetsEmpty()) {
1009
+ this._hide();
1010
+ } else {
1011
+ this.isOpen() && this._show();
1012
+ }
1013
+ return s._onRendered.apply(this, [].slice.call(arguments, 0));
1014
+ },
1015
+ _onCleared: function onCleared() {
1016
+ if (this._allDatasetsEmpty()) {
1017
+ this._hide();
1018
+ } else {
1019
+ this.isOpen() && this._show();
1020
+ }
1021
+ return s._onCleared.apply(this, [].slice.call(arguments, 0));
1022
+ },
1023
+ setLanguageDirection: function setLanguageDirection(dir) {
1024
+ this.$node.css(dir === "ltr" ? this.css.ltr : this.css.rtl);
1025
+ return s.setLanguageDirection.apply(this, [].slice.call(arguments, 0));
1026
+ },
1027
+ _hide: function hide() {
1028
+ this.$node.hide();
1029
+ },
1030
+ _show: function show() {
1031
+ this.$node.css("display", "block");
1032
+ }
1033
+ });
1034
+ return DefaultMenu;
847
1035
  }();
848
1036
  var Typeahead = function() {
849
1037
  "use strict";
850
- var attrsKey = "ttAttrs";
851
- function Typeahead(o) {
852
- var $menu, $input, $hint;
1038
+ function Typeahead(o, www) {
1039
+ var onFocused, onBlurred, onEnterKeyed, onTabKeyed, onEscKeyed, onUpKeyed, onDownKeyed, onLeftKeyed, onRightKeyed, onQueryChanged, onWhitespaceChanged;
853
1040
  o = o || {};
854
1041
  if (!o.input) {
855
1042
  $.error("missing input");
856
1043
  }
857
- this.isActivated = false;
858
- this.autoselect = !!o.autoselect;
1044
+ if (!o.menu) {
1045
+ $.error("missing menu");
1046
+ }
1047
+ if (!o.eventBus) {
1048
+ $.error("missing event bus");
1049
+ }
1050
+ www.mixin(this);
1051
+ this.eventBus = o.eventBus;
859
1052
  this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
860
- this.$node = buildDom(o.input, o.withHint);
861
- $menu = this.$node.find(".tt-dropdown-menu");
862
- $input = this.$node.find(".tt-input");
863
- $hint = this.$node.find(".tt-hint");
864
- $input.on("blur.tt", function($e) {
865
- var active, isActive, hasActive;
866
- active = document.activeElement;
867
- isActive = $menu.is(active);
868
- hasActive = $menu.has(active).length > 0;
869
- if (_.isMsie() && (isActive || hasActive)) {
870
- $e.preventDefault();
871
- $e.stopImmediatePropagation();
872
- _.defer(function() {
873
- $input.focus();
874
- });
875
- }
876
- });
877
- $menu.on("mousedown.tt", function($e) {
878
- $e.preventDefault();
879
- });
880
- this.eventBus = o.eventBus || new EventBus({
881
- el: $input
882
- });
883
- this.dropdown = new Dropdown({
884
- menu: $menu,
885
- datasets: o.datasets
886
- }).onSync("suggestionClicked", this._onSuggestionClicked, this).onSync("cursorMoved", this._onCursorMoved, this).onSync("cursorRemoved", this._onCursorRemoved, this).onSync("opened", this._onOpened, this).onSync("closed", this._onClosed, this).onAsync("datasetRendered", this._onDatasetRendered, this);
887
- this.input = new Input({
888
- input: $input,
889
- hint: $hint
890
- }).onSync("focused", this._onFocused, this).onSync("blurred", this._onBlurred, this).onSync("enterKeyed", this._onEnterKeyed, this).onSync("tabKeyed", this._onTabKeyed, this).onSync("escKeyed", this._onEscKeyed, this).onSync("upKeyed", this._onUpKeyed, this).onSync("downKeyed", this._onDownKeyed, this).onSync("leftKeyed", this._onLeftKeyed, this).onSync("rightKeyed", this._onRightKeyed, this).onSync("queryChanged", this._onQueryChanged, this).onSync("whitespaceChanged", this._onWhitespaceChanged, this);
891
- this._setLanguageDirection();
1053
+ this.input = o.input;
1054
+ this.menu = o.menu;
1055
+ this.enabled = true;
1056
+ this.active = false;
1057
+ this.input.hasFocus() && this.activate();
1058
+ this.dir = this.input.getLangDir();
1059
+ this._hacks();
1060
+ this.menu.bind().onSync("selectableClicked", this._onSelectableClicked, this).onSync("asyncRequested", this._onAsyncRequested, this).onSync("asyncCanceled", this._onAsyncCanceled, this).onSync("asyncReceived", this._onAsyncReceived, this).onSync("datasetRendered", this._onDatasetRendered, this).onSync("datasetCleared", this._onDatasetCleared, this);
1061
+ onFocused = c(this, "activate", "open", "_onFocused");
1062
+ onBlurred = c(this, "deactivate", "_onBlurred");
1063
+ onEnterKeyed = c(this, "isActive", "isOpen", "_onEnterKeyed");
1064
+ onTabKeyed = c(this, "isActive", "isOpen", "_onTabKeyed");
1065
+ onEscKeyed = c(this, "isActive", "_onEscKeyed");
1066
+ onUpKeyed = c(this, "isActive", "open", "_onUpKeyed");
1067
+ onDownKeyed = c(this, "isActive", "open", "_onDownKeyed");
1068
+ onLeftKeyed = c(this, "isActive", "isOpen", "_onLeftKeyed");
1069
+ onRightKeyed = c(this, "isActive", "isOpen", "_onRightKeyed");
1070
+ onQueryChanged = c(this, "_openIfActive", "_onQueryChanged");
1071
+ onWhitespaceChanged = c(this, "_openIfActive", "_onWhitespaceChanged");
1072
+ this.input.bind().onSync("focused", onFocused, this).onSync("blurred", onBlurred, this).onSync("enterKeyed", onEnterKeyed, this).onSync("tabKeyed", onTabKeyed, this).onSync("escKeyed", onEscKeyed, this).onSync("upKeyed", onUpKeyed, this).onSync("downKeyed", onDownKeyed, this).onSync("leftKeyed", onLeftKeyed, this).onSync("rightKeyed", onRightKeyed, this).onSync("queryChanged", onQueryChanged, this).onSync("whitespaceChanged", onWhitespaceChanged, this).onSync("langDirChanged", this._onLangDirChanged, this);
892
1073
  }
893
1074
  _.mixin(Typeahead.prototype, {
894
- _onSuggestionClicked: function onSuggestionClicked(type, $el) {
895
- var datum;
896
- if (datum = this.dropdown.getDatumForSuggestion($el)) {
897
- this._select(datum);
898
- }
1075
+ _hacks: function hacks() {
1076
+ var $input, $menu;
1077
+ $input = this.input.$input || $("<div>");
1078
+ $menu = this.menu.$node || $("<div>");
1079
+ $input.on("blur.tt", function($e) {
1080
+ var active, isActive, hasActive;
1081
+ active = document.activeElement;
1082
+ isActive = $menu.is(active);
1083
+ hasActive = $menu.has(active).length > 0;
1084
+ if (_.isMsie() && (isActive || hasActive)) {
1085
+ $e.preventDefault();
1086
+ $e.stopImmediatePropagation();
1087
+ _.defer(function() {
1088
+ $input.focus();
1089
+ });
1090
+ }
1091
+ });
1092
+ $menu.on("mousedown.tt", function($e) {
1093
+ $e.preventDefault();
1094
+ });
899
1095
  },
900
- _onCursorMoved: function onCursorMoved() {
901
- var datum = this.dropdown.getDatumForCursor();
902
- this.input.setInputValue(datum.value, true);
903
- this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName);
1096
+ _onSelectableClicked: function onSelectableClicked(type, $el) {
1097
+ this.select($el);
904
1098
  },
905
- _onCursorRemoved: function onCursorRemoved() {
906
- this.input.resetInputValue();
1099
+ _onDatasetCleared: function onDatasetCleared() {
907
1100
  this._updateHint();
908
1101
  },
909
- _onDatasetRendered: function onDatasetRendered() {
1102
+ _onDatasetRendered: function onDatasetRendered(type, dataset, suggestions, async) {
910
1103
  this._updateHint();
1104
+ this.eventBus.trigger("render", suggestions, async, dataset);
911
1105
  },
912
- _onOpened: function onOpened() {
913
- this._updateHint();
914
- this.eventBus.trigger("opened");
1106
+ _onAsyncRequested: function onAsyncRequested(type, dataset, query) {
1107
+ this.eventBus.trigger("asyncrequest", query, dataset);
915
1108
  },
916
- _onClosed: function onClosed() {
917
- this.input.clearHint();
918
- this.eventBus.trigger("closed");
1109
+ _onAsyncCanceled: function onAsyncCanceled(type, dataset, query) {
1110
+ this.eventBus.trigger("asynccancel", query, dataset);
1111
+ },
1112
+ _onAsyncReceived: function onAsyncReceived(type, dataset, query) {
1113
+ this.eventBus.trigger("asyncreceive", query, dataset);
919
1114
  },
920
1115
  _onFocused: function onFocused() {
921
- this.isActivated = true;
922
- this.dropdown.open();
1116
+ this._minLengthMet() && this.menu.update(this.input.getQuery());
923
1117
  },
924
1118
  _onBlurred: function onBlurred() {
925
- this.isActivated = false;
926
- this.dropdown.empty();
927
- this.dropdown.close();
1119
+ if (this.input.hasQueryChangedSinceLastFocus()) {
1120
+ this.eventBus.trigger("change", this.input.getQuery());
1121
+ }
928
1122
  },
929
1123
  _onEnterKeyed: function onEnterKeyed(type, $e) {
930
- var cursorDatum, topSuggestionDatum;
931
- cursorDatum = this.dropdown.getDatumForCursor();
932
- topSuggestionDatum = this.dropdown.getDatumForTopSuggestion();
933
- if (cursorDatum) {
934
- this._select(cursorDatum);
935
- $e.preventDefault();
936
- } else if (this.autoselect && topSuggestionDatum) {
937
- this._select(topSuggestionDatum);
938
- $e.preventDefault();
1124
+ var $selectable;
1125
+ if ($selectable = this.menu.getActiveSelectable()) {
1126
+ this.select($selectable) && $e.preventDefault();
939
1127
  }
940
1128
  },
941
1129
  _onTabKeyed: function onTabKeyed(type, $e) {
942
- var datum;
943
- if (datum = this.dropdown.getDatumForCursor()) {
944
- this._select(datum);
945
- $e.preventDefault();
946
- } else {
947
- this._autocomplete(true);
1130
+ var $selectable;
1131
+ if ($selectable = this.menu.getActiveSelectable()) {
1132
+ this.select($selectable) && $e.preventDefault();
1133
+ } else if ($selectable = this.menu.getTopSelectable()) {
1134
+ this.autocomplete($selectable) && $e.preventDefault();
948
1135
  }
949
1136
  },
950
1137
  _onEscKeyed: function onEscKeyed() {
951
- this.dropdown.close();
952
- this.input.resetInputValue();
1138
+ this.close();
953
1139
  },
954
1140
  _onUpKeyed: function onUpKeyed() {
955
- var query = this.input.getQuery();
956
- this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorUp();
957
- this.dropdown.open();
1141
+ this.moveCursor(-1);
958
1142
  },
959
1143
  _onDownKeyed: function onDownKeyed() {
960
- var query = this.input.getQuery();
961
- this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorDown();
962
- this.dropdown.open();
1144
+ this.moveCursor(+1);
963
1145
  },
964
1146
  _onLeftKeyed: function onLeftKeyed() {
965
- this.dir === "rtl" && this._autocomplete();
1147
+ if (this.dir === "rtl" && this.input.isCursorAtEnd()) {
1148
+ this.autocomplete(this.menu.getTopSelectable());
1149
+ }
966
1150
  },
967
1151
  _onRightKeyed: function onRightKeyed() {
968
- this.dir === "ltr" && this._autocomplete();
1152
+ if (this.dir === "ltr" && this.input.isCursorAtEnd()) {
1153
+ this.autocomplete(this.menu.getTopSelectable());
1154
+ }
969
1155
  },
970
1156
  _onQueryChanged: function onQueryChanged(e, query) {
971
- this.input.clearHintIfInvalid();
972
- query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.empty();
973
- this.dropdown.open();
974
- this._setLanguageDirection();
1157
+ this._minLengthMet(query) ? this.menu.update(query) : this.menu.empty();
975
1158
  },
976
1159
  _onWhitespaceChanged: function onWhitespaceChanged() {
977
1160
  this._updateHint();
978
- this.dropdown.open();
979
1161
  },
980
- _setLanguageDirection: function setLanguageDirection() {
981
- var dir;
982
- if (this.dir !== (dir = this.input.getLanguageDirection())) {
1162
+ _onLangDirChanged: function onLangDirChanged(e, dir) {
1163
+ if (this.dir !== dir) {
983
1164
  this.dir = dir;
984
- this.$node.css("direction", dir);
985
- this.dropdown.setLanguageDirection(dir);
1165
+ this.menu.setLanguageDirection(dir);
986
1166
  }
987
1167
  },
1168
+ _openIfActive: function openIfActive() {
1169
+ this.isActive() && this.open();
1170
+ },
1171
+ _minLengthMet: function minLengthMet(query) {
1172
+ query = _.isString(query) ? query : this.input.getQuery() || "";
1173
+ return query.length >= this.minLength;
1174
+ },
988
1175
  _updateHint: function updateHint() {
989
- var datum, val, query, escapedQuery, frontMatchRegEx, match;
990
- datum = this.dropdown.getDatumForTopSuggestion();
991
- if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) {
992
- val = this.input.getInputValue();
1176
+ var $selectable, data, val, query, escapedQuery, frontMatchRegEx, match;
1177
+ $selectable = this.menu.getTopSelectable();
1178
+ data = this.menu.getSelectableData($selectable);
1179
+ val = this.input.getInputValue();
1180
+ if (data && !_.isBlankString(val) && !this.input.hasOverflow()) {
993
1181
  query = Input.normalizeQuery(val);
994
1182
  escapedQuery = _.escapeRegExChars(query);
995
1183
  frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
996
- match = frontMatchRegEx.exec(datum.value);
997
- match ? this.input.setHint(val + match[1]) : this.input.clearHint();
1184
+ match = frontMatchRegEx.exec(data.val);
1185
+ match && this.input.setHint(val + match[1]);
998
1186
  } else {
999
1187
  this.input.clearHint();
1000
1188
  }
1001
1189
  },
1002
- _autocomplete: function autocomplete(laxCursor) {
1003
- var hint, query, isCursorAtEnd, datum;
1004
- hint = this.input.getHint();
1005
- query = this.input.getQuery();
1006
- isCursorAtEnd = laxCursor || this.input.isCursorAtEnd();
1007
- if (hint && query !== hint && isCursorAtEnd) {
1008
- datum = this.dropdown.getDatumForTopSuggestion();
1009
- datum && this.input.setInputValue(datum.value);
1010
- this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName);
1190
+ isEnabled: function isEnabled() {
1191
+ return this.enabled;
1192
+ },
1193
+ enable: function enable() {
1194
+ this.enabled = true;
1195
+ },
1196
+ disable: function disable() {
1197
+ this.enabled = false;
1198
+ },
1199
+ isActive: function isActive() {
1200
+ return this.active;
1201
+ },
1202
+ activate: function activate() {
1203
+ if (this.isActive()) {
1204
+ return true;
1205
+ } else if (!this.isEnabled() || this.eventBus.before("active")) {
1206
+ return false;
1207
+ } else {
1208
+ this.active = true;
1209
+ this.eventBus.trigger("active");
1210
+ return true;
1011
1211
  }
1012
1212
  },
1013
- _select: function select(datum) {
1014
- this.input.setQuery(datum.value);
1015
- this.input.setInputValue(datum.value, true);
1016
- this._setLanguageDirection();
1017
- this.eventBus.trigger("selected", datum.raw, datum.datasetName);
1018
- this.dropdown.close();
1019
- _.defer(_.bind(this.dropdown.empty, this.dropdown));
1213
+ deactivate: function deactivate() {
1214
+ if (!this.isActive()) {
1215
+ return true;
1216
+ } else if (this.eventBus.before("idle")) {
1217
+ return false;
1218
+ } else {
1219
+ this.active = false;
1220
+ this.close();
1221
+ this.eventBus.trigger("idle");
1222
+ return true;
1223
+ }
1224
+ },
1225
+ isOpen: function isOpen() {
1226
+ return this.menu.isOpen();
1020
1227
  },
1021
1228
  open: function open() {
1022
- this.dropdown.open();
1229
+ if (!this.isOpen() && !this.eventBus.before("open")) {
1230
+ this.menu.open();
1231
+ this._updateHint();
1232
+ this.eventBus.trigger("open");
1233
+ }
1234
+ return this.isOpen();
1023
1235
  },
1024
1236
  close: function close() {
1025
- this.dropdown.close();
1237
+ if (this.isOpen() && !this.eventBus.before("close")) {
1238
+ this.menu.close();
1239
+ this.input.clearHint();
1240
+ this.input.resetInputValue();
1241
+ this.eventBus.trigger("close");
1242
+ }
1243
+ return !this.isOpen();
1026
1244
  },
1027
1245
  setVal: function setVal(val) {
1028
- val = _.toStr(val);
1029
- if (this.isActivated) {
1030
- this.input.setInputValue(val);
1031
- } else {
1032
- this.input.setQuery(val);
1033
- this.input.setInputValue(val, true);
1034
- }
1035
- this._setLanguageDirection();
1246
+ this.input.setQuery(_.toStr(val));
1036
1247
  },
1037
1248
  getVal: function getVal() {
1038
1249
  return this.input.getQuery();
1039
1250
  },
1251
+ select: function select($selectable) {
1252
+ var data = this.menu.getSelectableData($selectable);
1253
+ if (data && !this.eventBus.before("select", data.obj)) {
1254
+ this.input.setQuery(data.val, true);
1255
+ this.eventBus.trigger("select", data.obj);
1256
+ this.close();
1257
+ return true;
1258
+ }
1259
+ return false;
1260
+ },
1261
+ autocomplete: function autocomplete($selectable) {
1262
+ var query, data, isValid;
1263
+ query = this.input.getQuery();
1264
+ data = this.menu.getSelectableData($selectable);
1265
+ isValid = data && query !== data.val;
1266
+ if (isValid && !this.eventBus.before("autocomplete", data.obj)) {
1267
+ this.input.setQuery(data.val);
1268
+ this.eventBus.trigger("autocomplete", data.obj);
1269
+ return true;
1270
+ }
1271
+ return false;
1272
+ },
1273
+ moveCursor: function moveCursor(delta) {
1274
+ var query, $candidate, data, payload, cancelMove;
1275
+ query = this.input.getQuery();
1276
+ $candidate = this.menu.selectableRelativeToCursor(delta);
1277
+ data = this.menu.getSelectableData($candidate);
1278
+ payload = data ? data.obj : null;
1279
+ cancelMove = this._minLengthMet() && this.menu.update(query);
1280
+ if (!cancelMove && !this.eventBus.before("cursorchange", payload)) {
1281
+ this.menu.setCursor($candidate);
1282
+ if (data) {
1283
+ this.input.setInputValue(data.val);
1284
+ } else {
1285
+ this.input.resetInputValue();
1286
+ this._updateHint();
1287
+ }
1288
+ this.eventBus.trigger("cursorchange", payload);
1289
+ return true;
1290
+ }
1291
+ return false;
1292
+ },
1040
1293
  destroy: function destroy() {
1041
1294
  this.input.destroy();
1042
- this.dropdown.destroy();
1043
- destroyDomStructure(this.$node);
1044
- this.$node = null;
1295
+ this.menu.destroy();
1045
1296
  }
1046
1297
  });
1047
1298
  return Typeahead;
1048
- function buildDom(input, withHint) {
1049
- var $input, $wrapper, $dropdown, $hint;
1050
- $input = $(input);
1051
- $wrapper = $(html.wrapper).css(css.wrapper);
1052
- $dropdown = $(html.dropdown).css(css.dropdown);
1053
- $hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
1054
- $hint.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder required").prop("readonly", true).attr({
1055
- autocomplete: "off",
1056
- spellcheck: "false",
1057
- tabindex: -1
1058
- });
1059
- $input.data(attrsKey, {
1060
- dir: $input.attr("dir"),
1061
- autocomplete: $input.attr("autocomplete"),
1062
- spellcheck: $input.attr("spellcheck"),
1063
- style: $input.attr("style")
1064
- });
1065
- $input.addClass("tt-input").attr({
1066
- autocomplete: "off",
1067
- spellcheck: false
1068
- }).css(withHint ? css.input : css.inputWithNoHint);
1069
- try {
1070
- !$input.attr("dir") && $input.attr("dir", "auto");
1071
- } catch (e) {}
1072
- return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown);
1073
- }
1074
- function getBackgroundStyles($el) {
1075
- return {
1076
- backgroundAttachment: $el.css("background-attachment"),
1077
- backgroundClip: $el.css("background-clip"),
1078
- backgroundColor: $el.css("background-color"),
1079
- backgroundImage: $el.css("background-image"),
1080
- backgroundOrigin: $el.css("background-origin"),
1081
- backgroundPosition: $el.css("background-position"),
1082
- backgroundRepeat: $el.css("background-repeat"),
1083
- backgroundSize: $el.css("background-size")
1299
+ function c(ctx) {
1300
+ var methods = [].slice.call(arguments, 1);
1301
+ return function() {
1302
+ var args = [].slice.call(arguments);
1303
+ _.each(methods, function(method) {
1304
+ return ctx[method].apply(ctx, args);
1305
+ });
1084
1306
  };
1085
1307
  }
1086
- function destroyDomStructure($node) {
1087
- var $input = $node.find(".tt-input");
1088
- _.each($input.data(attrsKey), function(val, key) {
1089
- _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
1090
- });
1091
- $input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node);
1092
- $node.remove();
1093
- }
1094
1308
  }();
1095
1309
  (function() {
1096
1310
  "use strict";
1097
- var old, typeaheadKey, methods;
1311
+ var old, keys, methods;
1098
1312
  old = $.fn.typeahead;
1099
- typeaheadKey = "ttTypeahead";
1313
+ keys = {
1314
+ www: "tt-www",
1315
+ attrs: "tt-attrs",
1316
+ typeahead: "tt-typeahead"
1317
+ };
1100
1318
  methods = {
1101
1319
  initialize: function initialize(o, datasets) {
1320
+ var www;
1102
1321
  datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
1103
1322
  o = o || {};
1323
+ www = WWW(o.classNames);
1104
1324
  return this.each(attach);
1105
1325
  function attach() {
1106
- var $input = $(this), eventBus, typeahead;
1326
+ var $input, $wrapper, $hint, $menu, defaultHint, defaultMenu, eventBus, input, menu, typeahead, MenuConstructor;
1107
1327
  _.each(datasets, function(d) {
1108
1328
  d.highlight = !!o.highlight;
1109
1329
  });
1110
- typeahead = new Typeahead({
1111
- input: $input,
1112
- eventBus: eventBus = new EventBus({
1113
- el: $input
1114
- }),
1115
- withHint: _.isUndefined(o.hint) ? true : !!o.hint,
1116
- minLength: o.minLength,
1117
- autoselect: o.autoselect,
1118
- datasets: datasets
1330
+ $input = $(this);
1331
+ $wrapper = $(www.html.wrapper);
1332
+ $hint = $elOrNull(o.hint);
1333
+ $menu = $elOrNull(o.menu);
1334
+ defaultHint = o.hint !== false && !$hint;
1335
+ defaultMenu = o.menu !== false && !$menu;
1336
+ defaultHint && ($hint = buildHintFromInput($input, www));
1337
+ defaultMenu && ($menu = $(www.html.menu).css(www.css.menu));
1338
+ $hint && $hint.val("");
1339
+ $input = prepInput($input, www);
1340
+ if (defaultHint || defaultMenu) {
1341
+ $wrapper.css(www.css.wrapper);
1342
+ $input.css(defaultHint ? www.css.input : www.css.inputWithNoHint);
1343
+ $input.wrap($wrapper).parent().prepend(defaultHint ? $hint : null).append(defaultMenu ? $menu : null);
1344
+ }
1345
+ MenuConstructor = defaultMenu ? DefaultMenu : Menu;
1346
+ eventBus = new EventBus({
1347
+ el: $input
1119
1348
  });
1120
- $input.data(typeaheadKey, typeahead);
1349
+ input = new Input({
1350
+ hint: $hint,
1351
+ input: $input
1352
+ }, www);
1353
+ menu = new MenuConstructor({
1354
+ node: $menu,
1355
+ datasets: datasets
1356
+ }, www);
1357
+ typeahead = new Typeahead({
1358
+ input: input,
1359
+ menu: menu,
1360
+ eventBus: eventBus,
1361
+ minLength: o.minLength
1362
+ }, www);
1363
+ $input.data(keys.www, www);
1364
+ $input.data(keys.typeahead, typeahead);
1121
1365
  }
1122
1366
  },
1367
+ isEnabled: function isEnabled() {
1368
+ var enabled;
1369
+ ttEach(this.first(), function(t) {
1370
+ enabled = t.isEnabled();
1371
+ });
1372
+ return enabled;
1373
+ },
1374
+ enable: function enable() {
1375
+ ttEach(this, function(t) {
1376
+ t.enable();
1377
+ });
1378
+ return this;
1379
+ },
1380
+ disable: function disable() {
1381
+ ttEach(this, function(t) {
1382
+ t.disable();
1383
+ });
1384
+ return this;
1385
+ },
1386
+ isActive: function isActive() {
1387
+ var active;
1388
+ ttEach(this.first(), function(t) {
1389
+ active = t.isActive();
1390
+ });
1391
+ return active;
1392
+ },
1393
+ activate: function activate() {
1394
+ ttEach(this, function(t) {
1395
+ t.activate();
1396
+ });
1397
+ return this;
1398
+ },
1399
+ deactivate: function deactivate() {
1400
+ ttEach(this, function(t) {
1401
+ t.deactivate();
1402
+ });
1403
+ return this;
1404
+ },
1405
+ isOpen: function isOpen() {
1406
+ var open;
1407
+ ttEach(this.first(), function(t) {
1408
+ open = t.isOpen();
1409
+ });
1410
+ return open;
1411
+ },
1123
1412
  open: function open() {
1124
- return this.each(openTypeahead);
1125
- function openTypeahead() {
1126
- var $input = $(this), typeahead;
1127
- if (typeahead = $input.data(typeaheadKey)) {
1128
- typeahead.open();
1129
- }
1130
- }
1413
+ ttEach(this, function(t) {
1414
+ t.open();
1415
+ });
1416
+ return this;
1131
1417
  },
1132
1418
  close: function close() {
1133
- return this.each(closeTypeahead);
1134
- function closeTypeahead() {
1135
- var $input = $(this), typeahead;
1136
- if (typeahead = $input.data(typeaheadKey)) {
1137
- typeahead.close();
1138
- }
1139
- }
1419
+ ttEach(this, function(t) {
1420
+ t.close();
1421
+ });
1422
+ return this;
1423
+ },
1424
+ select: function select(el) {
1425
+ var success = false, $el = $(el);
1426
+ ttEach(this.first(), function(t) {
1427
+ success = t.select($el);
1428
+ });
1429
+ return success;
1430
+ },
1431
+ autocomplete: function autocomplete(el) {
1432
+ var success = false, $el = $(el);
1433
+ ttEach(this.first(), function(t) {
1434
+ success = t.autocomplete($el);
1435
+ });
1436
+ return success;
1437
+ },
1438
+ moveCursor: function moveCursoe(delta) {
1439
+ var success = false;
1440
+ ttEach(this.first(), function(t) {
1441
+ success = t.moveCursor(delta);
1442
+ });
1443
+ return success;
1140
1444
  },
1141
1445
  val: function val(newVal) {
1142
- return !arguments.length ? getVal(this.first()) : this.each(setVal);
1143
- function setVal() {
1144
- var $input = $(this), typeahead;
1145
- if (typeahead = $input.data(typeaheadKey)) {
1146
- typeahead.setVal(newVal);
1147
- }
1148
- }
1149
- function getVal($input) {
1150
- var typeahead, query;
1151
- if (typeahead = $input.data(typeaheadKey)) {
1152
- query = typeahead.getVal();
1153
- }
1446
+ var query;
1447
+ if (!arguments.length) {
1448
+ ttEach(this.first(), function(t) {
1449
+ query = t.getVal();
1450
+ });
1154
1451
  return query;
1452
+ } else {
1453
+ ttEach(this, function(t) {
1454
+ t.setVal(_.toStr(newVal));
1455
+ });
1456
+ return this;
1155
1457
  }
1156
1458
  },
1157
1459
  destroy: function destroy() {
1158
- return this.each(unattach);
1159
- function unattach() {
1160
- var $input = $(this), typeahead;
1161
- if (typeahead = $input.data(typeaheadKey)) {
1162
- typeahead.destroy();
1163
- $input.removeData(typeaheadKey);
1164
- }
1165
- }
1460
+ ttEach(this, function(typeahead, $input) {
1461
+ revert($input);
1462
+ typeahead.destroy();
1463
+ });
1464
+ return this;
1166
1465
  }
1167
1466
  };
1168
1467
  $.fn.typeahead = function(method) {
1169
- var tts;
1170
- if (methods[method] && method !== "initialize") {
1171
- tts = this.filter(function() {
1172
- return !!$(this).data(typeaheadKey);
1173
- });
1174
- return methods[method].apply(tts, [].slice.call(arguments, 1));
1468
+ if (methods[method]) {
1469
+ return methods[method].apply(this, [].slice.call(arguments, 1));
1175
1470
  } else {
1176
1471
  return methods.initialize.apply(this, arguments);
1177
1472
  }
@@ -1180,5 +1475,65 @@
1180
1475
  $.fn.typeahead = old;
1181
1476
  return this;
1182
1477
  };
1478
+ function ttEach($els, fn) {
1479
+ $els.each(function() {
1480
+ var $input = $(this), typeahead;
1481
+ (typeahead = $input.data(keys.typeahead)) && fn(typeahead, $input);
1482
+ });
1483
+ }
1484
+ function buildHintFromInput($input, www) {
1485
+ return $input.clone().addClass(www.classes.hint).removeData().css(www.css.hint).css(getBackgroundStyles($input)).prop("readonly", true).removeAttr("id name placeholder required").attr({
1486
+ autocomplete: "off",
1487
+ spellcheck: "false",
1488
+ tabindex: -1
1489
+ });
1490
+ }
1491
+ function prepInput($input, www) {
1492
+ $input.data(keys.attrs, {
1493
+ dir: $input.attr("dir"),
1494
+ autocomplete: $input.attr("autocomplete"),
1495
+ spellcheck: $input.attr("spellcheck"),
1496
+ style: $input.attr("style")
1497
+ });
1498
+ $input.addClass(www.classes.input).attr({
1499
+ autocomplete: "off",
1500
+ spellcheck: false
1501
+ });
1502
+ try {
1503
+ !$input.attr("dir") && $input.attr("dir", "auto");
1504
+ } catch (e) {}
1505
+ return $input;
1506
+ }
1507
+ function getBackgroundStyles($el) {
1508
+ return {
1509
+ backgroundAttachment: $el.css("background-attachment"),
1510
+ backgroundClip: $el.css("background-clip"),
1511
+ backgroundColor: $el.css("background-color"),
1512
+ backgroundImage: $el.css("background-image"),
1513
+ backgroundOrigin: $el.css("background-origin"),
1514
+ backgroundPosition: $el.css("background-position"),
1515
+ backgroundRepeat: $el.css("background-repeat"),
1516
+ backgroundSize: $el.css("background-size")
1517
+ };
1518
+ }
1519
+ function revert($input) {
1520
+ var www, $wrapper;
1521
+ www = $input.data(keys.www);
1522
+ $wrapper = $input.parent().filter(www.selectors.wrapper);
1523
+ _.each($input.data(keys.attrs), function(val, key) {
1524
+ _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
1525
+ });
1526
+ $input.removeData(keys.typeahead).removeData(keys.www).removeData(keys.attr).removeClass(www.classes.input);
1527
+ if ($wrapper.length) {
1528
+ $input.detach().insertAfter($wrapper);
1529
+ $wrapper.remove();
1530
+ }
1531
+ }
1532
+ function $elOrNull(obj) {
1533
+ var isValid, $el;
1534
+ isValid = _.isJQuery(obj) || _.isElement(obj);
1535
+ $el = isValid ? $(obj).first() : [];
1536
+ return $el.length ? $el : null;
1537
+ }
1183
1538
  })();
1184
- })(window.jQuery);
1539
+ });