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 window
.os_cur_keypressed
= 0;
16 window
.os_keypressed_count
= 0;
18 window
.os_timer
= null;
19 // tie mousedown/up events
20 window
.os_mouse_pressed
= false;
21 window
.os_mouse_num
= -1;
22 // if true, the last change was made by mouse (and not keyboard)
23 window
.os_mouse_moved
= false;
24 // delay between keypress and suggestion (in ms)
25 window
.os_search_timeout
= 250;
26 // these pairs of inputs/forms will be autoloaded at startup
27 window
.os_autoload_inputs
= new Array('searchInput', 'searchInput2', 'powerSearchText', 'searchText');
28 window
.os_autoload_forms
= new Array('searchform', 'searchform2', 'powersearch', 'search' );
29 // if we stopped the service
30 window
.os_is_stopped
= false;
31 // max lines to show in suggest table
32 window
.os_max_lines_per_suggest
= 7;
33 // number of steps to animate expansion/contraction of container width
34 window
.os_animation_steps
= 6;
35 // num of pixels of smallest step
36 window
.os_animation_min_step
= 2;
37 // delay between steps (in ms)
38 window
.os_animation_delay
= 30;
39 // max width of container in percent of normal size (1 == 100%)
40 window
.os_container_max_width
= 2;
41 // currently active animation timer
42 window
.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. Opera as of version 11 has a fatal problem: the suggestion
47 * lags behind what the user types by one keypress. (Reported as DSK-276870 to
48 * Opera's secret bug tracker.) However, Firefox 4 supports it without
49 * problems, so Opera is just blacklisted here. Ideally we wouldn't blacklist
50 * future versions, in case they fix it, but the fallback isn't bad at all and
51 * the failure if they don't fix it is very annoying, so in this case we'll
52 * blacklist future versions too.
54 window
.os_use_datalist
= 'list' in document
.createElement( 'input' )
55 && $.client
.profile
.name
!= 'opera';
57 /** Timeout timer class that will fetch the results */
58 window
.os_Timer = function( id
, r
, query
) {
64 /** Property class for single search box */
65 window
.os_Results = function( name
, formname
) {
66 this.searchform
= formname
; // id of the searchform
67 this.searchbox
= name
; // id of the searchbox
68 this.container
= name
+ 'Suggest'; // div that holds results
69 this.resultTable
= name
+ 'Result'; // id base for the result table (+num = table row)
70 this.resultText
= name
+ 'ResultText'; // id base for the spans within result tables (+num)
71 this.toggle
= name
+ 'Toggle'; // div that has the toggle (enable/disable) link
72 this.query
= null; // last processed query
73 this.results
= null; // parsed titles
74 this.resultCount
= 0; // number of results
75 this.original
= null; // query that user entered
76 this.selected
= -1; // which result is selected
77 this.containerCount
= 0; // number of results visible in container
78 this.containerRow
= 0; // height of result field in the container
79 this.containerTotal
= 0; // total height of the container will all results
80 this.visible
= false; // if container is visible
81 this.stayHidden
= false; // don't try to show if lost focus
84 /** Timer user to animate expansion/contraction of container width */
85 window.os_AnimationTimer = function( r, target ) {
87 var current = document.getElementById(r.container).offsetWidth;
88 this.inc = Math.round( ( target - current ) / os_animation_steps );
89 if( this.inc < os_animation_min_step && this.inc >=0 ) {
90 this.inc = os_animation_min_step; // minimal animation step
92 if( this.inc > -os_animation_min_step && this.inc < 0 ) {
93 this.inc = -os_animation_min_step;
102 /** Initialization, call upon page onload */
103 window
.os_MWSuggestInit = function() {
104 for( i
= 0; i
< os_autoload_inputs
.length
; i
++ ) {
105 var id
= os_autoload_inputs
[i
];
106 var form
= os_autoload_forms
[i
];
107 element
= document
.getElementById( id
);
108 if( element
!= null ) {
109 os_initHandlers( id
, form
, element
);
114 /** Init Result objects and event handlers */
115 window
.os_initHandlers = function( name
, formname
, element
) {
116 var r
= new os_Results( name
, formname
);
117 var formElement
= document
.getElementById( formname
);
119 // Older browsers (Opera 8) cannot get form elements
123 os_hookEvent( element
, 'keyup', function( event
) { os_eventKeyup( event
); } );
124 os_hookEvent( element
, 'keydown', function( event
) { os_eventKeydown( event
); } );
125 os_hookEvent( element
, 'keypress', function( event
) { os_eventKeypress( event
); } );
126 if ( !os_use_datalist
) {
127 // These are needed for the div hack to hide it if the user blurs.
128 os_hookEvent( element
, 'blur', function( event
) { os_eventBlur( event
); } );
129 os_hookEvent( element
, 'focus', function( event
) { os_eventFocus( event
); } );
130 // We don't want browser auto-suggestions interfering with our div, but
131 // autocomplete must be on for datalist to work (at least in Opera
133 element
.setAttribute( 'autocomplete', 'off' );
136 os_hookEvent( formElement
, 'submit', function( event
) { return os_eventOnsubmit( event
); } );
139 if( document
.getElementById( r
.toggle
) == null ) {
140 // TODO: disable this while we figure out a way for this to work in all browsers
141 /* if( name == 'searchInput' ) {
142 // special case: place above the main search box
143 var t = os_createToggle( r, 'os-suggest-toggle' );
144 var searchBody = document.getElementById( 'searchBody' );
145 var first = searchBody.parentNode.firstChild.nextSibling.appendChild(t);
147 // default: place below search box to the right
148 var t = os_createToggle( r, 'os-suggest-toggle-def' );
149 var top = element.offsetTop + element.offsetHeight;
150 var left = element.offsetLeft + element.offsetWidth;
151 t.style.position = 'absolute';
152 t.style.top = top + 'px';
153 t.style.left = left + 'px';
154 element.parentNode.appendChild( t );
155 // only now width gets calculated, shift right
156 left -= t.offsetWidth;
157 t.style.left = left + 'px';
158 t.style.visibility = 'visible';
164 window
.os_hookEvent = function( element
, hookName
, hookFunct
) {
165 if ( element
.addEventListener
) {
166 element
.addEventListener( hookName
, hookFunct
, false );
167 } else if ( window
.attachEvent
) {
168 element
.attachEvent( 'on' + hookName
, hookFunct
);
172 /********************
174 ********************/
176 /** Event handler that will fetch results on keyup */
177 window
.os_eventKeyup = function( e
) {
178 var targ
= os_getTarget( e
);
179 var r
= os_map
[targ
.id
];
181 return; // not our event
184 // some browsers won't generate keypressed for arrow keys, catch it
185 if( os_keypressed_count
== 0 ) {
186 os_processKey( r
, os_cur_keypressed
, targ
);
188 var query
= targ
.value
;
189 os_fetchResults( r
, query
, os_search_timeout
);
192 /** catch arrows up/down and escape to hide the suggestions */
193 window.os_processKey = function( r, keypressed, targ ) {
194 if ( keypressed == 40 && !r.visible && os_timer == null ) {
195 // If the user hits the down arrow, fetch results immediately if none
196 // are already displayed.
198 os_fetchResults( r, targ.value, 0 );
200 // Otherwise, if we're not using datalist, we need to handle scrolling and
202 if ( os_use_datalist ) {
205 if ( keypressed == 40 ) { // Arrow Down
207 os_changeHighlight( r, r.selected, r.selected + 1, true );
209 } else if ( keypressed == 38 ) { // Arrow Up
211 os_changeHighlight( r, r.selected, r.selected - 1, true );
213 } else if( keypressed == 27 ) { // Escape
214 document.getElementById( r.searchbox ).value = r.original;
215 r.query = r.original;
217 } else if( r.query != document.getElementById( r.searchbox ).value ) {
218 // os_hideResults( r ); // don't show old suggestions
222 /** When keys is held down use a timer to output regular events */
223 window
.os_eventKeypress = function( e
) {
224 var targ
= os_getTarget( e
);
225 var r
= os_map
[targ
.id
];
227 return; // not our event
230 var keypressed
= os_cur_keypressed
;
232 os_keypressed_count
++;
233 os_processKey( r
, keypressed
, targ
);
236 /** Catch the key code (Firefox bug) */
237 window
.os_eventKeydown = function( e
) {
241 var targ
= os_getTarget( e
);
242 var r
= os_map
[targ
.id
];
244 return; // not our event
247 os_mouse_moved
= false;
249 os_cur_keypressed
= ( e
.keyCode
== undefined ) ? e
.which
: e
.keyCode
;
250 os_keypressed_count
= 0;
254 /** When the form is submitted hide everything, cancel updates... */
255 window
.os_eventOnsubmit = function( e
) {
256 var targ
= os_getTarget( e
);
258 os_is_stopped
= true;
259 // kill timed requests
260 if( os_timer
!= null && os_timer
.id
!= null ) {
261 clearTimeout( os_timer
.id
);
264 // Hide all suggestions
265 for( i
= 0; i
< os_autoload_inputs
.length
; i
++ ) {
266 var r
= os_map
[os_autoload_inputs
[i
]];
268 var b
= document
.getElementById( r
.searchform
);
269 if( b
!= null && b
== targ
) {
270 // set query value so the handler won't try to fetch additional results
271 r
.query
= document
.getElementById( r
.searchbox
).value
;
281 /** Hide results from the user, either making the div visibility=hidden or
282 * detaching the datalist from the input. */
283 window
.os_hideResults = function( r
) {
284 if ( os_use_datalist
) {
285 document
.getElementById( r
.searchbox
).setAttribute( 'list', '' );
287 var c
= document
.getElementById( r
.container
);
289 c
.style
.visibility
= 'hidden';
296 window
.os_decodeValue = function( value
) {
297 if ( decodeURIComponent
) {
298 return decodeURIComponent( value
);
301 return unescape( value
);
306 window
.os_encodeQuery = function( value
) {
307 if ( encodeURIComponent
) {
308 return encodeURIComponent( value
);
311 return escape( value
);
316 /** Handles data from XMLHttpRequest, and updates the suggest results */
317 window
.os_updateResults = function( r
, query
, text
, cacheKey
) {
318 os_cache
[cacheKey
] = text
;
327 var p
= eval( '(' + text
+ ')' ); // simple json parse, could do a safer one
328 if( p
.length
< 2 || p
[1].length
== 0 ) {
334 if ( os_use_datalist
) {
335 os_setupDatalist( r
, p
[1] );
337 os_setupDiv( r
, p
[1] );
340 // bad response from server or such
342 os_cache
[cacheKey
] = null;
348 * Create and populate a <datalist>.
350 * @param r os_Result object
351 * @param results Array of the new results to replace existing ones
353 window
.os_setupDatalist = function( r
, results
) {
354 var s
= document
.getElementById( r
.searchbox
);
355 var c
= document
.getElementById( r
.container
);
357 c
= document
.createElement( 'datalist' );
358 c
.setAttribute( 'id', r
.container
);
359 document
.body
.appendChild( c
);
363 s
.setAttribute( 'list', r
.container
);
365 r
.results
= new Array();
366 r
.resultCount
= results
.length
;
368 for ( i
= 0; i
< results
.length
; i
++ ) {
369 var title
= os_decodeValue( results
[i
] );
370 var opt
= document
.createElement( 'option' );
372 r
.results
[i
] = title
;
373 c
.appendChild( opt
);
377 /** Fetch namespaces from checkboxes or hidden fields in the search form,
378 if none defined use wgSearchNamespaces global */
379 window
.os_getNamespaces = function( r
) {
381 var elements
= document
.forms
[r
.searchform
].elements
;
382 for( i
= 0; i
< elements
.length
; i
++ ) {
383 var name
= elements
[i
].name
;
384 if( typeof name
!= 'undefined' && name
.length
> 2 && name
[0] == 'n' &&
386 ( elements
[i
].type
== 'checkbox' && elements
[i
].checked
) ||
387 ( elements
[i
].type
== 'hidden' && elements
[i
].value
== '1' )
390 if( namespaces
!= '' ) {
393 namespaces
+= name
.substring( 2 );
396 if( namespaces
== '' ) {
397 namespaces
= wgSearchNamespaces
.join('|');
402 /** Update results if user hasn't already typed something else */
403 window
.os_updateIfRelevant = function( r
, query
, text
, cacheKey
) {
404 var t
= document
.getElementById( r
.searchbox
);
405 if( t
!= null && t
.value
== query
) { // check if response is still relevant
406 os_updateResults( r
, query
, text
, cacheKey
);
411 /** Fetch results after some timeout */
412 window
.os_delayedFetch = function() {
413 if( os_timer
== null ) {
417 var query
= os_timer
.query
;
419 var path
= wgMWSuggestTemplate
.replace( "{namespaces}", os_getNamespaces( r
) )
420 .replace( "{dbname}", wgDBname
)
421 .replace( "{searchTerms}", os_encodeQuery( query
) );
423 // try to get from cache, if not fetch using ajax
424 var cached
= os_cache
[path
];
425 if( cached
!= null && cached
!= undefined ) {
426 os_updateIfRelevant( r
, query
, cached
, path
);
428 var xmlhttp
= sajax_init_object();
431 xmlhttp
.open( 'GET', path
, true );
432 xmlhttp
.onreadystatechange = function() {
433 if ( xmlhttp
.readyState
== 4 && typeof os_updateIfRelevant
== 'function' ) {
434 os_updateIfRelevant( r
, query
, xmlhttp
.responseText
, path
);
437 xmlhttp
.send( null );
439 if ( window
.location
.hostname
== 'localhost' ) {
440 alert( "Your browser blocks XMLHttpRequest to 'localhost', try using a real hostname for development/testing." );
448 /** Init timed update via os_delayedUpdate() */
449 window
.os_fetchResults = function( r
, query
, timeout
) {
454 } else if( query
== r
.query
) {
458 os_is_stopped
= false; // make sure we're running
460 // cancel any pending fetches
461 if( os_timer
!= null && os_timer
.id
!= null ) {
462 clearTimeout( os_timer
.id
);
464 // schedule delayed fetching of results
466 os_timer
= new os_Timer( setTimeout( "os_delayedFetch()", timeout
), r
, query
);
468 os_timer
= new os_Timer( null, r
, query
);
469 os_delayedFetch(); // do it now!
473 /** Find event target */
474 window
.os_getTarget = function( e
) {
480 } else if ( e
.srcElement
) {
487 /** Check if x is a valid integer */
488 window
.os_isNumber = function( x
) {
489 if( x
== '' || isNaN( x
) ) {
492 for( var i
= 0; i
< x
.length
; i
++ ) {
493 var c
= x
.charAt( i
);
494 if( !( c
>= '0' && c
<= '9' ) ) {
501 /** Call this to enable suggestions on input (id=inputId), on a form (name=formName) */
502 window
.os_enableSuggestionsOn = function( inputId
, formName
) {
503 os_initHandlers( inputId
, formName
, document
.getElementById( inputId
) );
506 /** Call this to disable suggestios on input box (id=inputId) */
507 window
.os_disableSuggestionsOn = function( inputId
) {
510 // cancel/hide results
513 // turn autocomplete on !
514 document
.getElementById( inputId
).setAttribute( 'autocomplete', 'on' );
516 os_map
[inputId
] = null;
519 // Remove the element from the os_autoload_* arrays
520 var index
= os_autoload_inputs
.indexOf( inputId
);
522 os_autoload_inputs
[index
] = os_autoload_forms
[index
] = '';
526 /************************************************
527 * Div-only functions (irrelevant for datalist)
528 ************************************************/
530 /** Event: loss of focus of input box */
531 window
.os_eventBlur = function( e
) {
532 var targ
= os_getTarget( e
);
533 var r
= os_map
[targ
.id
];
535 return; // not our event
537 if( !os_mouse_pressed
) {
539 // force canvas to stay hidden
541 // cancel any pending fetches
542 if( os_timer
!= null && os_timer
.id
!= null ) {
543 clearTimeout( os_timer
.id
);
549 /** Event: focus (catch only when stopped) */
550 window
.os_eventFocus = function( e
) {
551 var targ
= os_getTarget( e
);
552 var r
= os_map
[targ
.id
];
554 return; // not our event
556 r
.stayHidden
= false;
560 * Create and populate a <div>, for non-<datalist>-supporting browsers.
562 * @param r os_Result object
563 * @param results Array of the new results to replace existing ones
565 window
.os_setupDiv = function( r
, results
) {
566 var c
= document
.getElementById( r
.container
);
568 c
= os_createContainer( r
);
570 c
.innerHTML
= os_createResultTable( r
, results
);
571 // init container table sizes
572 var t
= document
.getElementById( r
.resultTable
);
573 r
.containerTotal
= t
.offsetHeight
;
574 r
.containerRow
= t
.offsetHeight
/ r
.resultCount
;
575 os_fitContainer( r
);
576 os_trimResultText( r
);
580 /** Create the result table to be placed in the container div */
581 window
.os_createResultTable = function( r
, results
) {
582 var c
= document
.getElementById( r
.container
);
583 var width
= c
.offsetWidth
- os_operaWidthFix( c
.offsetWidth
);
584 var html
= '<table class="os-suggest-results" id="' + r
.resultTable
+ '" style="width: ' + width
+ 'px;">';
585 r
.results
= new Array();
586 r
.resultCount
= results
.length
;
587 for( i
= 0; i
< results
.length
; i
++ ) {
588 var title
= os_decodeValue( results
[i
] );
589 r
.results
[i
] = title
;
590 html
+= '<tr><td class="os-suggest-result" id="' + r
.resultTable
+ i
+ '"><span id="' + r
.resultText
+ i
+ '">' + title
+ '</span></td></tr>';
596 /** Show results div */
597 window
.os_showResults = function( r
) {
598 if( os_is_stopped
) {
604 os_fitContainer( r
);
605 var c
= document
.getElementById( r
.container
);
609 c
.style
.visibility
= 'visible';
614 window
.os_operaWidthFix = function( x
) {
615 // For browsers that don't understand overflow-x, estimate scrollbar width
616 if( typeof document
.body
.style
.overflowX
!= 'string' ) {
622 /** Brower-dependent functions to find window inner size, and scroll status */
623 window
.f_clientWidth = function() {
624 return f_filterResults(
625 window
.innerWidth
? window
.innerWidth
: 0,
626 document
.documentElement
? document
.documentElement
.clientWidth
: 0,
627 document
.body
? document
.body
.clientWidth
: 0
631 window
.f_clientHeight = function() {
632 return f_filterResults(
633 window
.innerHeight
? window
.innerHeight
: 0,
634 document
.documentElement
? document
.documentElement
.clientHeight
: 0,
635 document
.body
? document
.body
.clientHeight
: 0
639 window
.f_scrollLeft = function() {
640 return f_filterResults(
641 window
.pageXOffset
? window
.pageXOffset
: 0,
642 document
.documentElement
? document
.documentElement
.scrollLeft
: 0,
643 document
.body
? document
.body
.scrollLeft
: 0
647 window
.f_scrollTop = function() {
648 return f_filterResults(
649 window
.pageYOffset
? window
.pageYOffset
: 0,
650 document
.documentElement
? document
.documentElement
.scrollTop
: 0,
651 document
.body
? document
.body
.scrollTop
: 0
655 window
.f_filterResults = function( n_win
, n_docel
, n_body
) {
656 var n_result
= n_win
? n_win
: 0;
657 if ( n_docel
&& ( !n_result
|| ( n_result
> n_docel
) ) ) {
660 return n_body
&& ( !n_result
|| ( n_result
> n_body
) ) ? n_body
: n_result
;
663 /** Get the height available for the results container */
664 window
.os_availableHeight = function( r
) {
665 var absTop
= document
.getElementById( r
.container
).style
.top
;
666 var px
= absTop
.lastIndexOf( 'px' );
668 absTop
= absTop
.substring( 0, px
);
670 return f_clientHeight() - ( absTop
- f_scrollTop() );
673 /** Get element absolute position {left,top} */
674 window
.os_getElementPosition = function( elemID
) {
675 var offsetTrail
= document
.getElementById( elemID
);
678 while ( offsetTrail
) {
679 offsetLeft
+= offsetTrail
.offsetLeft
;
680 offsetTop
+= offsetTrail
.offsetTop
;
681 offsetTrail
= offsetTrail
.offsetParent
;
683 if ( navigator
.userAgent
.indexOf('Mac') != -1 && typeof document
.body
.leftMargin
!= 'undefined' ) {
684 offsetLeft
+= document
.body
.leftMargin
;
685 offsetTop
+= document
.body
.topMargin
;
687 return { left
:offsetLeft
, top
:offsetTop
};
690 /** Create the container div that will hold the suggested titles */
691 window
.os_createContainer = function( r
) {
692 var c
= document
.createElement( 'div' );
693 var s
= document
.getElementById( r
.searchbox
);
694 var pos
= os_getElementPosition( r
.searchbox
);
696 var top
= pos
.top
+ s
.offsetHeight
;
697 c
.className
= 'os-suggest';
698 c
.setAttribute( 'id', r
.container
);
699 document
.body
.appendChild( c
);
701 // dynamically generated style params
702 // IE workaround, cannot explicitely set "style" attribute
703 c
= document
.getElementById( r
.container
);
704 c
.style
.top
= top
+ 'px';
705 c
.style
.left
= left
+ 'px';
706 c
.style
.width
= s
.offsetWidth
+ 'px';
708 // mouse event handlers
709 c
.onmouseover = function( event
) { os_eventMouseover( r
.searchbox
, event
); };
710 c
.onmousemove = function( event
) { os_eventMousemove( r
.searchbox
, event
); };
711 c
.onmousedown = function( event
) { return os_eventMousedown( r
.searchbox
, event
); };
712 c
.onmouseup = function( event
) { os_eventMouseup( r
.searchbox
, event
); };
716 /** change container height to fit to screen */
717 window
.os_fitContainer = function( r
) {
718 var c
= document
.getElementById( r
.container
);
719 var h
= os_availableHeight( r
) - 20;
720 var inc
= r
.containerRow
;
721 h
= parseInt( h
/ inc
) * inc
;
722 if( h
< ( 2 * inc
) && r
.resultCount
> 1 ) { // min: two results
725 if( ( h
/ inc
) > os_max_lines_per_suggest
) {
726 h
= inc
* os_max_lines_per_suggest
;
728 if( h
< r
.containerTotal
) {
729 c
.style
.height
= h
+ 'px';
730 r
.containerCount
= parseInt( Math
.round( h
/ inc
) );
732 c
.style
.height
= r
.containerTotal
+ 'px';
733 r
.containerCount
= r
.resultCount
;
737 /** If some entries are longer than the box, replace text with "..." */
738 window
.os_trimResultText = function( r
) {
739 // find max width, first see if we could expand the container to fit it
741 for( var i
= 0; i
< r
.resultCount
; i
++ ) {
742 var e
= document
.getElementById( r
.resultText
+ i
);
743 if( e
.offsetWidth
> maxW
) {
744 maxW
= e
.offsetWidth
;
747 var w
= document
.getElementById( r
.container
).offsetWidth
;
749 if( r
.containerCount
< r
.resultCount
) {
750 fix
= 20; // give 20px for scrollbar
752 fix
= os_operaWidthFix( w
);
755 fix
= 4; // basic padding
759 // resize container to fit more data if permitted
760 var normW
= document
.getElementById( r
.searchbox
).offsetWidth
;
761 var prop
= maxW
/ normW
;
762 if( prop
> os_container_max_width
) {
763 prop
= os_container_max_width
;
764 } else if( prop
< 1 ) {
767 var newW
= Math
.round( normW
* prop
);
770 if( os_animation_timer
!= null ) {
771 clearInterval( os_animation_timer
.id
);
773 os_animation_timer
= new os_AnimationTimer( r
, w
);
774 os_animation_timer
.id
= setInterval( "os_animateChangeWidth()", os_animation_delay
);
775 w
-= fix
; // this much is reserved
782 for( var i
= 0; i
< r
.resultCount
; i
++ ) {
783 var e
= document
.getElementById( r
.resultText
+ i
);
785 var lastW
= e
.offsetWidth
+ 1;
787 var changedText
= false;
788 while( e
.offsetWidth
> w
&& ( e
.offsetWidth
< lastW
|| iteration
< 2 ) ) {
790 lastW
= e
.offsetWidth
;
792 e
.innerHTML
= l
.substring( 0, l
.length
- replace
) + '...';
794 replace
= 4; // how many chars to replace
797 // show hint for trimmed titles
798 document
.getElementById( r
.resultTable
+ i
).setAttribute( 'title', r
.results
[i
] );
803 /** Invoked on timer to animate change in container width */
804 window
.os_animateChangeWidth = function() {
805 var r
= os_animation_timer
.r
;
806 var c
= document
.getElementById( r
.container
);
807 var w
= c
.offsetWidth
;
808 var normW
= document
.getElementById( r
.searchbox
).offsetWidth
;
809 var normL
= os_getElementPosition( r
.searchbox
).left
;
810 var inc
= os_animation_timer
.inc
;
811 var target
= os_animation_timer
.target
;
813 if( ( inc
> 0 && nw
>= target
) || ( inc
<= 0 && nw
<= target
) ) {
815 c
.style
.width
= target
+ 'px';
816 clearInterval( os_animation_timer
.id
);
817 os_animation_timer
= null;
820 c
.style
.width
= nw
+ 'px';
821 if( document
.documentElement
.dir
== 'rtl' ) {
822 c
.style
.left
= ( normL
+ normW
+ ( target
- nw
) - os_animation_timer
.target
- 1 ) + 'px';
827 /** Change the highlighted row (i.e. suggestion), from position cur to next */
828 window
.os_changeHighlight = function( r
, cur
, next
, updateSearchBox
) {
829 if ( next
>= r
.resultCount
) {
830 next
= r
.resultCount
- 1;
837 return; // nothing to do.
841 var curRow
= document
.getElementById( r
.resultTable
+ cur
);
842 if( curRow
!= null ) {
843 curRow
.className
= 'os-suggest-result';
848 var nextRow
= document
.getElementById( r
.resultTable
+ next
);
849 if( nextRow
!= null ) {
850 nextRow
.className
= os_HighlightClass();
852 newText
= r
.results
[next
];
854 newText
= r
.original
;
857 // adjust the scrollbar if any
858 if( r
.containerCount
< r
.resultCount
) {
859 var c
= document
.getElementById( r
.container
);
860 var vStart
= c
.scrollTop
/ r
.containerRow
;
861 var vEnd
= vStart
+ r
.containerCount
;
862 if( next
< vStart
) {
863 c
.scrollTop
= next
* r
.containerRow
;
864 } else if( next
>= vEnd
) {
865 c
.scrollTop
= ( next
- r
.containerCount
+ 1 ) * r
.containerRow
;
869 // update the contents of the search box
870 if( updateSearchBox
) {
871 os_updateSearchQuery( r
, newText
);
875 window
.os_HighlightClass = function() {
876 var match
= navigator
.userAgent
.match(/AppleWebKit\/(\d+)/);
878 var webKitVersion
= parseInt( match
[1] );
879 if ( webKitVersion
< 523 ) {
880 // CSS system highlight colors broken on old Safari
881 // https://bugs.webkit.org/show_bug.cgi?id=6129
882 // Safari 3.0.4, 3.1 known ok
883 return 'os-suggest-result-hl-webkit';
886 return 'os-suggest-result-hl';
889 window
.os_updateSearchQuery = function( r
, newText
) {
890 document
.getElementById( r
.searchbox
).value
= newText
;
895 /********************
897 ********************/
899 /** Mouse over the container */
900 window
.os_eventMouseover = function( srcId
, e
) {
901 var targ
= os_getTarget( e
);
902 var r
= os_map
[srcId
];
903 if( r
== null || !os_mouse_moved
) {
904 return; // not our event
906 var num
= os_getNumberSuffix( targ
.id
);
908 os_changeHighlight( r
, r
.selected
, num
, false );
912 /* Get row where the event occured (from its id) */
913 window
.os_getNumberSuffix = function( id
) {
914 var num
= id
.substring( id
.length
- 2 );
915 if( !( num
.charAt( 0 ) >= '0' && num
.charAt( 0 ) <= '9' ) ) {
916 num
= num
.substring( 1 );
918 if( os_isNumber( num
) ) {
919 return parseInt( num
);
925 /** Save mouse move as last action */
926 window
.os_eventMousemove = function( srcId
, e
) {
927 os_mouse_moved
= true;
930 /** Mouse button held down, register possible click */
931 window
.os_eventMousedown = function( srcId
, e
) {
932 var targ
= os_getTarget( e
);
933 var r
= os_map
[srcId
];
935 return; // not our event
937 var num
= os_getNumberSuffix( targ
.id
);
939 os_mouse_pressed
= true;
942 // os_updateSearchQuery( r, r.results[num] );
944 // keep the focus on the search field
945 document
.getElementById( r
.searchbox
).focus();
947 return false; // prevents selection
950 /** Mouse button released, check for click on some row */
951 window
.os_eventMouseup = function( srcId
, e
) {
952 var targ
= os_getTarget( e
);
953 var r
= os_map
[srcId
];
955 return; // not our event
957 var num
= os_getNumberSuffix( targ
.id
);
959 if( num
>= 0 && os_mouse_num
== num
) {
960 os_updateSearchQuery( r
, r
.results
[num
] );
962 document
.getElementById( r
.searchform
).submit();
964 os_mouse_pressed
= false;
965 // keep the focus on the search field
966 document
.getElementById( r
.searchbox
).focus();
969 /** Toggle stuff seems to be dead code? */
971 /** Return the span element that contains the toggle link */
972 window
.os_createToggle = function( r
, className
) {
973 var t
= document
.createElement( 'span' );
974 t
.className
= className
;
975 t
.setAttribute( 'id', r
.toggle
);
976 var link
= document
.createElement( 'a' );
977 link
.setAttribute( 'href', 'javascript:void(0);' );
978 link
.onclick = function() { os_toggle( r
.searchbox
, r
.searchform
); };
979 var msg
= document
.createTextNode( wgMWSuggestMessages
[0] );
980 link
.appendChild( msg
);
981 t
.appendChild( link
);
985 /** Call when user clicks on some of the toggle links */
986 window
.os_toggle = function( inputId
, formName
) {
990 os_enableSuggestionsOn( inputId
, formName
);
992 msg
= wgMWSuggestMessages
[0];
994 os_disableSuggestionsOn( inputId
, formName
);
995 msg
= wgMWSuggestMessages
[1];
998 var link
= document
.getElementById( r
.toggle
).firstChild
;
999 link
.replaceChild( document
.createTextNode( msg
), link
.firstChild
);
1002 hookEvent( 'load', os_MWSuggestInit
);