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. 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 window
.os_use_datalist
= false;
55 /** Timeout timer class that will fetch the results */
56 window
.os_Timer = function( id
, r
, query
) {
62 /** Property class for single search box */
63 window
.os_Results = function( 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 window.os_AnimationTimer = function( 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 window
.os_MWSuggestInit = function() {
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 window
.os_initHandlers = function( name
, formname
, element
) {
114 var r
= new os_Results( name
, formname
);
115 var formElement
= document
.getElementById( formname
);
117 // Older browsers (Opera 8) cannot get form elements
121 os_hookEvent( element
, 'keyup', function( event
) { os_eventKeyup( event
); } );
122 os_hookEvent( element
, 'keydown', function( event
) { os_eventKeydown( event
); } );
123 os_hookEvent( element
, 'keypress', function( event
) { os_eventKeypress( event
); } );
124 if ( !os_use_datalist
) {
125 // These are needed for the div hack to hide it if the user blurs.
126 os_hookEvent( element
, 'blur', function( event
) { os_eventBlur( event
); } );
127 os_hookEvent( element
, 'focus', function( event
) { os_eventFocus( event
); } );
128 // We don't want browser auto-suggestions interfering with our div, but
129 // autocomplete must be on for datalist to work (at least in Opera
131 element
.setAttribute( 'autocomplete', 'off' );
134 os_hookEvent( formElement
, 'submit', function( event
) { return os_eventOnsubmit( event
); } );
137 if( document
.getElementById( r
.toggle
) == null ) {
138 // TODO: disable this while we figure out a way for this to work in all browsers
139 /* if( name == 'searchInput' ) {
140 // special case: place above the main search box
141 var t = os_createToggle( r, 'os-suggest-toggle' );
142 var searchBody = document.getElementById( 'searchBody' );
143 var first = searchBody.parentNode.firstChild.nextSibling.appendChild(t);
145 // default: place below search box to the right
146 var t = os_createToggle( r, 'os-suggest-toggle-def' );
147 var top = element.offsetTop + element.offsetHeight;
148 var left = element.offsetLeft + element.offsetWidth;
149 t.style.position = 'absolute';
150 t.style.top = top + 'px';
151 t.style.left = left + 'px';
152 element.parentNode.appendChild( t );
153 // only now width gets calculated, shift right
154 left -= t.offsetWidth;
155 t.style.left = left + 'px';
156 t.style.visibility = 'visible';
162 window
.os_hookEvent = function( element
, hookName
, hookFunct
) {
163 if ( element
.addEventListener
) {
164 element
.addEventListener( hookName
, hookFunct
, false );
165 } else if ( window
.attachEvent
) {
166 element
.attachEvent( 'on' + hookName
, hookFunct
);
170 /********************
172 ********************/
174 /** Event handler that will fetch results on keyup */
175 window
.os_eventKeyup = function( e
) {
176 var targ
= os_getTarget( e
);
177 var r
= os_map
[targ
.id
];
179 return; // not our event
182 // some browsers won't generate keypressed for arrow keys, catch it
183 if( os_keypressed_count
== 0 ) {
184 os_processKey( r
, os_cur_keypressed
, targ
);
186 var query
= targ
.value
;
187 os_fetchResults( r
, query
, os_search_timeout
);
190 /** catch arrows up/down and escape to hide the suggestions */
191 window.os_processKey = function( r, keypressed, targ ) {
192 if ( keypressed == 40 && !r.visible && os_timer == null ) {
193 // If the user hits the down arrow, fetch results immediately if none
194 // are already displayed.
196 os_fetchResults( r, targ.value, 0 );
198 // Otherwise, if we're not using datalist, we need to handle scrolling and
200 if ( os_use_datalist ) {
203 if ( keypressed == 40 ) { // Arrow Down
205 os_changeHighlight( r, r.selected, r.selected + 1, true );
207 } else if ( keypressed == 38 ) { // Arrow Up
209 os_changeHighlight( r, r.selected, r.selected - 1, true );
211 } else if( keypressed == 27 ) { // Escape
212 document.getElementById( r.searchbox ).value = r.original;
213 r.query = r.original;
215 } else if( r.query != document.getElementById( r.searchbox ).value ) {
216 // os_hideResults( r ); // don't show old suggestions
220 /** When keys is held down use a timer to output regular events */
221 window
.os_eventKeypress = function( e
) {
222 var targ
= os_getTarget( e
);
223 var r
= os_map
[targ
.id
];
225 return; // not our event
228 var keypressed
= os_cur_keypressed
;
230 os_keypressed_count
++;
231 os_processKey( r
, keypressed
, targ
);
234 /** Catch the key code (Firefox bug) */
235 window
.os_eventKeydown = function( e
) {
239 var targ
= os_getTarget( e
);
240 var r
= os_map
[targ
.id
];
242 return; // not our event
245 os_mouse_moved
= false;
247 os_cur_keypressed
= ( e
.keyCode
== undefined ) ? e
.which
: e
.keyCode
;
248 os_keypressed_count
= 0;
252 /** When the form is submitted hide everything, cancel updates... */
253 window
.os_eventOnsubmit = function( e
) {
254 var targ
= os_getTarget( e
);
256 os_is_stopped
= true;
257 // kill timed requests
258 if( os_timer
!= null && os_timer
.id
!= null ) {
259 clearTimeout( os_timer
.id
);
262 // Hide all suggestions
263 for( i
= 0; i
< os_autoload_inputs
.length
; i
++ ) {
264 var r
= os_map
[os_autoload_inputs
[i
]];
266 var b
= document
.getElementById( r
.searchform
);
267 if( b
!= null && b
== targ
) {
268 // set query value so the handler won't try to fetch additional results
269 r
.query
= document
.getElementById( r
.searchbox
).value
;
279 /** Hide results from the user, either making the div visibility=hidden or
280 * detaching the datalist from the input. */
281 window
.os_hideResults = function( r
) {
282 if ( os_use_datalist
) {
283 document
.getElementById( r
.searchbox
).setAttribute( 'list', '' );
285 var c
= document
.getElementById( r
.container
);
287 c
.style
.visibility
= 'hidden';
294 window
.os_decodeValue = function( value
) {
295 if ( decodeURIComponent
) {
296 return decodeURIComponent( value
);
299 return unescape( value
);
304 window
.os_encodeQuery = function( value
) {
305 if ( encodeURIComponent
) {
306 return encodeURIComponent( value
);
309 return escape( value
);
314 /** Handles data from XMLHttpRequest, and updates the suggest results */
315 window
.os_updateResults = function( r
, query
, text
, cacheKey
) {
316 os_cache
[cacheKey
] = text
;
325 var p
= eval( '(' + text
+ ')' ); // simple json parse, could do a safer one
326 if( p
.length
< 2 || p
[1].length
== 0 ) {
332 if ( os_use_datalist
) {
333 os_setupDatalist( r
, p
[1] );
335 os_setupDiv( r
, p
[1] );
338 // bad response from server or such
340 os_cache
[cacheKey
] = null;
346 * Create and populate a <datalist>.
348 * @param r os_Result object
349 * @param results Array of the new results to replace existing ones
351 window
.os_setupDatalist = function( r
, results
) {
352 var s
= document
.getElementById( r
.searchbox
);
353 var c
= document
.getElementById( r
.container
);
355 c
= document
.createElement( 'datalist' );
356 c
.setAttribute( 'id', r
.container
);
357 document
.body
.appendChild( c
);
361 s
.setAttribute( 'list', r
.container
);
363 r
.results
= new Array();
364 r
.resultCount
= results
.length
;
366 for ( i
= 0; i
< results
.length
; i
++ ) {
367 var title
= os_decodeValue( results
[i
] );
368 var opt
= document
.createElement( 'option' );
370 r
.results
[i
] = title
;
371 c
.appendChild( opt
);
375 /** Fetch namespaces from checkboxes or hidden fields in the search form,
376 if none defined use wgSearchNamespaces global */
377 window
.os_getNamespaces = function( r
) {
379 var elements
= document
.forms
[r
.searchform
].elements
;
380 for( i
= 0; i
< elements
.length
; i
++ ) {
381 var name
= elements
[i
].name
;
382 if( typeof name
!= 'undefined' && name
.length
> 2 && name
[0] == 'n' &&
384 ( elements
[i
].type
== 'checkbox' && elements
[i
].checked
) ||
385 ( elements
[i
].type
== 'hidden' && elements
[i
].value
== '1' )
388 if( namespaces
!= '' ) {
391 namespaces
+= name
.substring( 2 );
394 if( namespaces
== '' ) {
395 namespaces
= wgSearchNamespaces
.join('|');
400 /** Update results if user hasn't already typed something else */
401 window
.os_updateIfRelevant = function( r
, query
, text
, cacheKey
) {
402 var t
= document
.getElementById( r
.searchbox
);
403 if( t
!= null && t
.value
== query
) { // check if response is still relevant
404 os_updateResults( r
, query
, text
, cacheKey
);
409 /** Fetch results after some timeout */
410 window
.os_delayedFetch = function() {
411 if( os_timer
== null ) {
415 var query
= os_timer
.query
;
417 var path
= wgMWSuggestTemplate
.replace( "{namespaces}", os_getNamespaces( r
) )
418 .replace( "{dbname}", wgDBname
)
419 .replace( "{searchTerms}", os_encodeQuery( query
) );
421 // try to get from cache, if not fetch using ajax
422 var cached
= os_cache
[path
];
423 if( cached
!= null && cached
!= undefined ) {
424 os_updateIfRelevant( r
, query
, cached
, path
);
426 var xmlhttp
= sajax_init_object();
429 xmlhttp
.open( 'GET', path
, true );
430 xmlhttp
.onreadystatechange = function() {
431 if ( xmlhttp
.readyState
== 4 && typeof os_updateIfRelevant
== 'function' ) {
432 os_updateIfRelevant( r
, query
, xmlhttp
.responseText
, path
);
435 xmlhttp
.send( null );
437 if ( window
.location
.hostname
== 'localhost' ) {
438 alert( "Your browser blocks XMLHttpRequest to 'localhost', try using a real hostname for development/testing." );
446 /** Init timed update via os_delayedUpdate() */
447 window
.os_fetchResults = function( r
, query
, timeout
) {
452 } else if( query
== r
.query
) {
456 os_is_stopped
= false; // make sure we're running
458 // cancel any pending fetches
459 if( os_timer
!= null && os_timer
.id
!= null ) {
460 clearTimeout( os_timer
.id
);
462 // schedule delayed fetching of results
464 os_timer
= new os_Timer( setTimeout( "os_delayedFetch()", timeout
), r
, query
);
466 os_timer
= new os_Timer( null, r
, query
);
467 os_delayedFetch(); // do it now!
471 /** Find event target */
472 window
.os_getTarget = function( e
) {
478 } else if ( e
.srcElement
) {
485 /** Check if x is a valid integer */
486 window
.os_isNumber = function( x
) {
487 if( x
== '' || isNaN( x
) ) {
490 for( var i
= 0; i
< x
.length
; i
++ ) {
491 var c
= x
.charAt( i
);
492 if( !( c
>= '0' && c
<= '9' ) ) {
499 /** Call this to enable suggestions on input (id=inputId), on a form (name=formName) */
500 window
.os_enableSuggestionsOn = function( inputId
, formName
) {
501 os_initHandlers( inputId
, formName
, document
.getElementById( inputId
) );
504 /** Call this to disable suggestios on input box (id=inputId) */
505 window
.os_disableSuggestionsOn = function( inputId
) {
508 // cancel/hide results
511 // turn autocomplete on !
512 document
.getElementById( inputId
).setAttribute( 'autocomplete', 'on' );
514 os_map
[inputId
] = null;
517 // Remove the element from the os_autoload_* arrays
518 var index
= os_autoload_inputs
.indexOf( inputId
);
520 os_autoload_inputs
[index
] = os_autoload_forms
[index
] = '';
524 /************************************************
525 * Div-only functions (irrelevant for datalist)
526 ************************************************/
528 /** Event: loss of focus of input box */
529 window
.os_eventBlur = function( e
) {
530 var targ
= os_getTarget( e
);
531 var r
= os_map
[targ
.id
];
533 return; // not our event
535 if( !os_mouse_pressed
) {
537 // force canvas to stay hidden
539 // cancel any pending fetches
540 if( os_timer
!= null && os_timer
.id
!= null ) {
541 clearTimeout( os_timer
.id
);
547 /** Event: focus (catch only when stopped) */
548 window
.os_eventFocus = function( e
) {
549 var targ
= os_getTarget( e
);
550 var r
= os_map
[targ
.id
];
552 return; // not our event
554 r
.stayHidden
= false;
558 * Create and populate a <div>, for non-<datalist>-supporting browsers.
560 * @param r os_Result object
561 * @param results Array of the new results to replace existing ones
563 window
.os_setupDiv = function( r
, results
) {
564 var c
= document
.getElementById( r
.container
);
566 c
= os_createContainer( r
);
568 c
.innerHTML
= os_createResultTable( r
, results
);
569 // init container table sizes
570 var t
= document
.getElementById( r
.resultTable
);
571 r
.containerTotal
= t
.offsetHeight
;
572 r
.containerRow
= t
.offsetHeight
/ r
.resultCount
;
573 os_fitContainer( r
);
574 os_trimResultText( r
);
578 /** Create the result table to be placed in the container div */
579 window
.os_createResultTable = function( r
, results
) {
580 var c
= document
.getElementById( r
.container
);
581 var width
= c
.offsetWidth
- os_operaWidthFix( c
.offsetWidth
);
582 var html
= '<table class="os-suggest-results" id="' + r
.resultTable
+ '" style="width: ' + width
+ 'px;">';
583 r
.results
= new Array();
584 r
.resultCount
= results
.length
;
585 for( i
= 0; i
< results
.length
; i
++ ) {
586 var title
= os_decodeValue( results
[i
] );
587 r
.results
[i
] = title
;
588 html
+= '<tr><td class="os-suggest-result" id="' + r
.resultTable
+ i
+ '"><span id="' + r
.resultText
+ i
+ '">' + title
+ '</span></td></tr>';
594 /** Show results div */
595 window
.os_showResults = function( r
) {
596 if( os_is_stopped
) {
602 os_fitContainer( r
);
603 var c
= document
.getElementById( r
.container
);
607 c
.style
.visibility
= 'visible';
612 window
.os_operaWidthFix = function( x
) {
613 // For browsers that don't understand overflow-x, estimate scrollbar width
614 if( typeof document
.body
.style
.overflowX
!= 'string' ) {
620 /** Brower-dependent functions to find window inner size, and scroll status */
621 window
.f_clientWidth = function() {
622 return f_filterResults(
623 window
.innerWidth
? window
.innerWidth
: 0,
624 document
.documentElement
? document
.documentElement
.clientWidth
: 0,
625 document
.body
? document
.body
.clientWidth
: 0
629 window
.f_clientHeight = function() {
630 return f_filterResults(
631 window
.innerHeight
? window
.innerHeight
: 0,
632 document
.documentElement
? document
.documentElement
.clientHeight
: 0,
633 document
.body
? document
.body
.clientHeight
: 0
637 window
.f_scrollLeft = function() {
638 return f_filterResults(
639 window
.pageXOffset
? window
.pageXOffset
: 0,
640 document
.documentElement
? document
.documentElement
.scrollLeft
: 0,
641 document
.body
? document
.body
.scrollLeft
: 0
645 window
.f_scrollTop = function() {
646 return f_filterResults(
647 window
.pageYOffset
? window
.pageYOffset
: 0,
648 document
.documentElement
? document
.documentElement
.scrollTop
: 0,
649 document
.body
? document
.body
.scrollTop
: 0
653 window
.f_filterResults = function( n_win
, n_docel
, n_body
) {
654 var n_result
= n_win
? n_win
: 0;
655 if ( n_docel
&& ( !n_result
|| ( n_result
> n_docel
) ) ) {
658 return n_body
&& ( !n_result
|| ( n_result
> n_body
) ) ? n_body
: n_result
;
661 /** Get the height available for the results container */
662 window
.os_availableHeight = function( r
) {
663 var absTop
= document
.getElementById( r
.container
).style
.top
;
664 var px
= absTop
.lastIndexOf( 'px' );
666 absTop
= absTop
.substring( 0, px
);
668 return f_clientHeight() - ( absTop
- f_scrollTop() );
671 /** Get element absolute position {left,top} */
672 window
.os_getElementPosition = function( elemID
) {
673 var offsetTrail
= document
.getElementById( elemID
);
676 while ( offsetTrail
) {
677 offsetLeft
+= offsetTrail
.offsetLeft
;
678 offsetTop
+= offsetTrail
.offsetTop
;
679 offsetTrail
= offsetTrail
.offsetParent
;
681 if ( navigator
.userAgent
.indexOf('Mac') != -1 && typeof document
.body
.leftMargin
!= 'undefined' ) {
682 offsetLeft
+= document
.body
.leftMargin
;
683 offsetTop
+= document
.body
.topMargin
;
685 return { left
:offsetLeft
, top
:offsetTop
};
688 /** Create the container div that will hold the suggested titles */
689 window
.os_createContainer = function( r
) {
690 var c
= document
.createElement( 'div' );
691 var s
= document
.getElementById( r
.searchbox
);
692 var pos
= os_getElementPosition( r
.searchbox
);
694 var top
= pos
.top
+ s
.offsetHeight
;
695 c
.className
= 'os-suggest';
696 c
.setAttribute( 'id', r
.container
);
697 document
.body
.appendChild( c
);
699 // dynamically generated style params
700 // IE workaround, cannot explicitely set "style" attribute
701 c
= document
.getElementById( r
.container
);
702 c
.style
.top
= top
+ 'px';
703 c
.style
.left
= left
+ 'px';
704 c
.style
.width
= s
.offsetWidth
+ 'px';
706 // mouse event handlers
707 c
.onmouseover = function( event
) { os_eventMouseover( r
.searchbox
, event
); };
708 c
.onmousemove = function( event
) { os_eventMousemove( r
.searchbox
, event
); };
709 c
.onmousedown = function( event
) { return os_eventMousedown( r
.searchbox
, event
); };
710 c
.onmouseup = function( event
) { os_eventMouseup( r
.searchbox
, event
); };
714 /** change container height to fit to screen */
715 window
.os_fitContainer = function( r
) {
716 var c
= document
.getElementById( r
.container
);
717 var h
= os_availableHeight( r
) - 20;
718 var inc
= r
.containerRow
;
719 h
= parseInt( h
/ inc
) * inc
;
720 if( h
< ( 2 * inc
) && r
.resultCount
> 1 ) { // min: two results
723 if( ( h
/ inc
) > os_max_lines_per_suggest
) {
724 h
= inc
* os_max_lines_per_suggest
;
726 if( h
< r
.containerTotal
) {
727 c
.style
.height
= h
+ 'px';
728 r
.containerCount
= parseInt( Math
.round( h
/ inc
) );
730 c
.style
.height
= r
.containerTotal
+ 'px';
731 r
.containerCount
= r
.resultCount
;
735 /** If some entries are longer than the box, replace text with "..." */
736 window
.os_trimResultText = function( r
) {
737 // find max width, first see if we could expand the container to fit it
739 for( var i
= 0; i
< r
.resultCount
; i
++ ) {
740 var e
= document
.getElementById( r
.resultText
+ i
);
741 if( e
.offsetWidth
> maxW
) {
742 maxW
= e
.offsetWidth
;
745 var w
= document
.getElementById( r
.container
).offsetWidth
;
747 if( r
.containerCount
< r
.resultCount
) {
748 fix
= 20; // give 20px for scrollbar
750 fix
= os_operaWidthFix( w
);
753 fix
= 4; // basic padding
757 // resize container to fit more data if permitted
758 var normW
= document
.getElementById( r
.searchbox
).offsetWidth
;
759 var prop
= maxW
/ normW
;
760 if( prop
> os_container_max_width
) {
761 prop
= os_container_max_width
;
762 } else if( prop
< 1 ) {
765 var newW
= Math
.round( normW
* prop
);
768 if( os_animation_timer
!= null ) {
769 clearInterval( os_animation_timer
.id
);
771 os_animation_timer
= new os_AnimationTimer( r
, w
);
772 os_animation_timer
.id
= setInterval( "os_animateChangeWidth()", os_animation_delay
);
773 w
-= fix
; // this much is reserved
780 for( var i
= 0; i
< r
.resultCount
; i
++ ) {
781 var e
= document
.getElementById( r
.resultText
+ i
);
783 var lastW
= e
.offsetWidth
+ 1;
785 var changedText
= false;
786 while( e
.offsetWidth
> w
&& ( e
.offsetWidth
< lastW
|| iteration
< 2 ) ) {
788 lastW
= e
.offsetWidth
;
790 e
.innerHTML
= l
.substring( 0, l
.length
- replace
) + '...';
792 replace
= 4; // how many chars to replace
795 // show hint for trimmed titles
796 document
.getElementById( r
.resultTable
+ i
).setAttribute( 'title', r
.results
[i
] );
801 /** Invoked on timer to animate change in container width */
802 window
.os_animateChangeWidth = function() {
803 var r
= os_animation_timer
.r
;
804 var c
= document
.getElementById( r
.container
);
805 var w
= c
.offsetWidth
;
806 var normW
= document
.getElementById( r
.searchbox
).offsetWidth
;
807 var normL
= os_getElementPosition( r
.searchbox
).left
;
808 var inc
= os_animation_timer
.inc
;
809 var target
= os_animation_timer
.target
;
811 if( ( inc
> 0 && nw
>= target
) || ( inc
<= 0 && nw
<= target
) ) {
813 c
.style
.width
= target
+ 'px';
814 clearInterval( os_animation_timer
.id
);
815 os_animation_timer
= null;
818 c
.style
.width
= nw
+ 'px';
819 if( document
.documentElement
.dir
== 'rtl' ) {
820 c
.style
.left
= ( normL
+ normW
+ ( target
- nw
) - os_animation_timer
.target
- 1 ) + 'px';
825 /** Change the highlighted row (i.e. suggestion), from position cur to next */
826 window
.os_changeHighlight = function( r
, cur
, next
, updateSearchBox
) {
827 if ( next
>= r
.resultCount
) {
828 next
= r
.resultCount
- 1;
835 return; // nothing to do.
839 var curRow
= document
.getElementById( r
.resultTable
+ cur
);
840 if( curRow
!= null ) {
841 curRow
.className
= 'os-suggest-result';
846 var nextRow
= document
.getElementById( r
.resultTable
+ next
);
847 if( nextRow
!= null ) {
848 nextRow
.className
= os_HighlightClass();
850 newText
= r
.results
[next
];
852 newText
= r
.original
;
855 // adjust the scrollbar if any
856 if( r
.containerCount
< r
.resultCount
) {
857 var c
= document
.getElementById( r
.container
);
858 var vStart
= c
.scrollTop
/ r
.containerRow
;
859 var vEnd
= vStart
+ r
.containerCount
;
860 if( next
< vStart
) {
861 c
.scrollTop
= next
* r
.containerRow
;
862 } else if( next
>= vEnd
) {
863 c
.scrollTop
= ( next
- r
.containerCount
+ 1 ) * r
.containerRow
;
867 // update the contents of the search box
868 if( updateSearchBox
) {
869 os_updateSearchQuery( r
, newText
);
873 window
.os_HighlightClass = function() {
874 var match
= navigator
.userAgent
.match(/AppleWebKit\/(\d+)/);
876 var webKitVersion
= parseInt( match
[1] );
877 if ( webKitVersion
< 523 ) {
878 // CSS system highlight colors broken on old Safari
879 // https://bugs.webkit.org/show_bug.cgi?id=6129
880 // Safari 3.0.4, 3.1 known ok
881 return 'os-suggest-result-hl-webkit';
884 return 'os-suggest-result-hl';
887 window
.os_updateSearchQuery = function( r
, newText
) {
888 document
.getElementById( r
.searchbox
).value
= newText
;
893 /********************
895 ********************/
897 /** Mouse over the container */
898 window
.os_eventMouseover = function( srcId
, e
) {
899 var targ
= os_getTarget( e
);
900 var r
= os_map
[srcId
];
901 if( r
== null || !os_mouse_moved
) {
902 return; // not our event
904 var num
= os_getNumberSuffix( targ
.id
);
906 os_changeHighlight( r
, r
.selected
, num
, false );
910 /* Get row where the event occured (from its id) */
911 window
.os_getNumberSuffix = function( id
) {
912 var num
= id
.substring( id
.length
- 2 );
913 if( !( num
.charAt( 0 ) >= '0' && num
.charAt( 0 ) <= '9' ) ) {
914 num
= num
.substring( 1 );
916 if( os_isNumber( num
) ) {
917 return parseInt( num
);
923 /** Save mouse move as last action */
924 window
.os_eventMousemove = function( srcId
, e
) {
925 os_mouse_moved
= true;
928 /** Mouse button held down, register possible click */
929 window
.os_eventMousedown = function( srcId
, e
) {
930 var targ
= os_getTarget( e
);
931 var r
= os_map
[srcId
];
933 return; // not our event
935 var num
= os_getNumberSuffix( targ
.id
);
937 os_mouse_pressed
= true;
940 // os_updateSearchQuery( r, r.results[num] );
942 // keep the focus on the search field
943 document
.getElementById( r
.searchbox
).focus();
945 return false; // prevents selection
948 /** Mouse button released, check for click on some row */
949 window
.os_eventMouseup = function( srcId
, e
) {
950 var targ
= os_getTarget( e
);
951 var r
= os_map
[srcId
];
953 return; // not our event
955 var num
= os_getNumberSuffix( targ
.id
);
957 if( num
>= 0 && os_mouse_num
== num
) {
958 os_updateSearchQuery( r
, r
.results
[num
] );
960 document
.getElementById( r
.searchform
).submit();
962 os_mouse_pressed
= false;
963 // keep the focus on the search field
964 document
.getElementById( r
.searchbox
).focus();
967 /** Toggle stuff seems to be dead code? */
969 /** Return the span element that contains the toggle link */
970 window
.os_createToggle = function( r
, className
) {
971 var t
= document
.createElement( 'span' );
972 t
.className
= className
;
973 t
.setAttribute( 'id', r
.toggle
);
974 var link
= document
.createElement( 'a' );
975 link
.setAttribute( 'href', 'javascript:void(0);' );
976 link
.onclick = function() { os_toggle( r
.searchbox
, r
.searchform
); };
977 var msg
= document
.createTextNode( wgMWSuggestMessages
[0] );
978 link
.appendChild( msg
);
979 t
.appendChild( link
);
983 /** Call when user clicks on some of the toggle links */
984 window
.os_toggle = function( inputId
, formName
) {
988 os_enableSuggestionsOn( inputId
, formName
);
990 msg
= wgMWSuggestMessages
[0];
992 os_disableSuggestionsOn( inputId
, formName
);
993 msg
= wgMWSuggestMessages
[1];
996 var link
= document
.getElementById( r
.toggle
).firstChild
;
997 link
.replaceChild( document
.createTextNode( msg
), link
.firstChild
);
1000 hookEvent( 'load', os_MWSuggestInit
);