Follow up r78003, forgot to make MonoBook use the footericons code.
[lhc/web/wiklou.git] / skins / common / mwsuggest.js
1 /*
2 * OpenSearch ajax suggestion engine for MediaWiki
3 *
4 * uses core MediaWiki open search support to fetch suggestions
5 * and show them below search boxes and other inputs
6 *
7 * by Robert Stojnic (April 2008)
8 */
9
10 // search_box_id -> Results object
11 window.os_map = {};
12 // cached data, url -> json_text
13 window.os_cache = {};
14 // global variables for suggest_keypress
15 window.os_cur_keypressed = 0;
16 window.os_keypressed_count = 0;
17 // type: Timer
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;
43 /**
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.
51 */
52 // var os_use_datalist = 'list' in document.createElement( 'input' );
53 window.os_use_datalist = false;
54
55 /** Timeout timer class that will fetch the results */
56 window.os_Timer = function( id, r, query ) {
57 this.id = id;
58 this.r = r;
59 this.query = query;
60 };
61
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
80 };
81
82 /** Timer user to animate expansion/contraction of container width */
83 window.os_AnimationTimer = function( r, target ) {
84 this.r = r;
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
89 }
90 if( this.inc > -os_animation_min_step && this.inc < 0 ) {
91 this.inc = -os_animation_min_step;
92 }
93 this.target = target;
94 };
95
96 /******************
97 * Initialization
98 ******************/
99
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 );
108 }
109 }
110 };
111
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 );
116 if( !formElement ) {
117 // Older browsers (Opera 8) cannot get form elements
118 return;
119 }
120 // event handler
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
130 // 10.10).
131 element.setAttribute( 'autocomplete', 'off' );
132 }
133 // stopping handler
134 os_hookEvent( formElement, 'submit', function( event ) { return os_eventOnsubmit( event ); } );
135 os_map[name] = r;
136 // toggle link
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);
144 } else {
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';
157 } */
158 }
159
160 };
161
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 );
167 }
168 };
169
170 /********************
171 * Keyboard events
172 ********************/
173
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];
178 if( r == null ) {
179 return; // not our event
180 }
181
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 );
185 }
186 var query = targ.value;
187 os_fetchResults( r, query, os_search_timeout );
188 };
189
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.
195 r.query = '';
196 os_fetchResults( r, targ.value, 0 );
197 }
198 // Otherwise, if we're not using datalist, we need to handle scrolling and
199 // so on.
200 if ( os_use_datalist ) {
201 return;
202 }
203 if ( keypressed == 40 ) { // Arrow Down
204 if ( r.visible ) {
205 os_changeHighlight( r, r.selected, r.selected + 1, true );
206 }
207 } else if ( keypressed == 38 ) { // Arrow Up
208 if ( r.visible ) {
209 os_changeHighlight( r, r.selected, r.selected - 1, true );
210 }
211 } else if( keypressed == 27 ) { // Escape
212 document.getElementById( r.searchbox ).value = r.original;
213 r.query = r.original;
214 os_hideResults( r );
215 } else if( r.query != document.getElementById( r.searchbox ).value ) {
216 // os_hideResults( r ); // don't show old suggestions
217 }
218 };
219
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];
224 if( r == null ) {
225 return; // not our event
226 }
227
228 var keypressed = os_cur_keypressed;
229
230 os_keypressed_count++;
231 os_processKey( r, keypressed, targ );
232 };
233
234 /** Catch the key code (Firefox bug) */
235 window.os_eventKeydown = function( e ) {
236 if ( !e ) {
237 e = window.event;
238 }
239 var targ = os_getTarget( e );
240 var r = os_map[targ.id];
241 if( r == null ) {
242 return; // not our event
243 }
244
245 os_mouse_moved = false;
246
247 os_cur_keypressed = ( e.keyCode == undefined ) ? e.which : e.keyCode;
248 os_keypressed_count = 0;
249 };
250
251
252 /** When the form is submitted hide everything, cancel updates... */
253 window.os_eventOnsubmit = function( e ) {
254 var targ = os_getTarget( e );
255
256 os_is_stopped = true;
257 // kill timed requests
258 if( os_timer != null && os_timer.id != null ) {
259 clearTimeout( os_timer.id );
260 os_timer = null;
261 }
262 // Hide all suggestions
263 for( i = 0; i < os_autoload_inputs.length; i++ ) {
264 var r = os_map[os_autoload_inputs[i]];
265 if( r != null ) {
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;
270 }
271 os_hideResults( r );
272 }
273 }
274 return true;
275 };
276
277
278
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', '' );
284 } else {
285 var c = document.getElementById( r.container );
286 if ( c != null ) {
287 c.style.visibility = 'hidden';
288 }
289 }
290 r.visible = false;
291 r.selected = -1;
292 };
293
294 window.os_decodeValue = function( value ) {
295 if ( decodeURIComponent ) {
296 return decodeURIComponent( value );
297 }
298 if( unescape ) {
299 return unescape( value );
300 }
301 return null;
302 };
303
304 window.os_encodeQuery = function( value ) {
305 if ( encodeURIComponent ) {
306 return encodeURIComponent( value );
307 }
308 if( escape ) {
309 return escape( value );
310 }
311 return null;
312 };
313
314 /** Handles data from XMLHttpRequest, and updates the suggest results */
315 window.os_updateResults = function( r, query, text, cacheKey ) {
316 os_cache[cacheKey] = text;
317 r.query = query;
318 r.original = query;
319 if( text == '' ) {
320 r.results = null;
321 r.resultCount = 0;
322 os_hideResults( r );
323 } else {
324 try {
325 var p = eval( '(' + text + ')' ); // simple json parse, could do a safer one
326 if( p.length < 2 || p[1].length == 0 ) {
327 r.results = null;
328 r.resultCount = 0;
329 os_hideResults( r );
330 return;
331 }
332 if ( os_use_datalist ) {
333 os_setupDatalist( r, p[1] );
334 } else {
335 os_setupDiv( r, p[1] );
336 }
337 } catch( e ) {
338 // bad response from server or such
339 os_hideResults( r );
340 os_cache[cacheKey] = null;
341 }
342 }
343 };
344
345 /**
346 * Create and populate a <datalist>.
347 *
348 * @param r os_Result object
349 * @param results Array of the new results to replace existing ones
350 */
351 window.os_setupDatalist = function( r, results ) {
352 var s = document.getElementById( r.searchbox );
353 var c = document.getElementById( r.container );
354 if ( c == null ) {
355 c = document.createElement( 'datalist' );
356 c.setAttribute( 'id', r.container );
357 document.body.appendChild( c );
358 } else {
359 c.innerHTML = '';
360 }
361 s.setAttribute( 'list', r.container );
362
363 r.results = new Array();
364 r.resultCount = results.length;
365 r.visible = true;
366 for ( i = 0; i < results.length; i++ ) {
367 var title = os_decodeValue( results[i] );
368 var opt = document.createElement( 'option' );
369 opt.value = title;
370 r.results[i] = title;
371 c.appendChild( opt );
372 }
373 };
374
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 ) {
378 var namespaces = '';
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' &&
383 name[1] == 's' && (
384 ( elements[i].type == 'checkbox' && elements[i].checked ) ||
385 ( elements[i].type == 'hidden' && elements[i].value == '1' )
386 )
387 ) {
388 if( namespaces != '' ) {
389 namespaces += '|';
390 }
391 namespaces += name.substring( 2 );
392 }
393 }
394 if( namespaces == '' ) {
395 namespaces = wgSearchNamespaces.join('|');
396 }
397 return namespaces;
398 };
399
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 );
405 }
406 r.query = query;
407 };
408
409 /** Fetch results after some timeout */
410 window.os_delayedFetch = function() {
411 if( os_timer == null ) {
412 return;
413 }
414 var r = os_timer.r;
415 var query = os_timer.query;
416 os_timer = null;
417 var path = wgMWSuggestTemplate.replace( "{namespaces}", os_getNamespaces( r ) )
418 .replace( "{dbname}", wgDBname )
419 .replace( "{searchTerms}", os_encodeQuery( query ) );
420
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 );
425 } else {
426 var xmlhttp = sajax_init_object();
427 if( xmlhttp ) {
428 try {
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 );
433 }
434 };
435 xmlhttp.send( null );
436 } catch ( e ) {
437 if ( window.location.hostname == 'localhost' ) {
438 alert( "Your browser blocks XMLHttpRequest to 'localhost', try using a real hostname for development/testing." );
439 }
440 throw e;
441 }
442 }
443 }
444 };
445
446 /** Init timed update via os_delayedUpdate() */
447 window.os_fetchResults = function( r, query, timeout ) {
448 if( query == '' ) {
449 r.query = '';
450 os_hideResults( r );
451 return;
452 } else if( query == r.query ) {
453 return; // no change
454 }
455
456 os_is_stopped = false; // make sure we're running
457
458 // cancel any pending fetches
459 if( os_timer != null && os_timer.id != null ) {
460 clearTimeout( os_timer.id );
461 }
462 // schedule delayed fetching of results
463 if( timeout != 0 ) {
464 os_timer = new os_Timer( setTimeout( "os_delayedFetch()", timeout ), r, query );
465 } else {
466 os_timer = new os_Timer( null, r, query );
467 os_delayedFetch(); // do it now!
468 }
469 };
470
471 /** Find event target */
472 window.os_getTarget = function( e ) {
473 if ( !e ) {
474 e = window.event;
475 }
476 if ( e.target ) {
477 return e.target;
478 } else if ( e.srcElement ) {
479 return e.srcElement;
480 } else {
481 return null;
482 }
483 };
484
485 /** Check if x is a valid integer */
486 window.os_isNumber = function( x ) {
487 if( x == '' || isNaN( x ) ) {
488 return false;
489 }
490 for( var i = 0; i < x.length; i++ ) {
491 var c = x.charAt( i );
492 if( !( c >= '0' && c <= '9' ) ) {
493 return false;
494 }
495 }
496 return true;
497 };
498
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 ) );
502 };
503
504 /** Call this to disable suggestios on input box (id=inputId) */
505 window.os_disableSuggestionsOn = function( inputId ) {
506 r = os_map[inputId];
507 if( r != null ) {
508 // cancel/hide results
509 os_timer = null;
510 os_hideResults( r );
511 // turn autocomplete on !
512 document.getElementById( inputId ).setAttribute( 'autocomplete', 'on' );
513 // remove descriptor
514 os_map[inputId] = null;
515 }
516
517 // Remove the element from the os_autoload_* arrays
518 var index = os_autoload_inputs.indexOf( inputId );
519 if ( index >= 0 ) {
520 os_autoload_inputs[index] = os_autoload_forms[index] = '';
521 }
522 };
523
524 /************************************************
525 * Div-only functions (irrelevant for datalist)
526 ************************************************/
527
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];
532 if( r == null ) {
533 return; // not our event
534 }
535 if( !os_mouse_pressed ) {
536 os_hideResults( r );
537 // force canvas to stay hidden
538 r.stayHidden = true;
539 // cancel any pending fetches
540 if( os_timer != null && os_timer.id != null ) {
541 clearTimeout( os_timer.id );
542 }
543 os_timer = null;
544 }
545 };
546
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];
551 if( r == null ) {
552 return; // not our event
553 }
554 r.stayHidden = false;
555 };
556
557 /**
558 * Create and populate a <div>, for non-<datalist>-supporting browsers.
559 *
560 * @param r os_Result object
561 * @param results Array of the new results to replace existing ones
562 */
563 window.os_setupDiv = function( r, results ) {
564 var c = document.getElementById( r.container );
565 if ( c == null ) {
566 c = os_createContainer( r );
567 }
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 );
575 os_showResults( r );
576 };
577
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>';
589 }
590 html += '</table>';
591 return html;
592 };
593
594 /** Show results div */
595 window.os_showResults = function( r ) {
596 if( os_is_stopped ) {
597 return;
598 }
599 if( r.stayHidden ) {
600 return;
601 }
602 os_fitContainer( r );
603 var c = document.getElementById( r.container );
604 r.selected = -1;
605 if( c != null ) {
606 c.scrollTop = 0;
607 c.style.visibility = 'visible';
608 r.visible = true;
609 }
610 };
611
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' ) {
615 return 30;
616 }
617 return 0;
618 };
619
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
626 );
627 };
628
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
634 );
635 };
636
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
642 );
643 };
644
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
650 );
651 };
652
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 ) ) ) {
656 n_result = n_docel;
657 }
658 return n_body && ( !n_result || ( n_result > n_body ) ) ? n_body : n_result;
659 };
660
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' );
665 if( px > 0 ) {
666 absTop = absTop.substring( 0, px );
667 }
668 return f_clientHeight() - ( absTop - f_scrollTop() );
669 };
670
671 /** Get element absolute position {left,top} */
672 window.os_getElementPosition = function( elemID ) {
673 var offsetTrail = document.getElementById( elemID );
674 var offsetLeft = 0;
675 var offsetTop = 0;
676 while ( offsetTrail ) {
677 offsetLeft += offsetTrail.offsetLeft;
678 offsetTop += offsetTrail.offsetTop;
679 offsetTrail = offsetTrail.offsetParent;
680 }
681 if ( navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined' ) {
682 offsetLeft += document.body.leftMargin;
683 offsetTop += document.body.topMargin;
684 }
685 return { left:offsetLeft, top:offsetTop };
686 };
687
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);
693 var left = pos.left;
694 var top = pos.top + s.offsetHeight;
695 c.className = 'os-suggest';
696 c.setAttribute('id', r.container);
697 document.body.appendChild(c);
698
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';
705
706 // mouse event handlers
707 c.onmouseover = function(event) {
708 os_eventMouseover(r.searchbox, event);
709 };
710 c.onmousemove = function(event) {
711 os_eventMousemove(r.searchbox, event);
712 };
713 c.onmousedown = function(event) {
714 return os_eventMousedown(r.searchbox, event);
715 };
716 c.onmouseup = function(event) {
717 os_eventMouseup(r.searchbox, event);
718 };
719 return c;
720 };
721
722 /** change container height to fit to screen */
723 window.os_fitContainer = function( r ) {
724 var c = document.getElementById( r.container );
725 var h = os_availableHeight( r ) - 20;
726 var inc = r.containerRow;
727 h = parseInt( h / inc ) * inc;
728 if( h < ( 2 * inc ) && r.resultCount > 1 ) { // min: two results
729 h = 2 * inc;
730 }
731 if( ( h / inc ) > os_max_lines_per_suggest ) {
732 h = inc * os_max_lines_per_suggest;
733 }
734 if( h < r.containerTotal ) {
735 c.style.height = h + 'px';
736 r.containerCount = parseInt( Math.round( h / inc ) );
737 } else {
738 c.style.height = r.containerTotal + 'px';
739 r.containerCount = r.resultCount;
740 }
741 };
742
743 /** If some entries are longer than the box, replace text with "..." */
744 window.os_trimResultText = function( r ) {
745 // find max width, first see if we could expand the container to fit it
746 var maxW = 0;
747 for( var i = 0; i < r.resultCount; i++ ) {
748 var e = document.getElementById( r.resultText + i );
749 if( e.offsetWidth > maxW ) {
750 maxW = e.offsetWidth;
751 }
752 }
753 var w = document.getElementById( r.container ).offsetWidth;
754 var fix = 0;
755 if( r.containerCount < r.resultCount ) {
756 fix = 20; // give 20px for scrollbar
757 } else {
758 fix = os_operaWidthFix( w );
759 }
760 if( fix < 4 ) {
761 fix = 4; // basic padding
762 }
763 maxW += fix;
764
765 // resize container to fit more data if permitted
766 var normW = document.getElementById( r.searchbox ).offsetWidth;
767 var prop = maxW / normW;
768 if( prop > os_container_max_width ) {
769 prop = os_container_max_width;
770 } else if( prop < 1 ) {
771 prop = 1;
772 }
773 var newW = Math.round( normW * prop );
774 if( w != newW ) {
775 w = newW;
776 if( os_animation_timer != null ) {
777 clearInterval( os_animation_timer.id );
778 }
779 os_animation_timer = new os_AnimationTimer( r, w );
780 os_animation_timer.id = setInterval( "os_animateChangeWidth()", os_animation_delay );
781 w -= fix; // this much is reserved
782 }
783
784 // trim results
785 if( w < 10 ) {
786 return;
787 }
788 for( var i = 0; i < r.resultCount; i++ ) {
789 var e = document.getElementById( r.resultText + i );
790 var replace = 1;
791 var lastW = e.offsetWidth + 1;
792 var iteration = 0;
793 var changedText = false;
794 while( e.offsetWidth > w && ( e.offsetWidth < lastW || iteration < 2 ) ) {
795 changedText = true;
796 lastW = e.offsetWidth;
797 var l = e.innerHTML;
798 e.innerHTML = l.substring( 0, l.length - replace ) + '...';
799 iteration++;
800 replace = 4; // how many chars to replace
801 }
802 if( changedText ) {
803 // show hint for trimmed titles
804 document.getElementById( r.resultTable + i ).setAttribute( 'title', r.results[i] );
805 }
806 }
807 };
808
809 /** Invoked on timer to animate change in container width */
810 window.os_animateChangeWidth = function() {
811 var r = os_animation_timer.r;
812 var c = document.getElementById( r.container );
813 var w = c.offsetWidth;
814 var normW = document.getElementById( r.searchbox ).offsetWidth;
815 var normL = os_getElementPosition( r.searchbox ).left;
816 var inc = os_animation_timer.inc;
817 var target = os_animation_timer.target;
818 var nw = w + inc;
819 if( ( inc > 0 && nw >= target ) || ( inc <= 0 && nw <= target ) ) {
820 // finished !
821 c.style.width = target + 'px';
822 clearInterval( os_animation_timer.id );
823 os_animation_timer = null;
824 } else {
825 // in-progress
826 c.style.width = nw + 'px';
827 if( document.documentElement.dir == 'rtl' ) {
828 c.style.left = ( normL + normW + ( target - nw ) - os_animation_timer.target - 1 ) + 'px';
829 }
830 }
831 };
832
833 /** Change the highlighted row (i.e. suggestion), from position cur to next */
834 window.os_changeHighlight = function( r, cur, next, updateSearchBox ) {
835 if ( next >= r.resultCount ) {
836 next = r.resultCount - 1;
837 }
838 if ( next < -1 ) {
839 next = -1;
840 }
841 r.selected = next;
842 if ( cur == next ) {
843 return; // nothing to do.
844 }
845
846 if( cur >= 0 ) {
847 var curRow = document.getElementById( r.resultTable + cur );
848 if( curRow != null ) {
849 curRow.className = 'os-suggest-result';
850 }
851 }
852 var newText;
853 if( next >= 0 ) {
854 var nextRow = document.getElementById( r.resultTable + next );
855 if( nextRow != null ) {
856 nextRow.className = os_HighlightClass();
857 }
858 newText = r.results[next];
859 } else {
860 newText = r.original;
861 }
862
863 // adjust the scrollbar if any
864 if( r.containerCount < r.resultCount ) {
865 var c = document.getElementById( r.container );
866 var vStart = c.scrollTop / r.containerRow;
867 var vEnd = vStart + r.containerCount;
868 if( next < vStart ) {
869 c.scrollTop = next * r.containerRow;
870 } else if( next >= vEnd ) {
871 c.scrollTop = ( next - r.containerCount + 1 ) * r.containerRow;
872 }
873 }
874
875 // update the contents of the search box
876 if( updateSearchBox ) {
877 os_updateSearchQuery( r, newText );
878 }
879 };
880
881 window.os_HighlightClass = function() {
882 var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
883 if ( match ) {
884 var webKitVersion = parseInt( match[1] );
885 if ( webKitVersion < 523 ) {
886 // CSS system highlight colors broken on old Safari
887 // https://bugs.webkit.org/show_bug.cgi?id=6129
888 // Safari 3.0.4, 3.1 known ok
889 return 'os-suggest-result-hl-webkit';
890 }
891 }
892 return 'os-suggest-result-hl';
893 };
894
895 window.os_updateSearchQuery = function( r, newText ) {
896 document.getElementById( r.searchbox ).value = newText;
897 r.query = newText;
898 };
899
900
901 /********************
902 * Mouse events
903 ********************/
904
905 /** Mouse over the container */
906 window.os_eventMouseover = function( srcId, e ) {
907 var targ = os_getTarget( e );
908 var r = os_map[srcId];
909 if( r == null || !os_mouse_moved ) {
910 return; // not our event
911 }
912 var num = os_getNumberSuffix( targ.id );
913 if( num >= 0 ) {
914 os_changeHighlight( r, r.selected, num, false );
915 }
916 };
917
918 /* Get row where the event occured (from its id) */
919 window.os_getNumberSuffix = function( id ) {
920 var num = id.substring( id.length - 2 );
921 if( !( num.charAt( 0 ) >= '0' && num.charAt( 0 ) <= '9' ) ) {
922 num = num.substring( 1 );
923 }
924 if( os_isNumber( num ) ) {
925 return parseInt( num );
926 } else {
927 return -1;
928 }
929 };
930
931 /** Save mouse move as last action */
932 window.os_eventMousemove = function( srcId, e ) {
933 os_mouse_moved = true;
934 };
935
936 /** Mouse button held down, register possible click */
937 window.os_eventMousedown = function( srcId, e ) {
938 var targ = os_getTarget( e );
939 var r = os_map[srcId];
940 if( r == null ) {
941 return; // not our event
942 }
943 var num = os_getNumberSuffix( targ.id );
944
945 os_mouse_pressed = true;
946 if( num >= 0 ) {
947 os_mouse_num = num;
948 // os_updateSearchQuery( r, r.results[num] );
949 }
950 // keep the focus on the search field
951 document.getElementById( r.searchbox ).focus();
952
953 return false; // prevents selection
954 };
955
956 /** Mouse button released, check for click on some row */
957 window.os_eventMouseup = function( srcId, e ) {
958 var targ = os_getTarget( e );
959 var r = os_map[srcId];
960 if( r == null ) {
961 return; // not our event
962 }
963 var num = os_getNumberSuffix( targ.id );
964
965 if( num >= 0 && os_mouse_num == num ) {
966 os_updateSearchQuery( r, r.results[num] );
967 os_hideResults( r );
968 document.getElementById( r.searchform ).submit();
969 }
970 os_mouse_pressed = false;
971 // keep the focus on the search field
972 document.getElementById( r.searchbox ).focus();
973 };
974
975 /** Toggle stuff seems to be dead code? */
976
977 /** Return the span element that contains the toggle link */
978 window.os_createToggle = function( r, className ) {
979 var t = document.createElement( 'span' );
980 t.className = className;
981 t.setAttribute( 'id', r.toggle );
982 var link = document.createElement( 'a' );
983 link.setAttribute( 'href', 'javascript:void(0);' );
984 link.onclick = function() { os_toggle( r.searchbox, r.searchform ); };
985 var msg = document.createTextNode( wgMWSuggestMessages[0] );
986 link.appendChild( msg );
987 t.appendChild( link );
988 return t;
989 };
990
991 /** Call when user clicks on some of the toggle links */
992 window.os_toggle = function( inputId, formName ) {
993 r = os_map[inputId];
994 var msg = '';
995 if( r == null ) {
996 os_enableSuggestionsOn( inputId, formName );
997 r = os_map[inputId];
998 msg = wgMWSuggestMessages[0];
999 } else{
1000 os_disableSuggestionsOn( inputId, formName );
1001 msg = wgMWSuggestMessages[1];
1002 }
1003 // change message
1004 var link = document.getElementById( r.toggle ).firstChild;
1005 link.replaceChild( document.createTextNode( msg ), link.firstChild );
1006 };
1007
1008 hookEvent( 'load', os_MWSuggestInit );