2 * OpenSearch ajax suggestion engine for MediaWiki
4 * uses core MediaWiki open search support to fetch suggestions
5 * and show them below search boxes and other inputs
7 * by Robert Stojnic (April 2008)
10 // search_box_id -> Results object
12 // cached data, url -> json_text
14 // global variables for suggest_keypress
15 var os_cur_keypressed
= 0;
16 var os_keypressed_count
= 0;
19 // tie mousedown/up events
20 var os_mouse_pressed
= false;
21 var os_mouse_num
= -1;
22 // if true, the last change was made by mouse (and not keyboard)
23 var os_mouse_moved
= false;
24 // delay between keypress and suggestion (in ms)
25 var os_search_timeout
= 250;
26 // these pairs of inputs/forms will be autoloaded at startup
27 var os_autoload_inputs
= new Array('searchInput', 'searchInput2', 'powerSearchText', 'searchText');
28 var os_autoload_forms
= new Array('searchform', 'searchform2', 'powersearch', 'search' );
29 // if we stopped the service
30 var os_is_stopped
= false;
31 // max lines to show in suggest table
32 var os_max_lines_per_suggest
= 7;
33 // number of steps to animate expansion/contraction of container width
34 var os_animation_steps
= 6;
35 // num of pixels of smallest step
36 var os_animation_min_step
= 2;
37 // delay between steps (in ms)
38 var os_animation_delay
= 30;
39 // max width of container in percent of normal size (1 == 100%)
40 var os_container_max_width
= 2;
41 // currently active animation timer
42 var os_animation_timer
= null;
44 * <datalist> is a new HTML5 element that allows you to manually supply
45 * suggestion lists and have them rendered according to the right platform
46 * conventions. However, the only shipping browser as of early 2010 is Opera,
47 * and that has a fatal problem: the suggestion lags behind what the user types
48 * by one keypress. (Reported as DSK-276870 to Opera's secret bug tracker.)
49 * The code here otherwise seems to work, though, so this can be flipped on
50 * (maybe with a UA check) when some browser has a better implementation.
52 // var os_use_datalist = 'list' in document.createElement( 'input' );
53 var os_use_datalist
= false;
55 /** Timeout timer class that will fetch the results */
56 function os_Timer( id
, r
, query
) {
62 /** Property class for single search box */
63 function os_Results( name
, formname
) {
64 this.searchform
= formname
; // id of the searchform
65 this.searchbox
= name
; // id of the searchbox
66 this.container
= name
+ 'Suggest'; // div that holds results
67 this.resultTable
= name
+ 'Result'; // id base for the result table (+num = table row)
68 this.resultText
= name
+ 'ResultText'; // id base for the spans within result tables (+num)
69 this.toggle
= name
+ 'Toggle'; // div that has the toggle (enable/disable) link
70 this.query
= null; // last processed query
71 this.results
= null; // parsed titles
72 this.resultCount
= 0; // number of results
73 this.original
= null; // query that user entered
74 this.selected
= -1; // which result is selected
75 this.containerCount
= 0; // number of results visible in container
76 this.containerRow
= 0; // height of result field in the container
77 this.containerTotal
= 0; // total height of the container will all results
78 this.visible
= false; // if container is visible
79 this.stayHidden
= false; // don't try to show if lost focus
82 /** Timer user to animate expansion/contraction of container width */
83 function os_AnimationTimer( r, target ) {
85 var current = document.getElementById(r.container).offsetWidth;
86 this.inc = Math.round( ( target - current ) / os_animation_steps );
87 if( this.inc < os_animation_min_step && this.inc >=0 ) {
88 this.inc = os_animation_min_step; // minimal animation step
90 if( this.inc > -os_animation_min_step && this.inc < 0 ) {
91 this.inc = -os_animation_min_step;
100 /** Initialization, call upon page onload */
101 function os_MWSuggestInit() {
102 for( i
= 0; i
< os_autoload_inputs
.length
; i
++ ) {
103 var id
= os_autoload_inputs
[i
];
104 var form
= os_autoload_forms
[i
];
105 element
= document
.getElementById( id
);
106 if( element
!= null ) {
107 os_initHandlers( id
, form
, element
);
112 /** Init Result objects and event handlers */
113 function os_initHandlers( name
, formname
, element
) {
114 var r
= new os_Results( name
, formname
);
116 os_hookEvent( element
, 'keyup', function( event
) { os_eventKeyup( event
); } );
117 os_hookEvent( element
, 'keydown', function( event
) { os_eventKeydown( event
); } );
118 os_hookEvent( element
, 'keypress', function( event
) { os_eventKeypress( event
); } );
119 if ( !os_use_datalist
) {
120 // These are needed for the div hack to hide it if the user blurs.
121 os_hookEvent( element
, 'blur', function( event
) { os_eventBlur( event
); } );
122 os_hookEvent( element
, 'focus', function( event
) { os_eventFocus( event
); } );
123 // We don't want browser auto-suggestions interfering with our div, but
124 // autocomplete must be on for datalist to work (at least in Opera
126 element
.setAttribute( 'autocomplete', 'off' );
129 os_hookEvent( document
.getElementById( formname
), 'submit', function( event
) { return os_eventOnsubmit( event
); } );
132 if( document
.getElementById( r
.toggle
) == null ) {
133 // TODO: disable this while we figure out a way for this to work in all browsers
134 /* if( name == 'searchInput' ) {
135 // special case: place above the main search box
136 var t = os_createToggle( r, 'os-suggest-toggle' );
137 var searchBody = document.getElementById( 'searchBody' );
138 var first = searchBody.parentNode.firstChild.nextSibling.appendChild(t);
140 // default: place below search box to the right
141 var t = os_createToggle( r, 'os-suggest-toggle-def' );
142 var top = element.offsetTop + element.offsetHeight;
143 var left = element.offsetLeft + element.offsetWidth;
144 t.style.position = 'absolute';
145 t.style.top = top + 'px';
146 t.style.left = left + 'px';
147 element.parentNode.appendChild( t );
148 // only now width gets calculated, shift right
149 left -= t.offsetWidth;
150 t.style.left = left + 'px';
151 t.style.visibility = 'visible';
157 function os_hookEvent( element
, hookName
, hookFunct
) {
158 if ( element
.addEventListener
) {
159 element
.addEventListener( hookName
, hookFunct
, false );
160 } else if ( window
.attachEvent
) {
161 element
.attachEvent( 'on' + hookName
, hookFunct
);
165 /********************
167 ********************/
169 /** Event handler that will fetch results on keyup */
170 function os_eventKeyup( e
) {
171 var targ
= os_getTarget( e
);
172 var r
= os_map
[targ
.id
];
174 return; // not our event
177 // some browsers won't generate keypressed for arrow keys, catch it
178 if( os_keypressed_count
== 0 ) {
179 os_processKey( r
, os_cur_keypressed
, targ
);
181 var query
= targ
.value
;
182 os_fetchResults( r
, query
, os_search_timeout
);
185 /** catch arrows up/down and escape to hide the suggestions */
186 function os_processKey( r, keypressed, targ ) {
187 if ( keypressed == 40 && !r.visible && os_timer == null ) {
188 // If the user hits the down arrow, fetch results immediately if none
189 // are already displayed.
191 os_fetchResults( r, targ.value, 0 );
193 // Otherwise, if we're not using datalist, we need to handle scrolling and
195 if ( os_use_datalist ) {
198 if ( keypressed == 40 ) { // Arrow Down
200 os_changeHighlight( r, r.selected, r.selected + 1, true );
202 } else if ( keypressed == 38 ) { // Arrow Up
204 os_changeHighlight( r, r.selected, r.selected - 1, true );
206 } else if( keypressed == 27 ) { // Escape
207 document.getElementById( r.searchbox ).value = r.original;
208 r.query = r.original;
210 } else if( r.query != document.getElementById( r.searchbox ).value ) {
211 // os_hideResults( r ); // don't show old suggestions
215 /** When keys is held down use a timer to output regular events */
216 function os_eventKeypress( e
) {
217 var targ
= os_getTarget( e
);
218 var r
= os_map
[targ
.id
];
220 return; // not our event
223 var keypressed
= os_cur_keypressed
;
225 os_keypressed_count
++;
226 os_processKey( r
, keypressed
, targ
);
229 /** Catch the key code (Firefox bug) */
230 function os_eventKeydown( e
) {
234 var targ
= os_getTarget( e
);
235 var r
= os_map
[targ
.id
];
237 return; // not our event
240 os_mouse_moved
= false;
242 os_cur_keypressed
= ( e
.keyCode
== undefined ) ? e
.which
: e
.keyCode
;
243 os_keypressed_count
= 0;
247 /** When the form is submitted hide everything, cancel updates... */
248 function os_eventOnsubmit( e
) {
249 var targ
= os_getTarget( e
);
251 os_is_stopped
= true;
252 // kill timed requests
253 if( os_timer
!= null && os_timer
.id
!= null ) {
254 clearTimeout( os_timer
.id
);
257 // Hide all suggestions
258 for( i
= 0; i
< os_autoload_inputs
.length
; i
++ ) {
259 var r
= os_map
[os_autoload_inputs
[i
]];
261 var b
= document
.getElementById( r
.searchform
);
262 if( b
!= null && b
== targ
) {
263 // set query value so the handler won't try to fetch additional results
264 r
.query
= document
.getElementById( r
.searchbox
).value
;
274 /** Hide results from the user, either making the div visibility=hidden or
275 * detaching the datalist from the input. */
276 function os_hideResults( r
) {
277 if ( os_use_datalist
) {
278 document
.getElementById( r
.searchbox
).setAttribute( 'list', '' );
280 var c
= document
.getElementById( r
.container
);
282 c
.style
.visibility
= 'hidden';
289 function os_decodeValue( value
) {
290 if ( decodeURIComponent
) {
291 return decodeURIComponent( value
);
294 return unescape( value
);
299 function os_encodeQuery( value
) {
300 if ( encodeURIComponent
) {
301 return encodeURIComponent( value
);
304 return escape( value
);
309 /** Handles data from XMLHttpRequest, and updates the suggest results */
310 function os_updateResults( r
, query
, text
, cacheKey
) {
311 os_cache
[cacheKey
] = text
;
320 var p
= eval( '(' + text
+ ')' ); // simple json parse, could do a safer one
321 if( p
.length
< 2 || p
[1].length
== 0 ) {
327 if ( os_use_datalist
) {
328 os_setupDatalist( r
, p
[1] );
330 os_setupDiv( r
, p
[1] );
333 // bad response from server or such
335 os_cache
[cacheKey
] = null;
341 * Create and populate a <datalist>.
343 * @param r os_Result object
344 * @param results Array of the new results to replace existing ones
346 function os_setupDatalist( r
, results
) {
347 var s
= document
.getElementById( r
.searchbox
);
348 var c
= document
.getElementById( r
.container
);
350 c
= document
.createElement( 'datalist' );
351 c
.setAttribute( 'id', r
.container
);
352 document
.body
.appendChild( c
);
356 s
.setAttribute( 'list', r
.container
);
358 r
.results
= new Array();
359 r
.resultCount
= results
.length
;
361 for ( i
= 0; i
< results
.length
; i
++ ) {
362 var title
= os_decodeValue( results
[i
] );
363 var opt
= document
.createElement( 'option' );
365 r
.results
[i
] = title
;
366 c
.appendChild( opt
);
370 /** Fetch namespaces from checkboxes or hidden fields in the search form,
371 if none defined use wgSearchNamespaces global */
372 function os_getNamespaces( r
) {
374 var elements
= document
.forms
[r
.searchform
].elements
;
375 for( i
= 0; i
< elements
.length
; i
++ ) {
376 var name
= elements
[i
].name
;
377 if( typeof name
!= 'undefined' && name
.length
> 2 && name
[0] == 'n' &&
379 ( elements
[i
].type
== 'checkbox' && elements
[i
].checked
) ||
380 ( elements
[i
].type
== 'hidden' && elements
[i
].value
== '1' )
383 if( namespaces
!= '' ) {
386 namespaces
+= name
.substring( 2 );
389 if( namespaces
== '' ) {
390 namespaces
= wgSearchNamespaces
.join('|');
395 /** Update results if user hasn't already typed something else */
396 function os_updateIfRelevant( r
, query
, text
, cacheKey
) {
397 var t
= document
.getElementById( r
.searchbox
);
398 if( t
!= null && t
.value
== query
) { // check if response is still relevant
399 os_updateResults( r
, query
, text
, cacheKey
);
404 /** Fetch results after some timeout */
405 function os_delayedFetch() {
406 if( os_timer
== null ) {
410 var query
= os_timer
.query
;
412 var path
= wgMWSuggestTemplate
.replace( "{namespaces}", os_getNamespaces( r
) )
413 .replace( "{dbname}", wgDBname
)
414 .replace( "{searchTerms}", os_encodeQuery( query
) );
416 // try to get from cache, if not fetch using ajax
417 var cached
= os_cache
[path
];
418 if( cached
!= null && cached
!= undefined ) {
419 os_updateIfRelevant( r
, query
, cached
, path
);
421 var xmlhttp
= sajax_init_object();
424 xmlhttp
.open( 'GET', path
, true );
425 xmlhttp
.onreadystatechange = function() {
426 if ( xmlhttp
.readyState
== 4 && typeof os_updateIfRelevant
== 'function' ) {
427 os_updateIfRelevant( r
, query
, xmlhttp
.responseText
, path
);
430 xmlhttp
.send( null );
432 if ( window
.location
.hostname
== 'localhost' ) {
433 alert( "Your browser blocks XMLHttpRequest to 'localhost', try using a real hostname for development/testing." );
441 /** Init timed update via os_delayedUpdate() */
442 function os_fetchResults( r
, query
, timeout
) {
447 } else if( query
== r
.query
) {
451 os_is_stopped
= false; // make sure we're running
453 // cancel any pending fetches
454 if( os_timer
!= null && os_timer
.id
!= null ) {
455 clearTimeout( os_timer
.id
);
457 // schedule delayed fetching of results
459 os_timer
= new os_Timer( setTimeout( "os_delayedFetch()", timeout
), r
, query
);
461 os_timer
= new os_Timer( null, r
, query
);
462 os_delayedFetch(); // do it now!
466 /** Find event target */
467 function os_getTarget( e
) {
473 } else if ( e
.srcElement
) {
480 /** Check if x is a valid integer */
481 function os_isNumber( x
) {
482 if( x
== '' || isNaN( x
) ) {
485 for( var i
= 0; i
< x
.length
; i
++ ) {
486 var c
= x
.charAt( i
);
487 if( !( c
>= '0' && c
<= '9' ) ) {
494 /** Call this to enable suggestions on input (id=inputId), on a form (name=formName) */
495 function os_enableSuggestionsOn( inputId
, formName
) {
496 os_initHandlers( inputId
, formName
, document
.getElementById( inputId
) );
499 /** Call this to disable suggestios on input box (id=inputId) */
500 function os_disableSuggestionsOn( inputId
) {
503 // cancel/hide results
506 // turn autocomplete on !
507 document
.getElementById( inputId
).setAttribute( 'autocomplete', 'on' );
509 os_map
[inputId
] = null;
512 // Remove the element from the os_autoload_* arrays
513 var index
= os_autoload_inputs
.indexOf( inputId
);
515 os_autoload_inputs
[index
] = os_autoload_forms
[index
] = '';
519 /************************************************
520 * Div-only functions (irrelevant for datalist)
521 ************************************************/
523 /** Event: loss of focus of input box */
524 function os_eventBlur( e
) {
525 var targ
= os_getTarget( e
);
526 var r
= os_map
[targ
.id
];
528 return; // not our event
530 if( !os_mouse_pressed
) {
532 // force canvas to stay hidden
534 // cancel any pending fetches
535 if( os_timer
!= null && os_timer
.id
!= null ) {
536 clearTimeout( os_timer
.id
);
542 /** Event: focus (catch only when stopped) */
543 function os_eventFocus( e
) {
544 var targ
= os_getTarget( e
);
545 var r
= os_map
[targ
.id
];
547 return; // not our event
549 r
.stayHidden
= false;
553 * Create and populate a <div>, for non-<datalist>-supporting browsers.
555 * @param r os_Result object
556 * @param results Array of the new results to replace existing ones
558 function os_setupDiv( r
, results
) {
559 var c
= document
.getElementById( r
.container
);
561 c
= os_createContainer( r
);
563 c
.innerHTML
= os_createResultTable( r
, results
);
564 // init container table sizes
565 var t
= document
.getElementById( r
.resultTable
);
566 r
.containerTotal
= t
.offsetHeight
;
567 r
.containerRow
= t
.offsetHeight
/ r
.resultCount
;
568 os_fitContainer( r
);
569 os_trimResultText( r
);
573 /** Create the result table to be placed in the container div */
574 function os_createResultTable( r
, results
) {
575 var c
= document
.getElementById( r
.container
);
576 var width
= c
.offsetWidth
- os_operaWidthFix( c
.offsetWidth
);
577 var html
= '<table class="os-suggest-results" id="' + r
.resultTable
+ '" style="width: ' + width
+ 'px;">';
578 r
.results
= new Array();
579 r
.resultCount
= results
.length
;
580 for( i
= 0; i
< results
.length
; i
++ ) {
581 var title
= os_decodeValue( results
[i
] );
582 r
.results
[i
] = title
;
583 html
+= '<tr><td class="os-suggest-result" id="' + r
.resultTable
+ i
+ '"><span id="' + r
.resultText
+ i
+ '">' + title
+ '</span></td></tr>';
589 /** Show results div */
590 function os_showResults( r
) {
591 if( os_is_stopped
) {
597 os_fitContainer( r
);
598 var c
= document
.getElementById( r
.container
);
602 c
.style
.visibility
= 'visible';
607 function os_operaWidthFix( x
) {
608 // For browsers that don't understand overflow-x, estimate scrollbar width
609 if( typeof document
.body
.style
.overflowX
!= 'string' ) {
615 /** Brower-dependent functions to find window inner size, and scroll status */
616 function f_clientWidth() {
617 return f_filterResults(
618 window
.innerWidth
? window
.innerWidth
: 0,
619 document
.documentElement
? document
.documentElement
.clientWidth
: 0,
620 document
.body
? document
.body
.clientWidth
: 0
624 function f_clientHeight() {
625 return f_filterResults(
626 window
.innerHeight
? window
.innerHeight
: 0,
627 document
.documentElement
? document
.documentElement
.clientHeight
: 0,
628 document
.body
? document
.body
.clientHeight
: 0
632 function f_scrollLeft() {
633 return f_filterResults(
634 window
.pageXOffset
? window
.pageXOffset
: 0,
635 document
.documentElement
? document
.documentElement
.scrollLeft
: 0,
636 document
.body
? document
.body
.scrollLeft
: 0
640 function f_scrollTop() {
641 return f_filterResults(
642 window
.pageYOffset
? window
.pageYOffset
: 0,
643 document
.documentElement
? document
.documentElement
.scrollTop
: 0,
644 document
.body
? document
.body
.scrollTop
: 0
648 function f_filterResults( n_win
, n_docel
, n_body
) {
649 var n_result
= n_win
? n_win
: 0;
650 if ( n_docel
&& ( !n_result
|| ( n_result
> n_docel
) ) ) {
653 return n_body
&& ( !n_result
|| ( n_result
> n_body
) ) ? n_body
: n_result
;
656 /** Get the height available for the results container */
657 function os_availableHeight( r
) {
658 var absTop
= document
.getElementById( r
.container
).style
.top
;
659 var px
= absTop
.lastIndexOf( 'px' );
661 absTop
= absTop
.substring( 0, px
);
663 return f_clientHeight() - ( absTop
- f_scrollTop() );
666 /** Get element absolute position {left,top} */
667 function os_getElementPosition( elemID
) {
668 var offsetTrail
= document
.getElementById( elemID
);
671 while ( offsetTrail
) {
672 offsetLeft
+= offsetTrail
.offsetLeft
;
673 offsetTop
+= offsetTrail
.offsetTop
;
674 offsetTrail
= offsetTrail
.offsetParent
;
676 if ( navigator
.userAgent
.indexOf('Mac') != -1 && typeof document
.body
.leftMargin
!= 'undefined' ) {
677 offsetLeft
+= document
.body
.leftMargin
;
678 offsetTop
+= document
.body
.topMargin
;
680 return { left
:offsetLeft
, top
:offsetTop
};
683 /** Create the container div that will hold the suggested titles */
684 function os_createContainer( r
) {
685 var c
= document
.createElement( 'div' );
686 var s
= document
.getElementById( r
.searchbox
);
687 var pos
= os_getElementPosition( r
.searchbox
);
689 var top
= pos
.top
+ s
.offsetHeight
;
690 c
.className
= 'os-suggest';
691 c
.setAttribute( 'id', r
.container
);
692 document
.body
.appendChild( c
);
694 // dynamically generated style params
695 // IE workaround, cannot explicitely set "style" attribute
696 c
= document
.getElementById( r
.container
);
697 c
.style
.top
= top
+ 'px';
698 c
.style
.left
= left
+ 'px';
699 c
.style
.width
= s
.offsetWidth
+ 'px';
701 // mouse event handlers
702 c
.onmouseover = function( event
) { os_eventMouseover( r
.searchbox
, event
); };
703 c
.onmousemove = function( event
) { os_eventMousemove( r
.searchbox
, event
); };
704 c
.onmousedown = function( event
) { return os_eventMousedown( r
.searchbox
, event
); };
705 c
.onmouseup = function( event
) { os_eventMouseup( r
.searchbox
, event
); };
709 /** change container height to fit to screen */
710 function os_fitContainer( r
) {
711 var c
= document
.getElementById( r
.container
);
712 var h
= os_availableHeight( r
) - 20;
713 var inc
= r
.containerRow
;
714 h
= parseInt( h
/ inc
) * inc
;
715 if( h
< ( 2 * inc
) && r
.resultCount
> 1 ) { // min: two results
718 if( ( h
/ inc
) > os_max_lines_per_suggest
) {
719 h
= inc
* os_max_lines_per_suggest
;
721 if( h
< r
.containerTotal
) {
722 c
.style
.height
= h
+ 'px';
723 r
.containerCount
= parseInt( Math
.round( h
/ inc
) );
725 c
.style
.height
= r
.containerTotal
+ 'px';
726 r
.containerCount
= r
.resultCount
;
730 /** If some entries are longer than the box, replace text with "..." */
731 function os_trimResultText( r
) {
732 // find max width, first see if we could expand the container to fit it
734 for( var i
= 0; i
< r
.resultCount
; i
++ ) {
735 var e
= document
.getElementById( r
.resultText
+ i
);
736 if( e
.offsetWidth
> maxW
) {
737 maxW
= e
.offsetWidth
;
740 var w
= document
.getElementById( r
.container
).offsetWidth
;
742 if( r
.containerCount
< r
.resultCount
) {
743 fix
= 20; // give 20px for scrollbar
745 fix
= os_operaWidthFix( w
);
748 fix
= 4; // basic padding
752 // resize container to fit more data if permitted
753 var normW
= document
.getElementById( r
.searchbox
).offsetWidth
;
754 var prop
= maxW
/ normW
;
755 if( prop
> os_container_max_width
) {
756 prop
= os_container_max_width
;
757 } else if( prop
< 1 ) {
760 var newW
= Math
.round( normW
* prop
);
763 if( os_animation_timer
!= null ) {
764 clearInterval( os_animation_timer
.id
);
766 os_animation_timer
= new os_AnimationTimer( r
, w
);
767 os_animation_timer
.id
= setInterval( "os_animateChangeWidth()", os_animation_delay
);
768 w
-= fix
; // this much is reserved
775 for( var i
= 0; i
< r
.resultCount
; i
++ ) {
776 var e
= document
.getElementById( r
.resultText
+ i
);
778 var lastW
= e
.offsetWidth
+ 1;
780 var changedText
= false;
781 while( e
.offsetWidth
> w
&& ( e
.offsetWidth
< lastW
|| iteration
< 2 ) ) {
783 lastW
= e
.offsetWidth
;
785 e
.innerHTML
= l
.substring( 0, l
.length
- replace
) + '...';
787 replace
= 4; // how many chars to replace
790 // show hint for trimmed titles
791 document
.getElementById( r
.resultTable
+ i
).setAttribute( 'title', r
.results
[i
] );
796 /** Invoked on timer to animate change in container width */
797 function os_animateChangeWidth() {
798 var r
= os_animation_timer
.r
;
799 var c
= document
.getElementById( r
.container
);
800 var w
= c
.offsetWidth
;
801 var normW
= document
.getElementById( r
.searchbox
).offsetWidth
;
802 var normL
= os_getElementPosition( r
.searchbox
).left
;
803 var inc
= os_animation_timer
.inc
;
804 var target
= os_animation_timer
.target
;
806 if( ( inc
> 0 && nw
>= target
) || ( inc
<= 0 && nw
<= target
) ) {
808 c
.style
.width
= target
+ 'px';
809 clearInterval( os_animation_timer
.id
);
810 os_animation_timer
= null;
813 c
.style
.width
= nw
+ 'px';
814 if( document
.documentElement
.dir
== 'rtl' ) {
815 c
.style
.left
= ( normL
+ normW
+ ( target
- nw
) - os_animation_timer
.target
- 1 ) + 'px';
820 /** Change the highlighted row (i.e. suggestion), from position cur to next */
821 function os_changeHighlight( r
, cur
, next
, updateSearchBox
) {
822 if ( next
>= r
.resultCount
) {
823 next
= r
.resultCount
- 1;
830 return; // nothing to do.
834 var curRow
= document
.getElementById( r
.resultTable
+ cur
);
835 if( curRow
!= null ) {
836 curRow
.className
= 'os-suggest-result';
841 var nextRow
= document
.getElementById( r
.resultTable
+ next
);
842 if( nextRow
!= null ) {
843 nextRow
.className
= os_HighlightClass();
845 newText
= r
.results
[next
];
847 newText
= r
.original
;
850 // adjust the scrollbar if any
851 if( r
.containerCount
< r
.resultCount
) {
852 var c
= document
.getElementById( r
.container
);
853 var vStart
= c
.scrollTop
/ r
.containerRow
;
854 var vEnd
= vStart
+ r
.containerCount
;
855 if( next
< vStart
) {
856 c
.scrollTop
= next
* r
.containerRow
;
857 } else if( next
>= vEnd
) {
858 c
.scrollTop
= ( next
- r
.containerCount
+ 1 ) * r
.containerRow
;
862 // update the contents of the search box
863 if( updateSearchBox
) {
864 os_updateSearchQuery( r
, newText
);
868 function os_HighlightClass() {
869 var match
= navigator
.userAgent
.match(/AppleWebKit\/(\d+)/);
871 var webKitVersion
= parseInt( match
[1] );
872 if ( webKitVersion
< 523 ) {
873 // CSS system highlight colors broken on old Safari
874 // https://bugs.webkit.org/show_bug.cgi?id=6129
875 // Safari 3.0.4, 3.1 known ok
876 return 'os-suggest-result-hl-webkit';
879 return 'os-suggest-result-hl';
882 function os_updateSearchQuery( r
, newText
) {
883 document
.getElementById( r
.searchbox
).value
= newText
;
888 /********************
890 ********************/
892 /** Mouse over the container */
893 function os_eventMouseover( srcId
, e
) {
894 var targ
= os_getTarget( e
);
895 var r
= os_map
[srcId
];
896 if( r
== null || !os_mouse_moved
) {
897 return; // not our event
899 var num
= os_getNumberSuffix( targ
.id
);
901 os_changeHighlight( r
, r
.selected
, num
, false );
905 /* Get row where the event occured (from its id) */
906 function os_getNumberSuffix( id
) {
907 var num
= id
.substring( id
.length
- 2 );
908 if( !( num
.charAt( 0 ) >= '0' && num
.charAt( 0 ) <= '9' ) ) {
909 num
= num
.substring( 1 );
911 if( os_isNumber( num
) ) {
912 return parseInt( num
);
918 /** Save mouse move as last action */
919 function os_eventMousemove( srcId
, e
) {
920 os_mouse_moved
= true;
923 /** Mouse button held down, register possible click */
924 function os_eventMousedown( srcId
, e
) {
925 var targ
= os_getTarget( e
);
926 var r
= os_map
[srcId
];
928 return; // not our event
930 var num
= os_getNumberSuffix( targ
.id
);
932 os_mouse_pressed
= true;
935 // os_updateSearchQuery( r, r.results[num] );
937 // keep the focus on the search field
938 document
.getElementById( r
.searchbox
).focus();
940 return false; // prevents selection
943 /** Mouse button released, check for click on some row */
944 function os_eventMouseup( srcId
, e
) {
945 var targ
= os_getTarget( e
);
946 var r
= os_map
[srcId
];
948 return; // not our event
950 var num
= os_getNumberSuffix( targ
.id
);
952 if( num
>= 0 && os_mouse_num
== num
) {
953 os_updateSearchQuery( r
, r
.results
[num
] );
955 document
.getElementById( r
.searchform
).submit();
957 os_mouse_pressed
= false;
958 // keep the focus on the search field
959 document
.getElementById( r
.searchbox
).focus();
962 /** Toggle stuff seems to be dead code? */
964 /** Return the span element that contains the toggle link */
965 function os_createToggle( r
, className
) {
966 var t
= document
.createElement( 'span' );
967 t
.className
= className
;
968 t
.setAttribute( 'id', r
.toggle
);
969 var link
= document
.createElement( 'a' );
970 link
.setAttribute( 'href', 'javascript:void(0);' );
971 link
.onclick = function() { os_toggle( r
.searchbox
, r
.searchform
); };
972 var msg
= document
.createTextNode( wgMWSuggestMessages
[0] );
973 link
.appendChild( msg
);
974 t
.appendChild( link
);
978 /** Call when user clicks on some of the toggle links */
979 function os_toggle( inputId
, formName
) {
983 os_enableSuggestionsOn( inputId
, formName
);
985 msg
= wgMWSuggestMessages
[0];
987 os_disableSuggestionsOn( inputId
, formName
);
988 msg
= wgMWSuggestMessages
[1];
991 var link
= document
.getElementById( r
.toggle
).firstChild
;
992 link
.replaceChild( document
.createTextNode( msg
), link
.firstChild
);
995 hookEvent( 'load', os_MWSuggestInit
);