2 Copyright (c) 2008, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
8 * The AutoComplete control provides the front-end logic for text-entry suggestion and
9 * completion functionality.
11 * @module autocomplete
12 * @requires yahoo, dom, event, datasource
13 * @optional animation, connection, get
14 * @namespace YAHOO.widget
15 * @title AutoComplete Widget
18 /****************************************************************************/
19 /****************************************************************************/
20 /****************************************************************************/
23 * The AutoComplete class provides the customizable functionality of a plug-and-play DHTML
24 * auto completion widget. Some key features:
26 * <li>Navigate with up/down arrow keys and/or mouse to pick a selection</li>
27 * <li>The drop down container can "roll down" or "fly out" via configurable
29 * <li>UI look-and-feel customizable through CSS, including container
30 * attributes, borders, position, fonts, etc</li>
35 * @param elInput {HTMLElement} DOM element reference of an input field.
36 * @param elInput {String} String ID of an input field.
37 * @param elContainer {HTMLElement} DOM element reference of an existing DIV.
38 * @param elContainer {String} String ID of an existing DIV.
39 * @param oDataSource {YAHOO.widget.DataSource} DataSource instance.
40 * @param oConfigs {Object} (optional) Object literal of configuration params.
42 YAHOO
.widget
.AutoComplete = function(elInput
,elContainer
,oDataSource
,oConfigs
) {
43 if(elInput
&& elContainer
&& oDataSource
) {
44 // Validate DataSource
45 if(oDataSource
instanceof YAHOO
.widget
.DataSource
) {
46 this.dataSource
= oDataSource
;
52 // Validate input element
53 if(YAHOO
.util
.Dom
.inDocument(elInput
)) {
54 if(YAHOO
.lang
.isString(elInput
)) {
55 this._sName
= "instance" + YAHOO
.widget
.AutoComplete
._nIndex
+ " " + elInput
;
56 this._elTextbox
= document
.getElementById(elInput
);
59 this._sName
= (elInput
.id
) ?
60 "instance" + YAHOO
.widget
.AutoComplete
._nIndex
+ " " + elInput
.id
:
61 "instance" + YAHOO
.widget
.AutoComplete
._nIndex
;
62 this._elTextbox
= elInput
;
64 YAHOO
.util
.Dom
.addClass(this._elTextbox
, "yui-ac-input");
70 // Validate container element
71 if(YAHOO
.util
.Dom
.inDocument(elContainer
)) {
72 if(YAHOO
.lang
.isString(elContainer
)) {
73 this._elContainer
= document
.getElementById(elContainer
);
76 this._elContainer
= elContainer
;
78 if(this._elContainer
.style
.display
== "none") {
82 var elParent
= this._elContainer
.parentNode
;
83 var elTag
= elParent
.tagName
.toLowerCase();
85 YAHOO
.util
.Dom
.addClass(elParent
, "yui-ac");
94 // Set any config params passed in to override defaults
95 if(oConfigs
&& (oConfigs
.constructor == Object
)) {
96 for(var sConfig
in oConfigs
) {
98 this[sConfig
] = oConfigs
[sConfig
];
103 // Initialization sequence
104 this._initContainer();
107 this._initContainerHelpers();
111 var elTextbox
= this._elTextbox
;
112 // Events are actually for the content module within the container
113 var elContent
= this._elContent
;
116 YAHOO
.util
.Event
.addListener(elTextbox
,"keyup",oSelf
._onTextboxKeyUp
,oSelf
);
117 YAHOO
.util
.Event
.addListener(elTextbox
,"keydown",oSelf
._onTextboxKeyDown
,oSelf
);
118 YAHOO
.util
.Event
.addListener(elTextbox
,"focus",oSelf
._onTextboxFocus
,oSelf
);
119 YAHOO
.util
.Event
.addListener(elTextbox
,"blur",oSelf
._onTextboxBlur
,oSelf
);
120 YAHOO
.util
.Event
.addListener(elContent
,"mouseover",oSelf
._onContainerMouseover
,oSelf
);
121 YAHOO
.util
.Event
.addListener(elContent
,"mouseout",oSelf
._onContainerMouseout
,oSelf
);
122 YAHOO
.util
.Event
.addListener(elContent
,"scroll",oSelf
._onContainerScroll
,oSelf
);
123 YAHOO
.util
.Event
.addListener(elContent
,"resize",oSelf
._onContainerResize
,oSelf
);
124 YAHOO
.util
.Event
.addListener(elTextbox
,"keypress",oSelf
._onTextboxKeyPress
,oSelf
);
125 YAHOO
.util
.Event
.addListener(window
,"unload",oSelf
._onWindowUnload
,oSelf
);
128 this.textboxFocusEvent
= new YAHOO
.util
.CustomEvent("textboxFocus", this);
129 this.textboxKeyEvent
= new YAHOO
.util
.CustomEvent("textboxKey", this);
130 this.dataRequestEvent
= new YAHOO
.util
.CustomEvent("dataRequest", this);
131 this.dataReturnEvent
= new YAHOO
.util
.CustomEvent("dataReturn", this);
132 this.dataErrorEvent
= new YAHOO
.util
.CustomEvent("dataError", this);
133 this.containerExpandEvent
= new YAHOO
.util
.CustomEvent("containerExpand", this);
134 this.typeAheadEvent
= new YAHOO
.util
.CustomEvent("typeAhead", this);
135 this.itemMouseOverEvent
= new YAHOO
.util
.CustomEvent("itemMouseOver", this);
136 this.itemMouseOutEvent
= new YAHOO
.util
.CustomEvent("itemMouseOut", this);
137 this.itemArrowToEvent
= new YAHOO
.util
.CustomEvent("itemArrowTo", this);
138 this.itemArrowFromEvent
= new YAHOO
.util
.CustomEvent("itemArrowFrom", this);
139 this.itemSelectEvent
= new YAHOO
.util
.CustomEvent("itemSelect", this);
140 this.unmatchedItemSelectEvent
= new YAHOO
.util
.CustomEvent("unmatchedItemSelect", this);
141 this.selectionEnforceEvent
= new YAHOO
.util
.CustomEvent("selectionEnforce", this);
142 this.containerCollapseEvent
= new YAHOO
.util
.CustomEvent("containerCollapse", this);
143 this.textboxBlurEvent
= new YAHOO
.util
.CustomEvent("textboxBlur", this);
146 elTextbox
.setAttribute("autocomplete","off");
147 YAHOO
.widget
.AutoComplete
._nIndex
++;
149 // Required arguments were not found
154 /////////////////////////////////////////////////////////////////////////////
156 // Public member variables
158 /////////////////////////////////////////////////////////////////////////////
161 * The DataSource object that encapsulates the data used for auto completion.
162 * This object should be an inherited object from YAHOO.widget.DataSource.
164 * @property dataSource
165 * @type YAHOO.widget.DataSource
167 YAHOO
.widget
.AutoComplete
.prototype.dataSource
= null;
170 * Number of characters that must be entered before querying for results. A negative value
171 * effectively turns off the widget. A value of 0 allows queries of null or empty string
174 * @property minQueryLength
178 YAHOO
.widget
.AutoComplete
.prototype.minQueryLength
= 1;
181 * Maximum number of results to display in results container.
183 * @property maxResultsDisplayed
187 YAHOO
.widget
.AutoComplete
.prototype.maxResultsDisplayed
= 10;
190 * Number of seconds to delay before submitting a query request. If a query
191 * request is received before a previous one has completed its delay, the
192 * previous request is cancelled and the new request is set to the delay.
193 * Implementers should take care when setting this value very low (i.e., less
194 * than 0.2) with low latency DataSources and the typeAhead feature enabled, as
195 * fast typers may see unexpected behavior.
197 * @property queryDelay
201 YAHOO
.widget
.AutoComplete
.prototype.queryDelay
= 0.2;
204 * Class name of a highlighted item within results container.
206 * @property highlightClassName
208 * @default "yui-ac-highlight"
210 YAHOO
.widget
.AutoComplete
.prototype.highlightClassName
= "yui-ac-highlight";
213 * Class name of a pre-highlighted item within results container.
215 * @property prehighlightClassName
218 YAHOO
.widget
.AutoComplete
.prototype.prehighlightClassName
= null;
221 * Query delimiter. A single character separator for multiple delimited
222 * selections. Multiple delimiter characteres may be defined as an array of
223 * strings. A null value or empty string indicates that query results cannot
224 * be delimited. This feature is not recommended if you need forceSelection to
227 * @property delimChar
228 * @type String | String[]
230 YAHOO
.widget
.AutoComplete
.prototype.delimChar
= null;
233 * Whether or not the first item in results container should be automatically highlighted
236 * @property autoHighlight
240 YAHOO
.widget
.AutoComplete
.prototype.autoHighlight
= true;
243 * Whether or not the input field should be automatically updated
244 * with the first query result as the user types, auto-selecting the substring
245 * that the user has not typed.
247 * @property typeAhead
251 YAHOO
.widget
.AutoComplete
.prototype.typeAhead
= false;
254 * Whether or not to animate the expansion/collapse of the results container in the
255 * horizontal direction.
257 * @property animHoriz
261 YAHOO
.widget
.AutoComplete
.prototype.animHoriz
= false;
264 * Whether or not to animate the expansion/collapse of the results container in the
265 * vertical direction.
271 YAHOO
.widget
.AutoComplete
.prototype.animVert
= true;
274 * Speed of container expand/collapse animation, in seconds..
276 * @property animSpeed
280 YAHOO
.widget
.AutoComplete
.prototype.animSpeed
= 0.3;
283 * Whether or not to force the user's selection to match one of the query
284 * results. Enabling this feature essentially transforms the input field into a
285 * <select> field. This feature is not recommended with delimiter character(s)
288 * @property forceSelection
292 YAHOO
.widget
.AutoComplete
.prototype.forceSelection
= false;
295 * Whether or not to allow browsers to cache user-typed input in the input
296 * field. Disabling this feature will prevent the widget from setting the
297 * autocomplete="off" on the input field. When autocomplete="off"
298 * and users click the back button after form submission, user-typed input can
299 * be prefilled by the browser from its cache. This caching of user input may
300 * not be desired for sensitive data, such as credit card numbers, in which
301 * case, implementers should consider setting allowBrowserAutocomplete to false.
303 * @property allowBrowserAutocomplete
307 YAHOO
.widget
.AutoComplete
.prototype.allowBrowserAutocomplete
= true;
310 * Whether or not the results container should always be displayed.
311 * Enabling this feature displays the container when the widget is instantiated
312 * and prevents the toggling of the container to a collapsed state.
314 * @property alwaysShowContainer
318 YAHOO
.widget
.AutoComplete
.prototype.alwaysShowContainer
= false;
321 * Whether or not to use an iFrame to layer over Windows form elements in
322 * IE. Set to true only when the results container will be on top of a
323 * <select> field in IE and thus exposed to the IE z-index bug (i.e.,
326 * @property useIFrame
330 YAHOO
.widget
.AutoComplete
.prototype.useIFrame
= false;
333 * Whether or not the results container should have a shadow.
335 * @property useShadow
339 YAHOO
.widget
.AutoComplete
.prototype.useShadow
= false;
341 /////////////////////////////////////////////////////////////////////////////
345 /////////////////////////////////////////////////////////////////////////////
348 * Public accessor to the unique name of the AutoComplete instance.
351 * @return {String} Unique name of the AutoComplete instance.
353 YAHOO
.widget
.AutoComplete
.prototype.toString = function() {
354 return "AutoComplete " + this._sName
;
358 * Returns true if container is in an expanded state, false otherwise.
360 * @method isContainerOpen
361 * @return {Boolean} Returns true if container is in an expanded state, false otherwise.
363 YAHOO
.widget
.AutoComplete
.prototype.isContainerOpen = function() {
364 return this._bContainerOpen
;
368 * Public accessor to the internal array of DOM <li> elements that
369 * display query results within the results container.
371 * @method getListItems
372 * @return {HTMLElement[]} Array of <li> elements within the results container.
374 YAHOO
.widget
.AutoComplete
.prototype.getListItems = function() {
375 return this._aListItems
;
379 * Public accessor to the data held in an <li> element of the
382 * @method getListItemData
383 * @return {Object | Object[]} Object or array of result data or null
385 YAHOO
.widget
.AutoComplete
.prototype.getListItemData = function(oListItem
) {
386 if(oListItem
._oResultData
) {
387 return oListItem
._oResultData
;
395 * Sets HTML markup for the results container header. This markup will be
396 * inserted within a <div> tag with a class of "yui-ac-hd".
399 * @param sHeader {String} HTML markup for results container header.
401 YAHOO
.widget
.AutoComplete
.prototype.setHeader = function(sHeader
) {
403 var elHeader
= this._elHeader
;
405 elHeader
.innerHTML
= sHeader
;
406 elHeader
.style
.display
= "block";
409 elHeader
.innerHTML
= "";
410 elHeader
.style
.display
= "none";
416 * Sets HTML markup for the results container footer. This markup will be
417 * inserted within a <div> tag with a class of "yui-ac-ft".
420 * @param sFooter {String} HTML markup for results container footer.
422 YAHOO
.widget
.AutoComplete
.prototype.setFooter = function(sFooter
) {
424 var elFooter
= this._elFooter
;
426 elFooter
.innerHTML
= sFooter
;
427 elFooter
.style
.display
= "block";
430 elFooter
.innerHTML
= "";
431 elFooter
.style
.display
= "none";
437 * Sets HTML markup for the results container body. This markup will be
438 * inserted within a <div> tag with a class of "yui-ac-bd".
441 * @param sBody {String} HTML markup for results container body.
443 YAHOO
.widget
.AutoComplete
.prototype.setBody = function(sBody
) {
445 var elBody
= this._elBody
;
447 elBody
.innerHTML
= sBody
;
448 elBody
.style
.display
= "block";
449 elBody
.style
.display
= "block";
452 elBody
.innerHTML
= "";
453 elBody
.style
.display
= "none";
455 this._maxResultsDisplayed
= 0;
460 * Overridable method that converts a result item object into HTML markup
461 * for display. Return data values are accessible via the oResultItem object,
462 * and the key return value will always be oResultItem[0]. Markup will be
463 * displayed within <li> element tags in the container.
465 * @method formatResult
466 * @param oResultItem {Object} Result item representing one query result. Data is held in an array.
467 * @param sQuery {String} The current query string.
468 * @return {String} HTML markup of formatted result data.
470 YAHOO
.widget
.AutoComplete
.prototype.formatResult = function(oResultItem
, sQuery
) {
471 var sResult
= oResultItem
[0];
481 * Overridable method called before container expands allows implementers to access data
484 * @method doBeforeExpandContainer
485 * @param elTextbox {HTMLElement} The text input box.
486 * @param elContainer {HTMLElement} The container element.
487 * @param sQuery {String} The query string.
488 * @param aResults {Object[]} An array of query results.
489 * @return {Boolean} Return true to continue expanding container, false to cancel the expand.
491 YAHOO
.widget
.AutoComplete
.prototype.doBeforeExpandContainer = function(elTextbox
, elContainer
, sQuery
, aResults
) {
496 * Makes query request to the DataSource.
499 * @param sQuery {String} Query string.
501 YAHOO
.widget
.AutoComplete
.prototype.sendQuery = function(sQuery
) {
502 this._sendQuery(sQuery
);
506 * Overridable method gives implementers access to the query before it gets sent.
508 * @method doBeforeSendQuery
509 * @param sQuery {String} Query string.
510 * @return {String} Query string.
512 YAHOO
.widget
.AutoComplete
.prototype.doBeforeSendQuery = function(sQuery
) {
517 * Nulls out the entire AutoComplete instance and related objects, removes attached
518 * event listeners, and clears out DOM elements inside the container. After
519 * calling this method, the instance reference should be expliclitly nulled by
520 * implementer, as in myDataTable = null. Use with caution!
524 YAHOO
.widget
.AutoComplete
.prototype.destroy = function() {
525 var instanceName
= this.toString();
526 var elInput
= this._elTextbox
;
527 var elContainer
= this._elContainer
;
529 // Unhook custom events
530 this.textboxFocusEvent
.unsubscribeAll();
531 this.textboxKeyEvent
.unsubscribeAll();
532 this.dataRequestEvent
.unsubscribeAll();
533 this.dataReturnEvent
.unsubscribeAll();
534 this.dataErrorEvent
.unsubscribeAll();
535 this.containerExpandEvent
.unsubscribeAll();
536 this.typeAheadEvent
.unsubscribeAll();
537 this.itemMouseOverEvent
.unsubscribeAll();
538 this.itemMouseOutEvent
.unsubscribeAll();
539 this.itemArrowToEvent
.unsubscribeAll();
540 this.itemArrowFromEvent
.unsubscribeAll();
541 this.itemSelectEvent
.unsubscribeAll();
542 this.unmatchedItemSelectEvent
.unsubscribeAll();
543 this.selectionEnforceEvent
.unsubscribeAll();
544 this.containerCollapseEvent
.unsubscribeAll();
545 this.textboxBlurEvent
.unsubscribeAll();
548 YAHOO
.util
.Event
.purgeElement(elInput
, true);
549 YAHOO
.util
.Event
.purgeElement(elContainer
, true);
551 // Remove DOM elements
552 elContainer
.innerHTML
= "";
555 for(var key
in this) {
556 if(YAHOO
.lang
.hasOwnProperty(this, key
)) {
563 /////////////////////////////////////////////////////////////////////////////
567 /////////////////////////////////////////////////////////////////////////////
570 * Fired when the input field receives focus.
572 * @event textboxFocusEvent
573 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
575 YAHOO
.widget
.AutoComplete
.prototype.textboxFocusEvent
= null;
578 * Fired when the input field receives key input.
580 * @event textboxKeyEvent
581 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
582 * @param nKeycode {Number} The keycode number.
584 YAHOO
.widget
.AutoComplete
.prototype.textboxKeyEvent
= null;
587 * Fired when the AutoComplete instance makes a query to the DataSource.
589 * @event dataRequestEvent
590 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
591 * @param sQuery {String} The query string.
593 YAHOO
.widget
.AutoComplete
.prototype.dataRequestEvent
= null;
596 * Fired when the AutoComplete instance receives query results from the data
599 * @event dataReturnEvent
600 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
601 * @param sQuery {String} The query string.
602 * @param aResults {Object[]} Results array.
604 YAHOO
.widget
.AutoComplete
.prototype.dataReturnEvent
= null;
607 * Fired when the AutoComplete instance does not receive query results from the
608 * DataSource due to an error.
610 * @event dataErrorEvent
611 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
612 * @param sQuery {String} The query string.
614 YAHOO
.widget
.AutoComplete
.prototype.dataErrorEvent
= null;
617 * Fired when the results container is expanded.
619 * @event containerExpandEvent
620 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
622 YAHOO
.widget
.AutoComplete
.prototype.containerExpandEvent
= null;
625 * Fired when the input field has been prefilled by the type-ahead
628 * @event typeAheadEvent
629 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
630 * @param sQuery {String} The query string.
631 * @param sPrefill {String} The prefill string.
633 YAHOO
.widget
.AutoComplete
.prototype.typeAheadEvent
= null;
636 * Fired when result item has been moused over.
638 * @event itemMouseOverEvent
639 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
640 * @param elItem {HTMLElement} The <li> element item moused to.
642 YAHOO
.widget
.AutoComplete
.prototype.itemMouseOverEvent
= null;
645 * Fired when result item has been moused out.
647 * @event itemMouseOutEvent
648 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
649 * @param elItem {HTMLElement} The <li> element item moused from.
651 YAHOO
.widget
.AutoComplete
.prototype.itemMouseOutEvent
= null;
654 * Fired when result item has been arrowed to.
656 * @event itemArrowToEvent
657 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
658 * @param elItem {HTMLElement} The <li> element item arrowed to.
660 YAHOO
.widget
.AutoComplete
.prototype.itemArrowToEvent
= null;
663 * Fired when result item has been arrowed away from.
665 * @event itemArrowFromEvent
666 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
667 * @param elItem {HTMLElement} The <li> element item arrowed from.
669 YAHOO
.widget
.AutoComplete
.prototype.itemArrowFromEvent
= null;
672 * Fired when an item is selected via mouse click, ENTER key, or TAB key.
674 * @event itemSelectEvent
675 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
676 * @param elItem {HTMLElement} The selected <li> element item.
677 * @param oData {Object} The data returned for the item, either as an object,
678 * or mapped from the schema into an array.
680 YAHOO
.widget
.AutoComplete
.prototype.itemSelectEvent
= null;
683 * Fired when a user selection does not match any of the displayed result items.
685 * @event unmatchedItemSelectEvent
686 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
688 YAHOO
.widget
.AutoComplete
.prototype.unmatchedItemSelectEvent
= null;
691 * Fired if forceSelection is enabled and the user's input has been cleared
692 * because it did not match one of the returned query results.
694 * @event selectionEnforceEvent
695 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
697 YAHOO
.widget
.AutoComplete
.prototype.selectionEnforceEvent
= null;
700 * Fired when the results container is collapsed.
702 * @event containerCollapseEvent
703 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
705 YAHOO
.widget
.AutoComplete
.prototype.containerCollapseEvent
= null;
708 * Fired when the input field loses focus.
710 * @event textboxBlurEvent
711 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
713 YAHOO
.widget
.AutoComplete
.prototype.textboxBlurEvent
= null;
715 /////////////////////////////////////////////////////////////////////////////
717 // Private member variables
719 /////////////////////////////////////////////////////////////////////////////
722 * Internal class variable to index multiple AutoComplete instances.
729 YAHOO
.widget
.AutoComplete
._nIndex
= 0;
732 * Name of AutoComplete instance.
738 YAHOO
.widget
.AutoComplete
.prototype._sName
= null;
741 * Text input field DOM element.
743 * @property _elTextbox
747 YAHOO
.widget
.AutoComplete
.prototype._elTextbox
= null;
750 * Container DOM element.
752 * @property _elContainer
756 YAHOO
.widget
.AutoComplete
.prototype._elContainer
= null;
759 * Reference to content element within container element.
761 * @property _elContent
765 YAHOO
.widget
.AutoComplete
.prototype._elContent
= null;
768 * Reference to header element within content element.
770 * @property _elHeader
774 YAHOO
.widget
.AutoComplete
.prototype._elHeader
= null;
777 * Reference to body element within content element.
783 YAHOO
.widget
.AutoComplete
.prototype._elBody
= null;
786 * Reference to footer element within content element.
788 * @property _elFooter
792 YAHOO
.widget
.AutoComplete
.prototype._elFooter
= null;
795 * Reference to shadow element within container element.
797 * @property _elShadow
801 YAHOO
.widget
.AutoComplete
.prototype._elShadow
= null;
804 * Reference to iframe element within container element.
806 * @property _elIFrame
810 YAHOO
.widget
.AutoComplete
.prototype._elIFrame
= null;
813 * Whether or not the input field is currently in focus. If query results come back
814 * but the user has already moved on, do not proceed with auto complete behavior.
816 * @property _bFocused
820 YAHOO
.widget
.AutoComplete
.prototype._bFocused
= true;
823 * Animation instance for container expand/collapse.
829 YAHOO
.widget
.AutoComplete
.prototype._oAnim
= null;
832 * Whether or not the results container is currently open.
834 * @property _bContainerOpen
838 YAHOO
.widget
.AutoComplete
.prototype._bContainerOpen
= false;
841 * Whether or not the mouse is currently over the results
842 * container. This is necessary in order to prevent clicks on container items
843 * from being text input field blur events.
845 * @property _bOverContainer
849 YAHOO
.widget
.AutoComplete
.prototype._bOverContainer
= false;
852 * Array of <li> elements references that contain query results within the
855 * @property _aListItems
856 * @type HTMLElement[]
859 YAHOO
.widget
.AutoComplete
.prototype._aListItems
= null;
862 * Number of <li> elements currently displayed in results container.
864 * @property _nDisplayedItems
868 YAHOO
.widget
.AutoComplete
.prototype._nDisplayedItems
= 0;
871 * Internal count of <li> elements displayed and hidden in results container.
873 * @property _maxResultsDisplayed
877 YAHOO
.widget
.AutoComplete
.prototype._maxResultsDisplayed
= 0;
880 * Current query string
882 * @property _sCurQuery
886 YAHOO
.widget
.AutoComplete
.prototype._sCurQuery
= null;
889 * Past queries this session (for saving delimited queries).
891 * @property _sSavedQuery
895 YAHOO
.widget
.AutoComplete
.prototype._sSavedQuery
= null;
898 * Pointer to the currently highlighted <li> element in the container.
900 * @property _oCurItem
904 YAHOO
.widget
.AutoComplete
.prototype._oCurItem
= null;
907 * Whether or not an item has been selected since the container was populated
908 * with results. Reset to false by _populateList, and set to true when item is
911 * @property _bItemSelected
915 YAHOO
.widget
.AutoComplete
.prototype._bItemSelected
= false;
918 * Key code of the last key pressed in textbox.
920 * @property _nKeyCode
924 YAHOO
.widget
.AutoComplete
.prototype._nKeyCode
= null;
929 * @property _nDelayID
933 YAHOO
.widget
.AutoComplete
.prototype._nDelayID
= -1;
936 * Src to iFrame used when useIFrame = true. Supports implementations over SSL
939 * @property _iFrameSrc
943 YAHOO
.widget
.AutoComplete
.prototype._iFrameSrc
= "javascript:false;";
946 * For users typing via certain IMEs, queries must be triggered by intervals,
947 * since key events yet supported across all browsers for all IMEs.
949 * @property _queryInterval
953 YAHOO
.widget
.AutoComplete
.prototype._queryInterval
= null;
956 * Internal tracker to last known textbox value, used to determine whether or not
957 * to trigger a query via interval for certain IME users.
959 * @event _sLastTextboxValue
963 YAHOO
.widget
.AutoComplete
.prototype._sLastTextboxValue
= null;
965 /////////////////////////////////////////////////////////////////////////////
969 /////////////////////////////////////////////////////////////////////////////
972 * Updates and validates latest public config properties.
974 * @method __initProps
977 YAHOO
.widget
.AutoComplete
.prototype._initProps = function() {
978 // Correct any invalid values
979 var minQueryLength
= this.minQueryLength
;
980 if(!YAHOO
.lang
.isNumber(minQueryLength
)) {
981 this.minQueryLength
= 1;
983 var maxResultsDisplayed
= this.maxResultsDisplayed
;
984 if(!YAHOO
.lang
.isNumber(maxResultsDisplayed
) || (maxResultsDisplayed
< 1)) {
985 this.maxResultsDisplayed
= 10;
987 var queryDelay
= this.queryDelay
;
988 if(!YAHOO
.lang
.isNumber(queryDelay
) || (queryDelay
< 0)) {
989 this.queryDelay
= 0.2;
991 var delimChar
= this.delimChar
;
992 if(YAHOO
.lang
.isString(delimChar
) && (delimChar
.length
> 0)) {
993 this.delimChar
= [delimChar
];
995 else if(!YAHOO
.lang
.isArray(delimChar
)) {
996 this.delimChar
= null;
998 var animSpeed
= this.animSpeed
;
999 if((this.animHoriz
|| this.animVert
) && YAHOO
.util
.Anim
) {
1000 if(!YAHOO
.lang
.isNumber(animSpeed
) || (animSpeed
< 0)) {
1001 this.animSpeed
= 0.3;
1004 this._oAnim
= new YAHOO
.util
.Anim(this._elContent
, {}, this.animSpeed
);
1007 this._oAnim
.duration
= this.animSpeed
;
1010 if(this.forceSelection
&& delimChar
) {
1015 * Initializes the results container helpers if they are enabled and do
1018 * @method _initContainerHelpers
1021 YAHOO
.widget
.AutoComplete
.prototype._initContainerHelpers = function() {
1022 if(this.useShadow
&& !this._elShadow
) {
1023 var elShadow
= document
.createElement("div");
1024 elShadow
.className
= "yui-ac-shadow";
1025 this._elShadow
= this._elContainer
.appendChild(elShadow
);
1027 if(this.useIFrame
&& !this._elIFrame
) {
1028 var elIFrame
= document
.createElement("iframe");
1029 elIFrame
.src
= this._iFrameSrc
;
1030 elIFrame
.frameBorder
= 0;
1031 elIFrame
.scrolling
= "no";
1032 elIFrame
.style
.position
= "absolute";
1033 elIFrame
.style
.width
= "100%";
1034 elIFrame
.style
.height
= "100%";
1035 elIFrame
.tabIndex
= -1;
1036 this._elIFrame
= this._elContainer
.appendChild(elIFrame
);
1041 * Initializes the results container once at object creation
1043 * @method _initContainer
1046 YAHOO
.widget
.AutoComplete
.prototype._initContainer = function() {
1047 YAHOO
.util
.Dom
.addClass(this._elContainer
, "yui-ac-container");
1049 if(!this._elContent
) {
1050 // The elContent div helps size the iframe and shadow properly
1051 var elContent
= document
.createElement("div");
1052 elContent
.className
= "yui-ac-content";
1053 elContent
.style
.display
= "none";
1054 this._elContent
= this._elContainer
.appendChild(elContent
);
1056 var elHeader
= document
.createElement("div");
1057 elHeader
.className
= "yui-ac-hd";
1058 elHeader
.style
.display
= "none";
1059 this._elHeader
= this._elContent
.appendChild(elHeader
);
1061 var elBody
= document
.createElement("div");
1062 elBody
.className
= "yui-ac-bd";
1063 this._elBody
= this._elContent
.appendChild(elBody
);
1065 var elFooter
= document
.createElement("div");
1066 elFooter
.className
= "yui-ac-ft";
1067 elFooter
.style
.display
= "none";
1068 this._elFooter
= this._elContent
.appendChild(elFooter
);
1075 * Clears out contents of container body and creates up to
1076 * YAHOO.widget.AutoComplete#maxResultsDisplayed <li> elements in an
1077 * <ul> element.
1082 YAHOO
.widget
.AutoComplete
.prototype._initList = function() {
1083 this._aListItems
= [];
1084 while(this._elBody
.hasChildNodes()) {
1085 var oldListItems
= this.getListItems();
1087 for(var oldi
= oldListItems
.length
-1; oldi
>= 0; oldi
--) {
1088 oldListItems
[oldi
] = null;
1091 this._elBody
.innerHTML
= "";
1094 var oList
= document
.createElement("ul");
1095 oList
= this._elBody
.appendChild(oList
);
1096 for(var i
=0; i
<this.maxResultsDisplayed
; i
++) {
1097 var oItem
= document
.createElement("li");
1098 oItem
= oList
.appendChild(oItem
);
1099 this._aListItems
[i
] = oItem
;
1100 this._initListItem(oItem
, i
);
1102 this._maxResultsDisplayed
= this.maxResultsDisplayed
;
1106 * Initializes each <li> element in the container list.
1108 * @method _initListItem
1109 * @param oItem {HTMLElement} The <li> DOM element.
1110 * @param nItemIndex {Number} The index of the element.
1113 YAHOO
.widget
.AutoComplete
.prototype._initListItem = function(oItem
, nItemIndex
) {
1115 oItem
.style
.display
= "none";
1116 oItem
._nItemIndex
= nItemIndex
;
1118 oItem
.mouseover
= oItem
.mouseout
= oItem
.onclick
= null;
1119 YAHOO
.util
.Event
.addListener(oItem
,"mouseover",oSelf
._onItemMouseover
,oSelf
);
1120 YAHOO
.util
.Event
.addListener(oItem
,"mouseout",oSelf
._onItemMouseout
,oSelf
);
1121 YAHOO
.util
.Event
.addListener(oItem
,"click",oSelf
._onItemMouseclick
,oSelf
);
1125 * Enables interval detection for Korean IME support.
1127 * @method _onIMEDetected
1128 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
1131 YAHOO
.widget
.AutoComplete
.prototype._onIMEDetected = function(oSelf
) {
1132 oSelf
._enableIntervalDetection();
1136 * Enables query triggers based on text input detection by intervals (rather
1137 * than by key events).
1139 * @method _enableIntervalDetection
1142 YAHOO
.widget
.AutoComplete
.prototype._enableIntervalDetection = function() {
1143 var currValue
= this._elTextbox
.value
;
1144 var lastValue
= this._sLastTextboxValue
;
1145 if(currValue
!= lastValue
) {
1146 this._sLastTextboxValue
= currValue
;
1147 this._sendQuery(currValue
);
1153 * Cancels text input detection by intervals.
1155 * @method _cancelIntervalDetection
1156 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
1159 YAHOO
.widget
.AutoComplete
.prototype._cancelIntervalDetection = function(oSelf
) {
1160 if(oSelf
._queryInterval
) {
1161 clearInterval(oSelf
._queryInterval
);
1167 * Whether or not key is functional or should be ignored. Note that the right
1168 * arrow key is NOT an ignored key since it triggers queries for certain intl
1171 * @method _isIgnoreKey
1172 * @param nKeycode {Number} Code of key pressed.
1173 * @return {Boolean} True if key should be ignored, false otherwise.
1176 YAHOO
.widget
.AutoComplete
.prototype._isIgnoreKey = function(nKeyCode
) {
1177 if((nKeyCode
== 9) || (nKeyCode
== 13) || // tab, enter
1178 (nKeyCode
== 16) || (nKeyCode
== 17) || // shift, ctl
1179 (nKeyCode
>= 18 && nKeyCode
<= 20) || // alt,pause/break,caps lock
1180 (nKeyCode
== 27) || // esc
1181 (nKeyCode
>= 33 && nKeyCode
<= 35) || // page up,page down,end
1182 /*(nKeyCode >= 36 && nKeyCode <= 38) || // home,left,up
1183 (nKeyCode == 40) || // down*/
1184 (nKeyCode
>= 36 && nKeyCode
<= 40) || // home,left,up, right, down
1185 (nKeyCode
>= 44 && nKeyCode
<= 45)) { // print screen,insert
1192 * Makes query request to the DataSource.
1194 * @method _sendQuery
1195 * @param sQuery {String} Query string.
1198 YAHOO
.widget
.AutoComplete
.prototype._sendQuery = function(sQuery
) {
1199 // Widget has been effectively turned off
1200 if(this.minQueryLength
== -1) {
1201 this._toggleContainer(false);
1204 // Delimiter has been enabled
1205 var aDelimChar
= (this.delimChar
) ? this.delimChar
: null;
1207 // Loop through all possible delimiters and find the latest one
1208 // A " " may be a false positive if they are defined as delimiters AND
1209 // are used to separate delimited queries
1210 var nDelimIndex
= -1;
1211 for(var i
= aDelimChar
.length
-1; i
>= 0; i
--) {
1212 var nNewIndex
= sQuery
.lastIndexOf(aDelimChar
[i
]);
1213 if(nNewIndex
> nDelimIndex
) {
1214 nDelimIndex
= nNewIndex
;
1217 // If we think the last delimiter is a space (" "), make sure it is NOT
1218 // a false positive by also checking the char directly before it
1219 if(aDelimChar
[i
] == " ") {
1220 for (var j
= aDelimChar
.length
-1; j
>= 0; j
--) {
1221 if(sQuery
[nDelimIndex
- 1] == aDelimChar
[j
]) {
1227 // A delimiter has been found so extract the latest query
1228 if(nDelimIndex
> -1) {
1229 var nQueryStart
= nDelimIndex
+ 1;
1230 // Trim any white space from the beginning...
1231 while(sQuery
.charAt(nQueryStart
) == " ") {
1234 // ...and save the rest of the string for later
1235 this._sSavedQuery
= sQuery
.substring(0,nQueryStart
);
1236 // Here is the query itself
1237 sQuery
= sQuery
.substr(nQueryStart
);
1239 else if(sQuery
.indexOf(this._sSavedQuery
) < 0){
1240 this._sSavedQuery
= null;
1244 // Don't search queries that are too short
1245 if((sQuery
&& (sQuery
.length
< this.minQueryLength
)) || (!sQuery
&& this.minQueryLength
> 0)) {
1246 if(this._nDelayID
!= -1) {
1247 clearTimeout(this._nDelayID
);
1249 this._toggleContainer(false);
1253 sQuery
= encodeURIComponent(sQuery
);
1254 this._nDelayID
= -1; // Reset timeout ID because request has been made
1255 sQuery
= this.doBeforeSendQuery(sQuery
);
1256 this.dataRequestEvent
.fire(this, sQuery
);
1257 this.dataSource
.getResults(this._populateList
, sQuery
, this);
1261 * Populates the array of <li> elements in the container with query
1262 * results. This method is passed to YAHOO.widget.DataSource#getResults as a
1263 * callback function so results from the DataSource instance are returned to the
1264 * AutoComplete instance.
1266 * @method _populateList
1267 * @param sQuery {String} The query string.
1268 * @param aResults {Object[]} An array of query result objects from the DataSource.
1269 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
1272 YAHOO
.widget
.AutoComplete
.prototype._populateList = function(sQuery
, aResults
, oSelf
) {
1273 if(aResults
=== null) {
1274 oSelf
.dataErrorEvent
.fire(oSelf
, sQuery
);
1276 if(!oSelf
._bFocused
|| !aResults
) {
1280 var isOpera
= (navigator
.userAgent
.toLowerCase().indexOf("opera") != -1);
1281 var contentStyle
= oSelf
._elContent
.style
;
1282 contentStyle
.width
= (!isOpera
) ? null : "";
1283 contentStyle
.height
= (!isOpera
) ? null : "";
1285 var sCurQuery
= decodeURIComponent(sQuery
);
1286 oSelf
._sCurQuery
= sCurQuery
;
1287 oSelf
._bItemSelected
= false;
1289 if(oSelf
._maxResultsDisplayed
!= oSelf
.maxResultsDisplayed
) {
1293 var nItems
= Math
.min(aResults
.length
,oSelf
.maxResultsDisplayed
);
1294 oSelf
._nDisplayedItems
= nItems
;
1296 oSelf
._initContainerHelpers();
1297 var aItems
= oSelf
._aListItems
;
1299 // Fill items with data
1300 for(var i
= nItems
-1; i
>= 0; i
--) {
1301 var oItemi
= aItems
[i
];
1302 var oResultItemi
= aResults
[i
];
1303 oItemi
.innerHTML
= oSelf
.formatResult(oResultItemi
, sCurQuery
);
1304 oItemi
.style
.display
= "list-item";
1305 oItemi
._sResultKey
= oResultItemi
[0];
1306 oItemi
._oResultData
= oResultItemi
;
1310 // Empty out remaining items if any
1311 for(var j
= aItems
.length
-1; j
>= nItems
; j
--) {
1312 var oItemj
= aItems
[j
];
1313 oItemj
.innerHTML
= null;
1314 oItemj
.style
.display
= "none";
1315 oItemj
._sResultKey
= null;
1316 oItemj
._oResultData
= null;
1319 // Expand the container
1320 var ok
= oSelf
.doBeforeExpandContainer(oSelf
._elTextbox
, oSelf
._elContainer
, sQuery
, aResults
);
1321 oSelf
._toggleContainer(ok
);
1323 if(oSelf
.autoHighlight
) {
1324 // Go to the first item
1325 var oFirstItem
= aItems
[0];
1326 oSelf
._toggleHighlight(oFirstItem
,"to");
1327 oSelf
.itemArrowToEvent
.fire(oSelf
, oFirstItem
);
1328 oSelf
._typeAhead(oFirstItem
,sQuery
);
1331 oSelf
._oCurItem
= null;
1335 oSelf
._toggleContainer(false);
1337 oSelf
.dataReturnEvent
.fire(oSelf
, sQuery
, aResults
);
1342 * When forceSelection is true and the user attempts
1343 * leave the text input box without selecting an item from the query results,
1344 * the user selection is cleared.
1346 * @method _clearSelection
1349 YAHOO
.widget
.AutoComplete
.prototype._clearSelection = function() {
1350 var sValue
= this._elTextbox
.value
;
1351 var sChar
= (this.delimChar
) ? this.delimChar
[0] : null;
1352 var nIndex
= (sChar
) ? sValue
.lastIndexOf(sChar
, sValue
.length
-2) : -1;
1354 this._elTextbox
.value
= sValue
.substring(0,nIndex
);
1357 this._elTextbox
.value
= "";
1359 this._sSavedQuery
= this._elTextbox
.value
;
1361 // Fire custom event
1362 this.selectionEnforceEvent
.fire(this);
1366 * Whether or not user-typed value in the text input box matches any of the
1369 * @method _textMatchesOption
1370 * @return {HTMLElement} Matching list item element if user-input text matches
1371 * a result, null otherwise.
1374 YAHOO
.widget
.AutoComplete
.prototype._textMatchesOption = function() {
1375 var foundMatch
= null;
1377 for(var i
= this._nDisplayedItems
-1; i
>= 0 ; i
--) {
1378 var oItem
= this._aListItems
[i
];
1379 var sMatch
= oItem
._sResultKey
.toLowerCase();
1380 if(sMatch
== this._sCurQuery
.toLowerCase()) {
1389 * Updates in the text input box with the first query result as the user types,
1390 * selecting the substring that the user has not typed.
1392 * @method _typeAhead
1393 * @param oItem {HTMLElement} The <li> element item whose data populates the input field.
1394 * @param sQuery {String} Query string.
1397 YAHOO
.widget
.AutoComplete
.prototype._typeAhead = function(oItem
, sQuery
) {
1398 // Don't update if turned off
1399 if(!this.typeAhead
|| (this._nKeyCode
== 8)) {
1403 var elTextbox
= this._elTextbox
;
1404 var sValue
= this._elTextbox
.value
; // any saved queries plus what user has typed
1406 // Don't update with type-ahead if text selection is not supported
1407 if(!elTextbox
.setSelectionRange
&& !elTextbox
.createTextRange
) {
1411 // Select the portion of text that the user has not typed
1412 var nStart
= sValue
.length
;
1413 this._updateValue(oItem
);
1414 var nEnd
= elTextbox
.value
.length
;
1415 this._selectText(elTextbox
,nStart
,nEnd
);
1416 var sPrefill
= elTextbox
.value
.substr(nStart
,nEnd
);
1417 this.typeAheadEvent
.fire(this,sQuery
,sPrefill
);
1421 * Selects text in the input field.
1423 * @method _selectText
1424 * @param elTextbox {HTMLElement} Text input box element in which to select text.
1425 * @param nStart {Number} Starting index of text string to select.
1426 * @param nEnd {Number} Ending index of text selection.
1429 YAHOO
.widget
.AutoComplete
.prototype._selectText = function(elTextbox
, nStart
, nEnd
) {
1430 if(elTextbox
.setSelectionRange
) { // For Mozilla
1431 elTextbox
.setSelectionRange(nStart
,nEnd
);
1433 else if(elTextbox
.createTextRange
) { // For IE
1434 var oTextRange
= elTextbox
.createTextRange();
1435 oTextRange
.moveStart("character", nStart
);
1436 oTextRange
.moveEnd("character", nEnd
-elTextbox
.value
.length
);
1437 oTextRange
.select();
1445 * Syncs results container with its helpers.
1447 * @method _toggleContainerHelpers
1448 * @param bShow {Boolean} True if container is expanded, false if collapsed
1451 YAHOO
.widget
.AutoComplete
.prototype._toggleContainerHelpers = function(bShow
) {
1452 var bFireEvent
= false;
1453 var width
= this._elContent
.offsetWidth
+ "px";
1454 var height
= this._elContent
.offsetHeight
+ "px";
1456 if(this.useIFrame
&& this._elIFrame
) {
1459 this._elIFrame
.style
.width
= width
;
1460 this._elIFrame
.style
.height
= height
;
1463 this._elIFrame
.style
.width
= 0;
1464 this._elIFrame
.style
.height
= 0;
1467 if(this.useShadow
&& this._elShadow
) {
1470 this._elShadow
.style
.width
= width
;
1471 this._elShadow
.style
.height
= height
;
1474 this._elShadow
.style
.width
= 0;
1475 this._elShadow
.style
.height
= 0;
1481 * Animates expansion or collapse of the container.
1483 * @method _toggleContainer
1484 * @param bShow {Boolean} True if container should be expanded, false if container should be collapsed
1487 YAHOO
.widget
.AutoComplete
.prototype._toggleContainer = function(bShow
) {
1488 var elContainer
= this._elContainer
;
1490 // Implementer has container always open so don't mess with it
1491 if(this.alwaysShowContainer
&& this._bContainerOpen
) {
1495 // Clear contents of container
1497 this._elContent
.scrollTop
= 0;
1498 var aItems
= this._aListItems
;
1500 if(aItems
&& (aItems
.length
> 0)) {
1501 for(var i
= aItems
.length
-1; i
>= 0 ; i
--) {
1502 aItems
[i
].style
.display
= "none";
1506 if(this._oCurItem
) {
1507 this._toggleHighlight(this._oCurItem
,"from");
1510 this._oCurItem
= null;
1511 this._nDisplayedItems
= 0;
1512 this._sCurQuery
= null;
1515 // Container is already closed
1516 if(!bShow
&& !this._bContainerOpen
) {
1517 this._elContent
.style
.display
= "none";
1521 // If animation is enabled...
1522 var oAnim
= this._oAnim
;
1523 if(oAnim
&& oAnim
.getEl() && (this.animHoriz
|| this.animVert
)) {
1524 // If helpers need to be collapsed, do it right away...
1525 // but if helpers need to be expanded, wait until after the container expands
1527 this._toggleContainerHelpers(bShow
);
1530 if(oAnim
.isAnimated()) {
1534 // Clone container to grab current size offscreen
1535 var oClone
= this._elContent
.cloneNode(true);
1536 elContainer
.appendChild(oClone
);
1537 oClone
.style
.top
= "-9000px";
1538 oClone
.style
.display
= "block";
1540 // Current size of the container is the EXPANDED size
1541 var wExp
= oClone
.offsetWidth
;
1542 var hExp
= oClone
.offsetHeight
;
1544 // Calculate COLLAPSED sizes based on horiz and vert anim
1545 var wColl
= (this.animHoriz
) ? 0 : wExp
;
1546 var hColl
= (this.animVert
) ? 0 : hExp
;
1548 // Set animation sizes
1549 oAnim
.attributes
= (bShow
) ?
1550 {width
: { to
: wExp
}, height
: { to
: hExp
}} :
1551 {width
: { to
: wColl
}, height
: { to
: hColl
}};
1553 // If opening anew, set to a collapsed size...
1554 if(bShow
&& !this._bContainerOpen
) {
1555 this._elContent
.style
.width
= wColl
+"px";
1556 this._elContent
.style
.height
= hColl
+"px";
1558 // Else, set it to its last known size.
1560 this._elContent
.style
.width
= wExp
+"px";
1561 this._elContent
.style
.height
= hExp
+"px";
1564 elContainer
.removeChild(oClone
);
1568 var onAnimComplete = function() {
1569 // Finish the collapse
1570 oAnim
.onComplete
.unsubscribeAll();
1573 oSelf
.containerExpandEvent
.fire(oSelf
);
1576 oSelf
._elContent
.style
.display
= "none";
1577 oSelf
.containerCollapseEvent
.fire(oSelf
);
1579 oSelf
._toggleContainerHelpers(bShow
);
1582 // Display container and animate it
1583 this._elContent
.style
.display
= "block";
1584 oAnim
.onComplete
.subscribe(onAnimComplete
);
1586 this._bContainerOpen
= bShow
;
1588 // Else don't animate, just show or hide
1591 this._elContent
.style
.display
= "block";
1592 this.containerExpandEvent
.fire(this);
1595 this._elContent
.style
.display
= "none";
1596 this.containerCollapseEvent
.fire(this);
1598 this._toggleContainerHelpers(bShow
);
1599 this._bContainerOpen
= bShow
;
1605 * Toggles the highlight on or off for an item in the container, and also cleans
1606 * up highlighting of any previous item.
1608 * @method _toggleHighlight
1609 * @param oNewItem {HTMLElement} The <li> element item to receive highlight behavior.
1610 * @param sType {String} Type "mouseover" will toggle highlight on, and "mouseout" will toggle highlight off.
1613 YAHOO
.widget
.AutoComplete
.prototype._toggleHighlight = function(oNewItem
, sType
) {
1614 var sHighlight
= this.highlightClassName
;
1615 if(this._oCurItem
) {
1616 // Remove highlight from old item
1617 YAHOO
.util
.Dom
.removeClass(this._oCurItem
, sHighlight
);
1620 if((sType
== "to") && sHighlight
) {
1621 // Apply highlight to new item
1622 YAHOO
.util
.Dom
.addClass(oNewItem
, sHighlight
);
1623 this._oCurItem
= oNewItem
;
1628 * Toggles the pre-highlight on or off for an item in the container.
1630 * @method _togglePrehighlight
1631 * @param oNewItem {HTMLElement} The <li> element item to receive highlight behavior.
1632 * @param sType {String} Type "mouseover" will toggle highlight on, and "mouseout" will toggle highlight off.
1635 YAHOO
.widget
.AutoComplete
.prototype._togglePrehighlight = function(oNewItem
, sType
) {
1636 if(oNewItem
== this._oCurItem
) {
1640 var sPrehighlight
= this.prehighlightClassName
;
1641 if((sType
== "mouseover") && sPrehighlight
) {
1642 // Apply prehighlight to new item
1643 YAHOO
.util
.Dom
.addClass(oNewItem
, sPrehighlight
);
1646 // Remove prehighlight from old item
1647 YAHOO
.util
.Dom
.removeClass(oNewItem
, sPrehighlight
);
1652 * Updates the text input box value with selected query result. If a delimiter
1653 * has been defined, then the value gets appended with the delimiter.
1655 * @method _updateValue
1656 * @param oItem {HTMLElement} The <li> element item with which to update the value.
1659 YAHOO
.widget
.AutoComplete
.prototype._updateValue = function(oItem
) {
1660 var elTextbox
= this._elTextbox
;
1661 var sDelimChar
= (this.delimChar
) ? (this.delimChar
[0] || this.delimChar
) : null;
1662 var sSavedQuery
= this._sSavedQuery
;
1663 var sResultKey
= oItem
._sResultKey
;
1666 // First clear text field
1667 elTextbox
.value
= "";
1668 // Grab data to put into text field
1671 elTextbox
.value
= sSavedQuery
;
1673 elTextbox
.value
+= sResultKey
+ sDelimChar
;
1674 if(sDelimChar
!= " ") {
1675 elTextbox
.value
+= " ";
1678 else { elTextbox
.value
= sResultKey
; }
1680 // scroll to bottom of textarea if necessary
1681 if(elTextbox
.type
== "textarea") {
1682 elTextbox
.scrollTop
= elTextbox
.scrollHeight
;
1685 // move cursor to end
1686 var end
= elTextbox
.value
.length
;
1687 this._selectText(elTextbox
,end
,end
);
1689 this._oCurItem
= oItem
;
1693 * Selects a result item from the container
1695 * @method _selectItem
1696 * @param oItem {HTMLElement} The selected <li> element item.
1699 YAHOO
.widget
.AutoComplete
.prototype._selectItem = function(oItem
) {
1700 this._bItemSelected
= true;
1701 this._updateValue(oItem
);
1702 this._cancelIntervalDetection(this);
1703 this.itemSelectEvent
.fire(this, oItem
, oItem
._oResultData
);
1704 this._toggleContainer(false);
1708 * If an item is highlighted in the container, the right arrow key jumps to the
1709 * end of the textbox and selects the highlighted item, otherwise the container
1712 * @method _jumpSelection
1715 YAHOO
.widget
.AutoComplete
.prototype._jumpSelection = function() {
1716 if(this._oCurItem
) {
1717 this._selectItem(this._oCurItem
);
1720 this._toggleContainer(false);
1725 * Triggered by up and down arrow keys, changes the current highlighted
1726 * <li> element item. Scrolls container if necessary.
1728 * @method _moveSelection
1729 * @param nKeyCode {Number} Code of key pressed.
1732 YAHOO
.widget
.AutoComplete
.prototype._moveSelection = function(nKeyCode
) {
1733 if(this._bContainerOpen
) {
1734 // Determine current item's id number
1735 var oCurItem
= this._oCurItem
;
1736 var nCurItemIndex
= -1;
1739 nCurItemIndex
= oCurItem
._nItemIndex
;
1742 var nNewItemIndex
= (nKeyCode
== 40) ?
1743 (nCurItemIndex
+ 1) : (nCurItemIndex
- 1);
1746 if(nNewItemIndex
< -2 || nNewItemIndex
>= this._nDisplayedItems
) {
1751 // Unhighlight current item
1752 this._toggleHighlight(oCurItem
, "from");
1753 this.itemArrowFromEvent
.fire(this, oCurItem
);
1755 if(nNewItemIndex
== -1) {
1756 // Go back to query (remove type-ahead string)
1757 if(this.delimChar
&& this._sSavedQuery
) {
1758 if(!this._textMatchesOption()) {
1759 this._elTextbox
.value
= this._sSavedQuery
;
1762 this._elTextbox
.value
= this._sSavedQuery
+ this._sCurQuery
;
1766 this._elTextbox
.value
= this._sCurQuery
;
1768 this._oCurItem
= null;
1771 if(nNewItemIndex
== -2) {
1773 this._toggleContainer(false);
1777 var oNewItem
= this._aListItems
[nNewItemIndex
];
1779 // Scroll the container if necessary
1780 var elContent
= this._elContent
;
1781 var scrollOn
= ((YAHOO
.util
.Dom
.getStyle(elContent
,"overflow") == "auto") ||
1782 (YAHOO
.util
.Dom
.getStyle(elContent
,"overflowY") == "auto"));
1783 if(scrollOn
&& (nNewItemIndex
> -1) &&
1784 (nNewItemIndex
< this._nDisplayedItems
)) {
1785 // User is keying down
1786 if(nKeyCode
== 40) {
1787 // Bottom of selected item is below scroll area...
1788 if((oNewItem
.offsetTop
+oNewItem
.offsetHeight
) > (elContent
.scrollTop
+ elContent
.offsetHeight
)) {
1789 // Set bottom of scroll area to bottom of selected item
1790 elContent
.scrollTop
= (oNewItem
.offsetTop
+oNewItem
.offsetHeight
) - elContent
.offsetHeight
;
1792 // Bottom of selected item is above scroll area...
1793 else if((oNewItem
.offsetTop
+oNewItem
.offsetHeight
) < elContent
.scrollTop
) {
1794 // Set top of selected item to top of scroll area
1795 elContent
.scrollTop
= oNewItem
.offsetTop
;
1799 // User is keying up
1801 // Top of selected item is above scroll area
1802 if(oNewItem
.offsetTop
< elContent
.scrollTop
) {
1803 // Set top of scroll area to top of selected item
1804 this._elContent
.scrollTop
= oNewItem
.offsetTop
;
1806 // Top of selected item is below scroll area
1807 else if(oNewItem
.offsetTop
> (elContent
.scrollTop
+ elContent
.offsetHeight
)) {
1808 // Set bottom of selected item to bottom of scroll area
1809 this._elContent
.scrollTop
= (oNewItem
.offsetTop
+oNewItem
.offsetHeight
) - elContent
.offsetHeight
;
1814 this._toggleHighlight(oNewItem
, "to");
1815 this.itemArrowToEvent
.fire(this, oNewItem
);
1816 if(this.typeAhead
) {
1817 this._updateValue(oNewItem
);
1822 /////////////////////////////////////////////////////////////////////////////
1824 // Private event handlers
1826 /////////////////////////////////////////////////////////////////////////////
1829 * Handles <li> element mouseover events in the container.
1831 * @method _onItemMouseover
1832 * @param v {HTMLEvent} The mouseover event.
1833 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
1836 YAHOO
.widget
.AutoComplete
.prototype._onItemMouseover = function(v
,oSelf
) {
1837 if(oSelf
.prehighlightClassName
) {
1838 oSelf
._togglePrehighlight(this,"mouseover");
1841 oSelf
._toggleHighlight(this,"to");
1844 oSelf
.itemMouseOverEvent
.fire(oSelf
, this);
1848 * Handles <li> element mouseout events in the container.
1850 * @method _onItemMouseout
1851 * @param v {HTMLEvent} The mouseout event.
1852 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
1855 YAHOO
.widget
.AutoComplete
.prototype._onItemMouseout = function(v
,oSelf
) {
1856 if(oSelf
.prehighlightClassName
) {
1857 oSelf
._togglePrehighlight(this,"mouseout");
1860 oSelf
._toggleHighlight(this,"from");
1863 oSelf
.itemMouseOutEvent
.fire(oSelf
, this);
1867 * Handles <li> element click events in the container.
1869 * @method _onItemMouseclick
1870 * @param v {HTMLEvent} The click event.
1871 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
1874 YAHOO
.widget
.AutoComplete
.prototype._onItemMouseclick = function(v
,oSelf
) {
1875 // In case item has not been moused over
1876 oSelf
._toggleHighlight(this,"to");
1877 oSelf
._selectItem(this);
1881 * Handles container mouseover events.
1883 * @method _onContainerMouseover
1884 * @param v {HTMLEvent} The mouseover event.
1885 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
1888 YAHOO
.widget
.AutoComplete
.prototype._onContainerMouseover = function(v
,oSelf
) {
1889 oSelf
._bOverContainer
= true;
1893 * Handles container mouseout events.
1895 * @method _onContainerMouseout
1896 * @param v {HTMLEvent} The mouseout event.
1897 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
1900 YAHOO
.widget
.AutoComplete
.prototype._onContainerMouseout = function(v
,oSelf
) {
1901 oSelf
._bOverContainer
= false;
1902 // If container is still active
1903 if(oSelf
._oCurItem
) {
1904 oSelf
._toggleHighlight(oSelf
._oCurItem
,"to");
1909 * Handles container scroll events.
1911 * @method _onContainerScroll
1912 * @param v {HTMLEvent} The scroll event.
1913 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
1916 YAHOO
.widget
.AutoComplete
.prototype._onContainerScroll = function(v
,oSelf
) {
1917 oSelf
._elTextbox
.focus();
1921 * Handles container resize events.
1923 * @method _onContainerResize
1924 * @param v {HTMLEvent} The resize event.
1925 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
1928 YAHOO
.widget
.AutoComplete
.prototype._onContainerResize = function(v
,oSelf
) {
1929 oSelf
._toggleContainerHelpers(oSelf
._bContainerOpen
);
1934 * Handles textbox keydown events of functional keys, mainly for UI behavior.
1936 * @method _onTextboxKeyDown
1937 * @param v {HTMLEvent} The keydown event.
1938 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
1941 YAHOO
.widget
.AutoComplete
.prototype._onTextboxKeyDown = function(v
,oSelf
) {
1942 var nKeyCode
= v
.keyCode
;
1946 if((navigator
.userAgent
.toLowerCase().indexOf("mac") == -1)) {
1947 // select an item or clear out
1948 if(oSelf
._oCurItem
) {
1949 if(oSelf
.delimChar
&& (oSelf
._nKeyCode
!= nKeyCode
)) {
1950 if(oSelf
._bContainerOpen
) {
1951 YAHOO
.util
.Event
.stopEvent(v
);
1954 oSelf
._selectItem(oSelf
._oCurItem
);
1957 oSelf
._toggleContainer(false);
1962 if((navigator
.userAgent
.toLowerCase().indexOf("mac") == -1)) {
1963 if(oSelf
._oCurItem
) {
1964 if(oSelf
._nKeyCode
!= nKeyCode
) {
1965 if(oSelf
._bContainerOpen
) {
1966 YAHOO
.util
.Event
.stopEvent(v
);
1969 oSelf
._selectItem(oSelf
._oCurItem
);
1972 oSelf
._toggleContainer(false);
1977 oSelf
._toggleContainer(false);
1980 oSelf
._jumpSelection();
1983 YAHOO
.util
.Event
.stopEvent(v
);
1984 oSelf
._moveSelection(nKeyCode
);
1987 YAHOO
.util
.Event
.stopEvent(v
);
1988 oSelf
._moveSelection(nKeyCode
);
1996 * Handles textbox keypress events.
1997 * @method _onTextboxKeyPress
1998 * @param v {HTMLEvent} The keypress event.
1999 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
2002 YAHOO
.widget
.AutoComplete
.prototype._onTextboxKeyPress = function(v
,oSelf
) {
2003 var nKeyCode
= v
.keyCode
;
2005 //Expose only to Mac browsers, where stopEvent is ineffective on keydown events (bug 790337)
2006 if((navigator
.userAgent
.toLowerCase().indexOf("mac") != -1)) {
2009 // select an item or clear out
2010 if(oSelf
._oCurItem
) {
2011 if(oSelf
.delimChar
&& (oSelf
._nKeyCode
!= nKeyCode
)) {
2012 if(oSelf
._bContainerOpen
) {
2013 YAHOO
.util
.Event
.stopEvent(v
);
2016 oSelf
._selectItem(oSelf
._oCurItem
);
2019 oSelf
._toggleContainer(false);
2023 if(oSelf
._oCurItem
) {
2024 if(oSelf
._nKeyCode
!= nKeyCode
) {
2025 if(oSelf
._bContainerOpen
) {
2026 YAHOO
.util
.Event
.stopEvent(v
);
2029 oSelf
._selectItem(oSelf
._oCurItem
);
2032 oSelf
._toggleContainer(false);
2040 //TODO: (?) limit only to non-IE, non-Mac-FF for Korean IME support (bug 811948)
2041 // Korean IME detected
2042 else if(nKeyCode
== 229) {
2043 oSelf
._queryInterval
= setInterval(function() { oSelf
._onIMEDetected(oSelf
); },500);
2048 * Handles textbox keyup events that trigger queries.
2050 * @method _onTextboxKeyUp
2051 * @param v {HTMLEvent} The keyup event.
2052 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
2055 YAHOO
.widget
.AutoComplete
.prototype._onTextboxKeyUp = function(v
,oSelf
) {
2056 // Check to see if any of the public properties have been updated
2059 var nKeyCode
= v
.keyCode
;
2061 oSelf
._nKeyCode
= nKeyCode
;
2062 var sText
= this.value
; //string in textbox
2064 // Filter out chars that don't trigger queries
2065 if(oSelf
._isIgnoreKey(nKeyCode
) || (sText
.toLowerCase() == oSelf
._sCurQuery
)) {
2069 oSelf
._bItemSelected
= false;
2070 YAHOO
.util
.Dom
.removeClass(oSelf
._oCurItem
, oSelf
.highlightClassName
);
2071 oSelf
._oCurItem
= null;
2073 oSelf
.textboxKeyEvent
.fire(oSelf
, nKeyCode
);
2076 // Set timeout on the request
2077 if(oSelf
.queryDelay
> 0) {
2079 setTimeout(function(){oSelf
._sendQuery(sText
);},(oSelf
.queryDelay
* 1000));
2081 if(oSelf
._nDelayID
!= -1) {
2082 clearTimeout(oSelf
._nDelayID
);
2085 oSelf
._nDelayID
= nDelayID
;
2088 // No delay so send request immediately
2089 oSelf
._sendQuery(sText
);
2094 * Handles text input box receiving focus.
2096 * @method _onTextboxFocus
2097 * @param v {HTMLEvent} The focus event.
2098 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
2101 YAHOO
.widget
.AutoComplete
.prototype._onTextboxFocus = function (v
,oSelf
) {
2102 oSelf
._elTextbox
.setAttribute("autocomplete","off");
2103 oSelf
._bFocused
= true;
2104 if(!oSelf
._bItemSelected
) {
2105 oSelf
.textboxFocusEvent
.fire(oSelf
);
2110 * Handles text input box losing focus.
2112 * @method _onTextboxBlur
2113 * @param v {HTMLEvent} The focus event.
2114 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
2117 YAHOO
.widget
.AutoComplete
.prototype._onTextboxBlur = function (v
,oSelf
) {
2118 // Don't treat as a blur if it was a selection via mouse click
2119 if(!oSelf
._bOverContainer
|| (oSelf
._nKeyCode
== 9)) {
2120 // Current query needs to be validated as a selection
2121 if(!oSelf
._bItemSelected
) {
2122 var oMatch
= oSelf
._textMatchesOption();
2123 // Container is closed or current query doesn't match any result
2124 if(!oSelf
._bContainerOpen
|| (oSelf
._bContainerOpen
&& (oMatch
=== null))) {
2125 // Force selection is enabled so clear the current query
2126 if(oSelf
.forceSelection
) {
2127 oSelf
._clearSelection();
2129 // Treat current query as a valid selection
2131 oSelf
.unmatchedItemSelectEvent
.fire(oSelf
);
2134 // Container is open and current query matches a result
2136 // Force a selection when textbox is blurred with a match
2137 if(oSelf
.forceSelection
) {
2138 oSelf
._selectItem(oMatch
);
2143 if(oSelf
._bContainerOpen
) {
2144 oSelf
._toggleContainer(false);
2146 oSelf
._cancelIntervalDetection(oSelf
);
2147 oSelf
._bFocused
= false;
2148 oSelf
.textboxBlurEvent
.fire(oSelf
);
2153 * Handles window unload event.
2155 * @method _onWindowUnload
2156 * @param v {HTMLEvent} The unload event.
2157 * @param oSelf {YAHOO.widget.AutoComplete} The AutoComplete instance.
2160 YAHOO
.widget
.AutoComplete
.prototype._onWindowUnload = function(v
,oSelf
) {
2161 if(oSelf
&& oSelf
._elTextbox
&& oSelf
.allowBrowserAutocomplete
) {
2162 oSelf
._elTextbox
.setAttribute("autocomplete","on");
2166 /****************************************************************************/
2167 /****************************************************************************/
2168 /****************************************************************************/
2171 * The DataSource classes manages sending a request and returning response from a live
2172 * database. Supported data include local JavaScript arrays and objects and databases
2173 * accessible via XHR connections. Supported response formats include JavaScript arrays,
2174 * JSON, XML, and flat-file textual data.
2179 YAHOO
.widget
.DataSource = function() {
2180 /* abstract class */
2184 /////////////////////////////////////////////////////////////////////////////
2188 /////////////////////////////////////////////////////////////////////////////
2191 * Error message for null data responses.
2193 * @property ERROR_DATANULL
2198 YAHOO
.widget
.DataSource
.ERROR_DATANULL
= "Response data was null";
2201 * Error message for data responses with parsing errors.
2203 * @property ERROR_DATAPARSE
2208 YAHOO
.widget
.DataSource
.ERROR_DATAPARSE
= "Response data could not be parsed";
2211 /////////////////////////////////////////////////////////////////////////////
2213 // Public member variables
2215 /////////////////////////////////////////////////////////////////////////////
2218 * Max size of the local cache. Set to 0 to turn off caching. Caching is
2219 * useful to reduce the number of server connections. Recommended only for data
2220 * sources that return comprehensive results for queries or when stale data is
2223 * @property maxCacheEntries
2227 YAHOO
.widget
.DataSource
.prototype.maxCacheEntries
= 15;
2230 * Use this to fine-tune the matching algorithm used against JS Array types of
2231 * DataSource and DataSource caches. If queryMatchContains is true, then the JS
2232 * Array or cache returns results that "contain" the query string. By default,
2233 * queryMatchContains is set to false, so that only results that "start with"
2234 * the query string are returned.
2236 * @property queryMatchContains
2240 YAHOO
.widget
.DataSource
.prototype.queryMatchContains
= false;
2243 * Enables query subset matching. If caching is on and queryMatchSubset is
2244 * true, substrings of queries will return matching cached results. For
2245 * instance, if the first query is for "abc" susequent queries that start with
2246 * "abc", like "abcd", will be queried against the cache, and not the live data
2247 * source. Recommended only for DataSources that return comprehensive results
2248 * for queries with very few characters.
2250 * @property queryMatchSubset
2255 YAHOO
.widget
.DataSource
.prototype.queryMatchSubset
= false;
2258 * Enables case-sensitivity in the matching algorithm used against JS Array
2259 * types of DataSources and DataSource caches. If queryMatchCase is true, only
2260 * case-sensitive matches will return.
2262 * @property queryMatchCase
2266 YAHOO
.widget
.DataSource
.prototype.queryMatchCase
= false;
2269 /////////////////////////////////////////////////////////////////////////////
2273 /////////////////////////////////////////////////////////////////////////////
2276 * Public accessor to the unique name of the DataSource instance.
2279 * @return {String} Unique name of the DataSource instance
2281 YAHOO
.widget
.DataSource
.prototype.toString = function() {
2282 return "DataSource " + this._sName
;
2286 * Retrieves query results, first checking the local cache, then making the
2287 * query request to the live data source as defined by the function doQuery.
2289 * @method getResults
2290 * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results.
2291 * @param sQuery {String} Query string.
2292 * @param oParent {Object} The object instance that has requested data.
2294 YAHOO
.widget
.DataSource
.prototype.getResults = function(oCallbackFn
, sQuery
, oParent
) {
2296 // First look in cache
2297 var aResults
= this._doQueryCache(oCallbackFn
,sQuery
,oParent
);
2298 // Not in cache, so get results from server
2299 if(aResults
.length
=== 0) {
2300 this.queryEvent
.fire(this, oParent
, sQuery
);
2301 this.doQuery(oCallbackFn
, sQuery
, oParent
);
2306 * Abstract method implemented by subclasses to make a query to the live data
2307 * source. Must call the callback function with the response returned from the
2308 * query. Populates cache (if enabled).
2311 * @param oCallbackFn {HTMLFunction} Callback function implemented by oParent to which to return results.
2312 * @param sQuery {String} Query string.
2313 * @param oParent {Object} The object instance that has requested data.
2315 YAHOO
.widget
.DataSource
.prototype.doQuery = function(oCallbackFn
, sQuery
, oParent
) {
2322 * @method flushCache
2324 YAHOO
.widget
.DataSource
.prototype.flushCache = function() {
2328 if(this._aCacheHelper
) {
2329 this._aCacheHelper
= [];
2331 this.cacheFlushEvent
.fire(this);
2335 /////////////////////////////////////////////////////////////////////////////
2339 /////////////////////////////////////////////////////////////////////////////
2342 * Fired when a query is made to the live data source.
2345 * @param oSelf {Object} The DataSource instance.
2346 * @param oParent {Object} The requesting object.
2347 * @param sQuery {String} The query string.
2349 YAHOO
.widget
.DataSource
.prototype.queryEvent
= null;
2352 * Fired when a query is made to the local cache.
2354 * @event cacheQueryEvent
2355 * @param oSelf {Object} The DataSource instance.
2356 * @param oParent {Object} The requesting object.
2357 * @param sQuery {String} The query string.
2359 YAHOO
.widget
.DataSource
.prototype.cacheQueryEvent
= null;
2362 * Fired when data is retrieved from the live data source.
2364 * @event getResultsEvent
2365 * @param oSelf {Object} The DataSource instance.
2366 * @param oParent {Object} The requesting object.
2367 * @param sQuery {String} The query string.
2368 * @param aResults {Object[]} Array of result objects.
2370 YAHOO
.widget
.DataSource
.prototype.getResultsEvent
= null;
2373 * Fired when data is retrieved from the local cache.
2375 * @event getCachedResultsEvent
2376 * @param oSelf {Object} The DataSource instance.
2377 * @param oParent {Object} The requesting object.
2378 * @param sQuery {String} The query string.
2379 * @param aResults {Object[]} Array of result objects.
2381 YAHOO
.widget
.DataSource
.prototype.getCachedResultsEvent
= null;
2384 * Fired when an error is encountered with the live data source.
2386 * @event dataErrorEvent
2387 * @param oSelf {Object} The DataSource instance.
2388 * @param oParent {Object} The requesting object.
2389 * @param sQuery {String} The query string.
2390 * @param sMsg {String} Error message string
2392 YAHOO
.widget
.DataSource
.prototype.dataErrorEvent
= null;
2395 * Fired when the local cache is flushed.
2397 * @event cacheFlushEvent
2398 * @param oSelf {Object} The DataSource instance
2400 YAHOO
.widget
.DataSource
.prototype.cacheFlushEvent
= null;
2402 /////////////////////////////////////////////////////////////////////////////
2404 // Private member variables
2406 /////////////////////////////////////////////////////////////////////////////
2409 * Internal class variable to index multiple DataSource instances.
2416 YAHOO
.widget
.DataSource
._nIndex
= 0;
2419 * Name of DataSource instance.
2425 YAHOO
.widget
.DataSource
.prototype._sName
= null;
2428 * Local cache of data result objects indexed chronologically.
2434 YAHOO
.widget
.DataSource
.prototype._aCache
= null;
2437 /////////////////////////////////////////////////////////////////////////////
2441 /////////////////////////////////////////////////////////////////////////////
2444 * Initializes DataSource instance.
2449 YAHOO
.widget
.DataSource
.prototype._init = function() {
2450 // Validate and initialize public configs
2451 var maxCacheEntries
= this.maxCacheEntries
;
2452 if(!YAHOO
.lang
.isNumber(maxCacheEntries
) || (maxCacheEntries
< 0)) {
2453 maxCacheEntries
= 0;
2455 // Initialize local cache
2456 if(maxCacheEntries
> 0 && !this._aCache
) {
2460 this._sName
= "instance" + YAHOO
.widget
.DataSource
._nIndex
;
2461 YAHOO
.widget
.DataSource
._nIndex
++;
2463 this.queryEvent
= new YAHOO
.util
.CustomEvent("query", this);
2464 this.cacheQueryEvent
= new YAHOO
.util
.CustomEvent("cacheQuery", this);
2465 this.getResultsEvent
= new YAHOO
.util
.CustomEvent("getResults", this);
2466 this.getCachedResultsEvent
= new YAHOO
.util
.CustomEvent("getCachedResults", this);
2467 this.dataErrorEvent
= new YAHOO
.util
.CustomEvent("dataError", this);
2468 this.cacheFlushEvent
= new YAHOO
.util
.CustomEvent("cacheFlush", this);
2472 * Adds a result object to the local cache, evicting the oldest element if the
2473 * cache is full. Newer items will have higher indexes, the oldest item will have
2476 * @method _addCacheElem
2477 * @param oResult {Object} Data result object, including array of results.
2480 YAHOO
.widget
.DataSource
.prototype._addCacheElem = function(oResult
) {
2481 var aCache
= this._aCache
;
2482 // Don't add if anything important is missing.
2483 if(!aCache
|| !oResult
|| !oResult
.query
|| !oResult
.results
) {
2487 // If the cache is full, make room by removing from index=0
2488 if(aCache
.length
>= this.maxCacheEntries
) {
2492 // Add to cache, at the end of the array
2493 aCache
.push(oResult
);
2497 * Queries the local cache for results. If query has been cached, the callback
2498 * function is called with the results, and the cached is refreshed so that it
2499 * is now the newest element.
2501 * @method _doQueryCache
2502 * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results.
2503 * @param sQuery {String} Query string.
2504 * @param oParent {Object} The object instance that has requested data.
2505 * @return aResults {Object[]} Array of results from local cache if found, otherwise null.
2508 YAHOO
.widget
.DataSource
.prototype._doQueryCache = function(oCallbackFn
, sQuery
, oParent
) {
2510 var bMatchFound
= false;
2511 var aCache
= this._aCache
;
2512 var nCacheLength
= (aCache
) ? aCache
.length
: 0;
2513 var bMatchContains
= this.queryMatchContains
;
2516 // If cache is enabled...
2517 if((this.maxCacheEntries
> 0) && aCache
&& (nCacheLength
> 0)) {
2518 this.cacheQueryEvent
.fire(this, oParent
, sQuery
);
2519 // If case is unimportant, normalize query now instead of in loops
2520 if(!this.queryMatchCase
) {
2521 sOrigQuery
= sQuery
;
2522 sQuery
= sQuery
.toLowerCase();
2525 // Loop through each cached element's query property...
2526 for(var i
= nCacheLength
-1; i
>= 0; i
--) {
2527 var resultObj
= aCache
[i
];
2528 var aAllResultItems
= resultObj
.results
;
2529 // If case is unimportant, normalize match key for comparison
2530 var matchKey
= (!this.queryMatchCase
) ?
2531 encodeURIComponent(resultObj
.query
).toLowerCase():
2532 encodeURIComponent(resultObj
.query
);
2534 // If a cached match key exactly matches the query...
2535 if(matchKey
== sQuery
) {
2536 // Stash all result objects into aResult[] and stop looping through the cache.
2538 aResults
= aAllResultItems
;
2540 // The matching cache element was not the most recent,
2541 // so now we need to refresh the cache.
2542 if(i
!= nCacheLength
-1) {
2543 // Remove element from its original location
2545 // Add element as newest
2546 this._addCacheElem(resultObj
);
2550 // Else if this query is not an exact match and subset matching is enabled...
2551 else if(this.queryMatchSubset
) {
2552 // Loop through substrings of each cached element's query property...
2553 for(var j
= sQuery
.length
-1; j
>= 0 ; j
--) {
2554 var subQuery
= sQuery
.substr(0,j
);
2556 // If a substring of a cached sQuery exactly matches the query...
2557 if(matchKey
== subQuery
) {
2560 // Go through each cached result object to match against the query...
2561 for(var k
= aAllResultItems
.length
-1; k
>= 0; k
--) {
2562 var aRecord
= aAllResultItems
[k
];
2563 var sKeyIndex
= (this.queryMatchCase
) ?
2564 encodeURIComponent(aRecord
[0]).indexOf(sQuery
):
2565 encodeURIComponent(aRecord
[0]).toLowerCase().indexOf(sQuery
);
2567 // A STARTSWITH match is when the query is found at the beginning of the key string...
2568 if((!bMatchContains
&& (sKeyIndex
=== 0)) ||
2569 // A CONTAINS match is when the query is found anywhere within the key string...
2570 (bMatchContains
&& (sKeyIndex
> -1))) {
2571 // Stash a match into aResults[].
2572 aResults
.unshift(aRecord
);
2576 // Add the subset match result set object as the newest element to cache,
2577 // and stop looping through the cache.
2579 resultObj
.query
= sQuery
;
2580 resultObj
.results
= aResults
;
2581 this._addCacheElem(resultObj
);
2591 // If there was a match, send along the results.
2593 this.getCachedResultsEvent
.fire(this, oParent
, sOrigQuery
, aResults
);
2594 oCallbackFn(sOrigQuery
, aResults
, oParent
);
2601 /****************************************************************************/
2602 /****************************************************************************/
2603 /****************************************************************************/
2606 * Implementation of YAHOO.widget.DataSource using XML HTTP requests that return
2610 * @extends YAHOO.widget.DataSource
2611 * @requires connection
2613 * @param sScriptURI {String} Absolute or relative URI to script that returns query
2614 * results as JSON, XML, or delimited flat-file data.
2615 * @param aSchema {String[]} Data schema definition of results.
2616 * @param oConfigs {Object} (optional) Object literal of config params.
2618 YAHOO
.widget
.DS_XHR = function(sScriptURI
, aSchema
, oConfigs
) {
2619 // Set any config params passed in to override defaults
2620 if(oConfigs
&& (oConfigs
.constructor == Object
)) {
2621 for(var sConfig
in oConfigs
) {
2622 this[sConfig
] = oConfigs
[sConfig
];
2626 // Initialization sequence
2627 if(!YAHOO
.lang
.isArray(aSchema
) || !YAHOO
.lang
.isString(sScriptURI
)) {
2631 this.schema
= aSchema
;
2632 this.scriptURI
= sScriptURI
;
2637 YAHOO
.widget
.DS_XHR
.prototype = new YAHOO
.widget
.DataSource();
2639 /////////////////////////////////////////////////////////////////////////////
2643 /////////////////////////////////////////////////////////////////////////////
2648 * @property TYPE_JSON
2653 YAHOO
.widget
.DS_XHR
.TYPE_JSON
= 0;
2658 * @property TYPE_XML
2663 YAHOO
.widget
.DS_XHR
.TYPE_XML
= 1;
2666 * Flat-file data type.
2668 * @property TYPE_FLAT
2673 YAHOO
.widget
.DS_XHR
.TYPE_FLAT
= 2;
2676 * Error message for XHR failure.
2678 * @property ERROR_DATAXHR
2683 YAHOO
.widget
.DS_XHR
.ERROR_DATAXHR
= "XHR response failed";
2685 /////////////////////////////////////////////////////////////////////////////
2687 // Public member variables
2689 /////////////////////////////////////////////////////////////////////////////
2692 * Alias to YUI Connection Manager, to allow implementers to customize the utility.
2696 * @default YAHOO.util.Connect
2698 YAHOO
.widget
.DS_XHR
.prototype.connMgr
= YAHOO
.util
.Connect
;
2701 * Number of milliseconds the XHR connection will wait for a server response. A
2702 * a value of zero indicates the XHR connection will wait forever. Any value
2703 * greater than zero will use the Connection utility's Auto-Abort feature.
2705 * @property connTimeout
2709 YAHOO
.widget
.DS_XHR
.prototype.connTimeout
= 0;
2712 * Absolute or relative URI to script that returns query results. For instance,
2713 * queries will be sent to <scriptURI>?<scriptQueryParam>=userinput
2715 * @property scriptURI
2718 YAHOO
.widget
.DS_XHR
.prototype.scriptURI
= null;
2721 * Query string parameter name sent to scriptURI. For instance, queries will be
2722 * sent to <scriptURI>?<scriptQueryParam>=userinput
2724 * @property scriptQueryParam
2728 YAHOO
.widget
.DS_XHR
.prototype.scriptQueryParam
= "query";
2731 * String of key/value pairs to append to requests made to scriptURI. Define
2732 * this string when you want to send additional query parameters to your script.
2733 * When defined, queries will be sent to
2734 * <scriptURI>?<scriptQueryParam>=userinput&<scriptQueryAppend>
2736 * @property scriptQueryAppend
2740 YAHOO
.widget
.DS_XHR
.prototype.scriptQueryAppend
= "";
2743 * XHR response data type. Other types that may be defined are YAHOO.widget.DS_XHR.TYPE_XML
2744 * and YAHOO.widget.DS_XHR.TYPE_FLAT.
2746 * @property responseType
2748 * @default YAHOO.widget.DS_XHR.TYPE_JSON
2750 YAHOO
.widget
.DS_XHR
.prototype.responseType
= YAHOO
.widget
.DS_XHR
.TYPE_JSON
;
2753 * String after which to strip results. If the results from the XHR are sent
2754 * back as HTML, the gzip HTML comment appears at the end of the data and should
2757 * @property responseStripAfter
2759 * @default "\n<!-"
2761 YAHOO
.widget
.DS_XHR
.prototype.responseStripAfter
= "\n<!-";
2763 /////////////////////////////////////////////////////////////////////////////
2767 /////////////////////////////////////////////////////////////////////////////
2770 * Queries the live data source defined by scriptURI for results. Results are
2771 * passed back to a callback function.
2774 * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results.
2775 * @param sQuery {String} Query string.
2776 * @param oParent {Object} The object instance that has requested data.
2778 YAHOO
.widget
.DS_XHR
.prototype.doQuery = function(oCallbackFn
, sQuery
, oParent
) {
2779 var isXML
= (this.responseType
== YAHOO
.widget
.DS_XHR
.TYPE_XML
);
2780 var sUri
= this.scriptURI
+"?"+this.scriptQueryParam
+"="+sQuery
;
2781 if(this.scriptQueryAppend
.length
> 0) {
2782 sUri
+= "&" + this.scriptQueryAppend
;
2784 var oResponse
= null;
2788 * Sets up ajax request callback
2790 * @param {object} oReq HTTPXMLRequest object
2793 var responseSuccess = function(oResp
) {
2794 // Response ID does not match last made request ID.
2795 if(!oSelf
._oConn
|| (oResp
.tId
!= oSelf
._oConn
.tId
)) {
2796 oSelf
.dataErrorEvent
.fire(oSelf
, oParent
, sQuery
, YAHOO
.widget
.DataSource
.ERROR_DATANULL
);
2800 for(var foo
in oResp
) {
2803 oResp
= oResp
.responseText
;
2806 oResp
= oResp
.responseXML
;
2808 if(oResp
=== null) {
2809 oSelf
.dataErrorEvent
.fire(oSelf
, oParent
, sQuery
, YAHOO
.widget
.DataSource
.ERROR_DATANULL
);
2813 var aResults
= oSelf
.parseResponse(sQuery
, oResp
, oParent
);
2815 resultObj
.query
= decodeURIComponent(sQuery
);
2816 resultObj
.results
= aResults
;
2817 if(aResults
=== null) {
2818 oSelf
.dataErrorEvent
.fire(oSelf
, oParent
, sQuery
, YAHOO
.widget
.DataSource
.ERROR_DATAPARSE
);
2822 oSelf
.getResultsEvent
.fire(oSelf
, oParent
, sQuery
, aResults
);
2823 oSelf
._addCacheElem(resultObj
);
2825 oCallbackFn(sQuery
, aResults
, oParent
);
2828 var responseFailure = function(oResp
) {
2829 oSelf
.dataErrorEvent
.fire(oSelf
, oParent
, sQuery
, YAHOO
.widget
.DS_XHR
.ERROR_DATAXHR
);
2834 success
:responseSuccess
,
2835 failure
:responseFailure
2838 if(YAHOO
.lang
.isNumber(this.connTimeout
) && (this.connTimeout
> 0)) {
2839 oCallback
.timeout
= this.connTimeout
;
2843 this.connMgr
.abort(this._oConn
);
2846 oSelf
._oConn
= this.connMgr
.asyncRequest("GET", sUri
, oCallback
, null);
2850 * Parses raw response data into an array of result objects. The result data key
2851 * is always stashed in the [0] element of each result object.
2853 * @method parseResponse
2854 * @param sQuery {String} Query string.
2855 * @param oResponse {Object} The raw response data to parse.
2856 * @param oParent {Object} The object instance that has requested data.
2857 * @returns {Object[]} Array of result objects.
2859 YAHOO
.widget
.DS_XHR
.prototype.parseResponse = function(sQuery
, oResponse
, oParent
) {
2860 var aSchema
= this.schema
;
2864 // Strip out comment at the end of results
2865 var nEnd
= ((this.responseStripAfter
!== "") && (oResponse
.indexOf
)) ?
2866 oResponse
.indexOf(this.responseStripAfter
) : -1;
2868 oResponse
= oResponse
.substring(0,nEnd
);
2871 switch (this.responseType
) {
2872 case YAHOO
.widget
.DS_XHR
.TYPE_JSON
:
2873 var jsonList
, jsonObjParsed
;
2874 // Check for YUI JSON
2875 if(YAHOO
.lang
.JSON
) {
2876 // Use the JSON utility if available
2877 jsonObjParsed
= YAHOO
.lang
.JSON
.parse(oResponse
);
2878 if(!jsonObjParsed
) {
2884 // eval is necessary here since aSchema[0] is of unknown depth
2885 jsonList
= eval("jsonObjParsed." + aSchema
[0]);
2893 // Check for JSON lib
2894 else if(oResponse
.parseJSON
) {
2895 // Use the new JSON utility if available
2896 jsonObjParsed
= oResponse
.parseJSON();
2897 if(!jsonObjParsed
) {
2902 // eval is necessary here since aSchema[0] is of unknown depth
2903 jsonList
= eval("jsonObjParsed." + aSchema
[0]);
2911 // Use older JSON lib if available
2912 else if(window
.JSON
) {
2913 jsonObjParsed
= JSON
.parse(oResponse
);
2914 if(!jsonObjParsed
) {
2920 // eval is necessary here since aSchema[0] is of unknown depth
2921 jsonList
= eval("jsonObjParsed." + aSchema
[0]);
2930 // Parse the JSON response as a string
2932 // Trim leading spaces
2933 while (oResponse
.substring(0,1) == " ") {
2934 oResponse
= oResponse
.substring(1, oResponse
.length
);
2937 // Invalid JSON response
2938 if(oResponse
.indexOf("{") < 0) {
2943 // Empty (but not invalid) JSON response
2944 if(oResponse
.indexOf("{}") === 0) {
2948 // Turn the string into an object literal...
2949 // ...eval is necessary here
2950 var jsonObjRaw
= eval("(" + oResponse
+ ")");
2956 // Grab the object member that contains an array of all reponses...
2957 // ...eval is necessary here since aSchema[0] is of unknown depth
2958 jsonList
= eval("(jsonObjRaw." + aSchema
[0]+")");
2971 if(!YAHOO
.lang
.isArray(jsonList
)) {
2972 jsonList
= [jsonList
];
2975 // Loop through the array of all responses...
2976 for(var i
= jsonList
.length
-1; i
>= 0 ; i
--) {
2977 var aResultItem
= [];
2978 var jsonResult
= jsonList
[i
];
2979 // ...and loop through each data field value of each response
2980 for(var j
= aSchema
.length
-1; j
>= 1 ; j
--) {
2981 // ...and capture data into an array mapped according to the schema...
2982 var dataFieldValue
= jsonResult
[aSchema
[j
]];
2983 if(!dataFieldValue
) {
2984 dataFieldValue
= "";
2986 aResultItem
.unshift(dataFieldValue
);
2988 // If schema isn't well defined, pass along the entire result object
2989 if(aResultItem
.length
== 1) {
2990 aResultItem
.push(jsonResult
);
2992 // Capture the array of data field values in an array of results
2993 aResults
.unshift(aResultItem
);
2996 case YAHOO
.widget
.DS_XHR
.TYPE_XML
:
2997 // Get the collection of results
2998 var xmlList
= oResponse
.getElementsByTagName(aSchema
[0]);
3003 // Loop through each result
3004 for(var k
= xmlList
.length
-1; k
>= 0 ; k
--) {
3005 var result
= xmlList
.item(k
);
3007 // Loop through each data field in each result using the schema
3008 for(var m
= aSchema
.length
-1; m
>= 1 ; m
--) {
3010 // Values may be held in an attribute...
3011 var xmlAttr
= result
.attributes
.getNamedItem(aSchema
[m
]);
3013 sValue
= xmlAttr
.value
;
3017 var xmlNode
= result
.getElementsByTagName(aSchema
[m
]);
3018 if(xmlNode
&& xmlNode
.item(0) && xmlNode
.item(0).firstChild
) {
3019 sValue
= xmlNode
.item(0).firstChild
.nodeValue
;
3025 // Capture the schema-mapped data field values into an array
3026 aFieldSet
.unshift(sValue
);
3028 // Capture each array of values into an array of results
3029 aResults
.unshift(aFieldSet
);
3032 case YAHOO
.widget
.DS_XHR
.TYPE_FLAT
:
3033 if(oResponse
.length
> 0) {
3034 // Delete the last line delimiter at the end of the data if it exists
3035 var newLength
= oResponse
.length
-aSchema
[0].length
;
3036 if(oResponse
.substr(newLength
) == aSchema
[0]) {
3037 oResponse
= oResponse
.substr(0, newLength
);
3039 if(oResponse
.length
> 0) {
3040 var aRecords
= oResponse
.split(aSchema
[0]);
3041 for(var n
= aRecords
.length
-1; n
>= 0; n
--) {
3042 if(aRecords
[n
].length
> 0) {
3043 aResults
[n
] = aRecords
[n
].split(aSchema
[1]);
3063 /////////////////////////////////////////////////////////////////////////////
3065 // Private member variables
3067 /////////////////////////////////////////////////////////////////////////////
3070 * XHR connection object.
3076 YAHOO
.widget
.DS_XHR
.prototype._oConn
= null;
3079 /****************************************************************************/
3080 /****************************************************************************/
3081 /****************************************************************************/
3084 * Implementation of YAHOO.widget.DataSource using the Get Utility to generate
3085 * dynamic SCRIPT nodes for data retrieval.
3087 * @class DS_ScriptNode
3089 * @extends YAHOO.widget.DataSource
3090 * @param sUri {String} URI to the script location that will return data.
3091 * @param aSchema {String[]} Data schema definition of results.
3092 * @param oConfigs {Object} (optional) Object literal of config params.
3094 YAHOO
.widget
.DS_ScriptNode = function(sUri
, aSchema
, oConfigs
) {
3095 // Set any config params passed in to override defaults
3096 if(oConfigs
&& (oConfigs
.constructor == Object
)) {
3097 for(var sConfig
in oConfigs
) {
3098 this[sConfig
] = oConfigs
[sConfig
];
3102 // Initialization sequence
3103 if(!YAHOO
.lang
.isArray(aSchema
) || !YAHOO
.lang
.isString(sUri
)) {
3107 this.schema
= aSchema
;
3108 this.scriptURI
= sUri
;
3113 YAHOO
.widget
.DS_ScriptNode
.prototype = new YAHOO
.widget
.DataSource();
3115 /////////////////////////////////////////////////////////////////////////////
3117 // Public member variables
3119 /////////////////////////////////////////////////////////////////////////////
3122 * Alias to YUI Get Utility. Allows implementers to specify their own
3123 * subclasses of the YUI Get Utility.
3125 * @property getUtility
3127 * @default YAHOO.util.Get
3129 YAHOO
.widget
.DS_ScriptNode
.prototype.getUtility
= YAHOO
.util
.Get
;
3132 * URI to the script that returns data.
3134 * @property scriptURI
3137 YAHOO
.widget
.DS_ScriptNode
.prototype.scriptURI
= null;
3140 * Query string parameter name sent to scriptURI. For instance, requests will be
3141 * sent to <scriptURI>?<scriptQueryParam>=queryString
3143 * @property scriptQueryParam
3147 YAHOO
.widget
.DS_ScriptNode
.prototype.scriptQueryParam
= "query";
3150 * Defines request/response management in the following manner:
3152 * <!--<dt>queueRequests</dt>
3153 * <dd>If a request is already in progress, wait until response is returned before sending the next request.</dd>
3154 * <dt>cancelStaleRequests</dt>
3155 * <dd>If a request is already in progress, cancel it before sending the next request.</dd>-->
3156 * <dt>ignoreStaleResponses</dt>
3157 * <dd>Send all requests, but handle only the response for the most recently sent request.</dd>
3159 * <dd>Send all requests and handle all responses.</dd>
3162 * @property asyncMode
3164 * @default "allowAll"
3166 YAHOO
.widget
.DS_ScriptNode
.prototype.asyncMode
= "allowAll";
3169 * Callback string parameter name sent to scriptURI. For instance, requests will be
3170 * sent to <scriptURI>?<scriptCallbackParam>=callbackFunction
3172 * @property scriptCallbackParam
3174 * @default "callback"
3176 YAHOO
.widget
.DS_ScriptNode
.prototype.scriptCallbackParam
= "callback";
3179 * Global array of callback functions, one for each request sent.
3181 * @property callbacks
3185 YAHOO
.widget
.DS_ScriptNode
.callbacks
= [];
3187 /////////////////////////////////////////////////////////////////////////////
3189 // Private member variables
3191 /////////////////////////////////////////////////////////////////////////////
3194 * Unique ID to track requests.
3201 YAHOO
.widget
.DS_ScriptNode
._nId
= 0;
3204 * Counter for pending requests. When this is 0, it is safe to purge callbacks
3207 * @property _nPending
3212 YAHOO
.widget
.DS_ScriptNode
._nPending
= 0;
3214 /////////////////////////////////////////////////////////////////////////////
3218 /////////////////////////////////////////////////////////////////////////////
3221 * Queries the live data source. Results are passed back to a callback function.
3224 * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results.
3225 * @param sQuery {String} Query string.
3226 * @param oParent {Object} The object instance that has requested data.
3228 YAHOO
.widget
.DS_ScriptNode
.prototype.doQuery = function(oCallbackFn
, sQuery
, oParent
) {
3231 // If there are no global pending requests, it is safe to purge global callback stack and global counter
3232 if(YAHOO
.widget
.DS_ScriptNode
._nPending
=== 0) {
3233 YAHOO
.widget
.DS_ScriptNode
.callbacks
= [];
3234 YAHOO
.widget
.DS_ScriptNode
._nId
= 0;
3237 // ID for this request
3238 var id
= YAHOO
.widget
.DS_ScriptNode
._nId
;
3239 YAHOO
.widget
.DS_ScriptNode
._nId
++;
3241 // Dynamically add handler function with a closure to the callback stack
3242 YAHOO
.widget
.DS_ScriptNode
.callbacks
[id
] = function(oResponse
) {
3243 if((oSelf
.asyncMode
!== "ignoreStaleResponses")||
3244 (id
=== YAHOO
.widget
.DS_ScriptNode
.callbacks
.length
-1)) { // Must ignore stale responses
3245 oSelf
.handleResponse(oResponse
, oCallbackFn
, sQuery
, oParent
);
3250 delete YAHOO
.widget
.DS_ScriptNode
.callbacks
[id
];
3253 // We are now creating a request
3254 YAHOO
.widget
.DS_ScriptNode
._nPending
++;
3256 var sUri
= this.scriptURI
+"&"+ this.scriptQueryParam
+"="+sQuery
+"&"+
3257 this.scriptCallbackParam
+"=YAHOO.widget.DS_ScriptNode.callbacks["+id
+"]";
3258 this.getUtility
.script(sUri
,
3260 onsuccess
:YAHOO
.widget
.DS_ScriptNode
._bumpPendingDown
,
3261 onfail
:YAHOO
.widget
.DS_ScriptNode
._bumpPendingDown
});
3265 * Parses JSON response data into an array of result objects and passes it to
3266 * the callback function.
3268 * @method handleResponse
3269 * @param oResponse {Object} The raw response data to parse.
3270 * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results.
3271 * @param sQuery {String} Query string.
3272 * @param oParent {Object} The object instance that has requested data.
3274 YAHOO
.widget
.DS_ScriptNode
.prototype.handleResponse = function(oResponse
, oCallbackFn
, sQuery
, oParent
) {
3275 var aSchema
= this.schema
;
3279 var jsonList
, jsonObjParsed
;
3281 // Parse the JSON response as a string
3283 // Grab the object member that contains an array of all reponses...
3284 // ...eval is necessary here since aSchema[0] is of unknown depth
3285 jsonList
= eval("(oResponse." + aSchema
[0]+")");
3296 else if(!YAHOO
.lang
.isArray(jsonList
)) {
3297 jsonList
= [jsonList
];
3300 // Loop through the array of all responses...
3301 for(var i
= jsonList
.length
-1; i
>= 0 ; i
--) {
3302 var aResultItem
= [];
3303 var jsonResult
= jsonList
[i
];
3304 // ...and loop through each data field value of each response
3305 for(var j
= aSchema
.length
-1; j
>= 1 ; j
--) {
3306 // ...and capture data into an array mapped according to the schema...
3307 var dataFieldValue
= jsonResult
[aSchema
[j
]];
3308 if(!dataFieldValue
) {
3309 dataFieldValue
= "";
3311 aResultItem
.unshift(dataFieldValue
);
3313 // If schema isn't well defined, pass along the entire result object
3314 if(aResultItem
.length
== 1) {
3315 aResultItem
.push(jsonResult
);
3317 // Capture the array of data field values in an array of results
3318 aResults
.unshift(aResultItem
);
3325 if(aResults
=== null) {
3326 this.dataErrorEvent
.fire(this, oParent
, sQuery
, YAHOO
.widget
.DataSource
.ERROR_DATAPARSE
);
3331 resultObj
.query
= decodeURIComponent(sQuery
);
3332 resultObj
.results
= aResults
;
3333 this._addCacheElem(resultObj
);
3335 this.getResultsEvent
.fire(this, oParent
, sQuery
, aResults
);
3338 oCallbackFn(sQuery
, aResults
, oParent
);
3341 /////////////////////////////////////////////////////////////////////////////
3345 /////////////////////////////////////////////////////////////////////////////
3348 * Any success/failure response should decrement counter.
3350 * @method _bumpPendingDown
3353 YAHOO
.widget
.DS_ScriptNode
._bumpPendingDown = function() {
3354 YAHOO
.widget
.DS_ScriptNode
._nPending
--;
3358 /****************************************************************************/
3359 /****************************************************************************/
3360 /****************************************************************************/
3363 * Implementation of YAHOO.widget.DataSource using a native Javascript function as
3364 * its live data source.
3366 * @class DS_JSFunction
3368 * @extends YAHOO.widget.DataSource
3369 * @param oFunction {HTMLFunction} In-memory Javascript function that returns query results as an array of objects.
3370 * @param oConfigs {Object} (optional) Object literal of config params.
3372 YAHOO
.widget
.DS_JSFunction = function(oFunction
, oConfigs
) {
3373 // Set any config params passed in to override defaults
3374 if(oConfigs
&& (oConfigs
.constructor == Object
)) {
3375 for(var sConfig
in oConfigs
) {
3376 this[sConfig
] = oConfigs
[sConfig
];
3380 // Initialization sequence
3381 if(!YAHOO
.lang
.isFunction(oFunction
)) {
3385 this.dataFunction
= oFunction
;
3390 YAHOO
.widget
.DS_JSFunction
.prototype = new YAHOO
.widget
.DataSource();
3392 /////////////////////////////////////////////////////////////////////////////
3394 // Public member variables
3396 /////////////////////////////////////////////////////////////////////////////
3399 * In-memory Javascript function that returns query results.
3401 * @property dataFunction
3402 * @type HTMLFunction
3404 YAHOO
.widget
.DS_JSFunction
.prototype.dataFunction
= null;
3406 /////////////////////////////////////////////////////////////////////////////
3410 /////////////////////////////////////////////////////////////////////////////
3413 * Queries the live data source defined by function for results. Results are
3414 * passed back to a callback function.
3417 * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results.
3418 * @param sQuery {String} Query string.
3419 * @param oParent {Object} The object instance that has requested data.
3421 YAHOO
.widget
.DS_JSFunction
.prototype.doQuery = function(oCallbackFn
, sQuery
, oParent
) {
3422 var oFunction
= this.dataFunction
;
3425 aResults
= oFunction(sQuery
);
3426 if(aResults
=== null) {
3427 this.dataErrorEvent
.fire(this, oParent
, sQuery
, YAHOO
.widget
.DataSource
.ERROR_DATANULL
);
3432 resultObj
.query
= decodeURIComponent(sQuery
);
3433 resultObj
.results
= aResults
;
3434 this._addCacheElem(resultObj
);
3436 this.getResultsEvent
.fire(this, oParent
, sQuery
, aResults
);
3437 oCallbackFn(sQuery
, aResults
, oParent
);
3442 /****************************************************************************/
3443 /****************************************************************************/
3444 /****************************************************************************/
3447 * Implementation of YAHOO.widget.DataSource using a native Javascript array as
3448 * its live data source.
3452 * @extends YAHOO.widget.DataSource
3453 * @param aData {String[]} In-memory Javascript array of simple string data.
3454 * @param oConfigs {Object} (optional) Object literal of config params.
3456 YAHOO
.widget
.DS_JSArray = function(aData
, oConfigs
) {
3457 // Set any config params passed in to override defaults
3458 if(oConfigs
&& (oConfigs
.constructor == Object
)) {
3459 for(var sConfig
in oConfigs
) {
3460 this[sConfig
] = oConfigs
[sConfig
];
3464 // Initialization sequence
3465 if(!YAHOO
.lang
.isArray(aData
)) {
3474 YAHOO
.widget
.DS_JSArray
.prototype = new YAHOO
.widget
.DataSource();
3476 /////////////////////////////////////////////////////////////////////////////
3478 // Public member variables
3480 /////////////////////////////////////////////////////////////////////////////
3483 * In-memory Javascript array of strings.
3488 YAHOO
.widget
.DS_JSArray
.prototype.data
= null;
3490 /////////////////////////////////////////////////////////////////////////////
3494 /////////////////////////////////////////////////////////////////////////////
3497 * Queries the live data source defined by data for results. Results are passed
3498 * back to a callback function.
3501 * @param oCallbackFn {HTMLFunction} Callback function defined by oParent object to which to return results.
3502 * @param sQuery {String} Query string.
3503 * @param oParent {Object} The object instance that has requested data.
3505 YAHOO
.widget
.DS_JSArray
.prototype.doQuery = function(oCallbackFn
, sQuery
, oParent
) {
3507 var aData
= this.data
; // the array
3508 var aResults
= []; // container for results
3509 var bMatchFound
= false;
3510 var bMatchContains
= this.queryMatchContains
;
3512 if(!this.queryMatchCase
) {
3513 sQuery
= sQuery
.toLowerCase();
3516 // Loop through each element of the array...
3517 // which can be a string or an array of strings
3518 for(i
= aData
.length
-1; i
>= 0; i
--) {
3521 if(YAHOO
.lang
.isString(aData
[i
])) {
3522 aDataset
[0] = aData
[i
];
3524 else if(YAHOO
.lang
.isArray(aData
[i
])) {
3525 aDataset
= aData
[i
];
3528 if(YAHOO
.lang
.isString(aDataset
[0])) {
3529 var sKeyIndex
= (this.queryMatchCase
) ?
3530 encodeURIComponent(aDataset
[0]).indexOf(sQuery
):
3531 encodeURIComponent(aDataset
[0]).toLowerCase().indexOf(sQuery
);
3533 // A STARTSWITH match is when the query is found at the beginning of the key string...
3534 if((!bMatchContains
&& (sKeyIndex
=== 0)) ||
3535 // A CONTAINS match is when the query is found anywhere within the key string...
3536 (bMatchContains
&& (sKeyIndex
> -1))) {
3537 // Stash a match into aResults[].
3538 aResults
.unshift(aDataset
);
3544 for(i
= aData
.length
-1; i
>= 0; i
--) {
3545 if(YAHOO
.lang
.isString(aData
[i
])) {
3546 aResults
.unshift([aData
[i
]]);
3548 else if(YAHOO
.lang
.isArray(aData
[i
])) {
3549 aResults
.unshift(aData
[i
]);
3554 this.getResultsEvent
.fire(this, oParent
, sQuery
, aResults
);
3555 oCallbackFn(sQuery
, aResults
, oParent
);
3558 YAHOO
.register("autocomplete", YAHOO
.widget
.AutoComplete
, {version
: "2.5.2", build
: "1076"});