renaming mediawiki.specials to mediawiki.special (matches the Special-pagename and...
[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 ) { 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 ); };
711 return c;
712 }
713
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
721 h = 2 * inc;
722 }
723 if( ( h / inc ) > os_max_lines_per_suggest ) {
724 h = inc * os_max_lines_per_suggest;
725 }
726 if( h < r.containerTotal ) {
727 c.style.height = h + 'px';
728 r.containerCount = parseInt( Math.round( h / inc ) );
729 } else {
730 c.style.height = r.containerTotal + 'px';
731 r.containerCount = r.resultCount;
732 }
733 }
734
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
738 var maxW = 0;
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;
743 }
744 }
745 var w = document.getElementById( r.container ).offsetWidth;
746 var fix = 0;
747 if( r.containerCount < r.resultCount ) {
748 fix = 20; // give 20px for scrollbar
749 } else {
750 fix = os_operaWidthFix( w );
751 }
752 if( fix < 4 ) {
753 fix = 4; // basic padding
754 }
755 maxW += fix;
756
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 ) {
763 prop = 1;
764 }
765 var newW = Math.round( normW * prop );
766 if( w != newW ) {
767 w = newW;
768 if( os_animation_timer != null ) {
769 clearInterval( os_animation_timer.id );
770 }
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
774 }
775
776 // trim results
777 if( w < 10 ) {
778 return;
779 }
780 for( var i = 0; i < r.resultCount; i++ ) {
781 var e = document.getElementById( r.resultText + i );
782 var replace = 1;
783 var lastW = e.offsetWidth + 1;
784 var iteration = 0;
785 var changedText = false;
786 while( e.offsetWidth > w && ( e.offsetWidth < lastW || iteration < 2 ) ) {
787 changedText = true;
788 lastW = e.offsetWidth;
789 var l = e.innerHTML;
790 e.innerHTML = l.substring( 0, l.length - replace ) + '...';
791 iteration++;
792 replace = 4; // how many chars to replace
793 }
794 if( changedText ) {
795 // show hint for trimmed titles
796 document.getElementById( r.resultTable + i ).setAttribute( 'title', r.results[i] );
797 }
798 }
799 }
800
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;
810 var nw = w + inc;
811 if( ( inc > 0 && nw >= target ) || ( inc <= 0 && nw <= target ) ) {
812 // finished !
813 c.style.width = target + 'px';
814 clearInterval( os_animation_timer.id );
815 os_animation_timer = null;
816 } else {
817 // in-progress
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';
821 }
822 }
823 }
824
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;
829 }
830 if ( next < -1 ) {
831 next = -1;
832 }
833 r.selected = next;
834 if ( cur == next ) {
835 return; // nothing to do.
836 }
837
838 if( cur >= 0 ) {
839 var curRow = document.getElementById( r.resultTable + cur );
840 if( curRow != null ) {
841 curRow.className = 'os-suggest-result';
842 }
843 }
844 var newText;
845 if( next >= 0 ) {
846 var nextRow = document.getElementById( r.resultTable + next );
847 if( nextRow != null ) {
848 nextRow.className = os_HighlightClass();
849 }
850 newText = r.results[next];
851 } else {
852 newText = r.original;
853 }
854
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;
864 }
865 }
866
867 // update the contents of the search box
868 if( updateSearchBox ) {
869 os_updateSearchQuery( r, newText );
870 }
871 }
872
873 window.os_HighlightClass = function() {
874 var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
875 if ( match ) {
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';
882 }
883 }
884 return 'os-suggest-result-hl';
885 }
886
887 window.os_updateSearchQuery = function( r, newText ) {
888 document.getElementById( r.searchbox ).value = newText;
889 r.query = newText;
890 }
891
892
893 /********************
894 * Mouse events
895 ********************/
896
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
903 }
904 var num = os_getNumberSuffix( targ.id );
905 if( num >= 0 ) {
906 os_changeHighlight( r, r.selected, num, false );
907 }
908 }
909
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 );
915 }
916 if( os_isNumber( num ) ) {
917 return parseInt( num );
918 } else {
919 return -1;
920 }
921 }
922
923 /** Save mouse move as last action */
924 window.os_eventMousemove = function( srcId, e ) {
925 os_mouse_moved = true;
926 }
927
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];
932 if( r == null ) {
933 return; // not our event
934 }
935 var num = os_getNumberSuffix( targ.id );
936
937 os_mouse_pressed = true;
938 if( num >= 0 ) {
939 os_mouse_num = num;
940 // os_updateSearchQuery( r, r.results[num] );
941 }
942 // keep the focus on the search field
943 document.getElementById( r.searchbox ).focus();
944
945 return false; // prevents selection
946 }
947
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];
952 if( r == null ) {
953 return; // not our event
954 }
955 var num = os_getNumberSuffix( targ.id );
956
957 if( num >= 0 && os_mouse_num == num ) {
958 os_updateSearchQuery( r, r.results[num] );
959 os_hideResults( r );
960 document.getElementById( r.searchform ).submit();
961 }
962 os_mouse_pressed = false;
963 // keep the focus on the search field
964 document.getElementById( r.searchbox ).focus();
965 }
966
967 /** Toggle stuff seems to be dead code? */
968
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 );
980 return t;
981 }
982
983 /** Call when user clicks on some of the toggle links */
984 window.os_toggle = function( inputId, formName ) {
985 r = os_map[inputId];
986 var msg = '';
987 if( r == null ) {
988 os_enableSuggestionsOn( inputId, formName );
989 r = os_map[inputId];
990 msg = wgMWSuggestMessages[0];
991 } else{
992 os_disableSuggestionsOn( inputId, formName );
993 msg = wgMWSuggestMessages[1];
994 }
995 // change message
996 var link = document.getElementById( r.toggle ).firstChild;
997 link.replaceChild( document.createTextNode( msg ), link.firstChild );
998 }
999
1000 hookEvent( 'load', os_MWSuggestInit );