Disable the mysterious keypress throttling that overrides your operating system's...
[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 var os_map = {};
12 // cached data, url -> json_text
13 var os_cache = {};
14 // global variables for suggest_keypress
15 var os_cur_keypressed = 0;
16 var os_keypressed_count = 0;
17 // type: Timer
18 var os_timer = null;
19 // tie mousedown/up events
20 var os_mouse_pressed = false;
21 var os_mouse_num = -1;
22 // if true, the last change was made by mouse (and not keyboard)
23 var os_mouse_moved = false;
24 // delay between keypress and suggestion (in ms)
25 var os_search_timeout = 250;
26 // these pairs of inputs/forms will be autoloaded at startup
27 var os_autoload_inputs = new Array('searchInput', 'searchInput2', 'powerSearchText', 'searchText');
28 var os_autoload_forms = new Array('searchform', 'searchform2', 'powersearch', 'search' );
29 // if we stopped the service
30 var os_is_stopped = false;
31 // max lines to show in suggest table
32 var os_max_lines_per_suggest = 7;
33 // number of steps to animate expansion/contraction of container width
34 var os_animation_steps = 6;
35 // num of pixels of smallest step
36 var os_animation_min_step = 2;
37 // delay between steps (in ms)
38 var os_animation_delay = 30;
39 // max width of container in percent of normal size (1 == 100%)
40 var os_container_max_width = 2;
41 // currently active animation timer
42 var os_animation_timer = null;
43
44 /** Timeout timer class that will fetch the results */
45 function os_Timer(id,r,query){
46 this.id = id;
47 this.r = r;
48 this.query = query;
49 }
50
51 /** Timer user to animate expansion/contraction of container width */
52 function os_AnimationTimer(r, target){
53 this.r = r;
54 var current = document.getElementById(r.container).offsetWidth;
55 this.inc = Math.round((target-current) / os_animation_steps);
56 if(this.inc < os_animation_min_step && this.inc >=0)
57 this.inc = os_animation_min_step; // minimal animation step
58 if(this.inc > -os_animation_min_step && this.inc <0)
59 this.inc = -os_animation_min_step;
60 this.target = target;
61 }
62
63 /** Property class for single search box */
64 function os_Results(name, formname){
65 this.searchform = formname; // id of the searchform
66 this.searchbox = name; // id of the searchbox
67 this.container = name+"Suggest"; // div that holds results
68 this.resultTable = name+"Result"; // id base for the result table (+num = table row)
69 this.resultText = name+"ResultText"; // id base for the spans within result tables (+num)
70 this.toggle = name+"Toggle"; // div that has the toggle (enable/disable) link
71 this.query = null; // last processed query
72 this.results = null; // parsed titles
73 this.resultCount = 0; // number of results
74 this.original = null; // query that user entered
75 this.selected = -1; // which result is selected
76 this.containerCount = 0; // number of results visible in container
77 this.containerRow = 0; // height of result field in the container
78 this.containerTotal = 0; // total height of the container will all results
79 this.visible = false; // if container is visible
80 this.stayHidden = false; // don't try to show if lost focus
81 }
82
83 /** Hide results div */
84 function os_hideResults(r){
85 var c = document.getElementById(r.container);
86 if(c != null)
87 c.style.visibility = "hidden";
88 r.visible = false;
89 r.selected = -1;
90 }
91
92 /** Show results div */
93 function os_showResults(r){
94 if(os_is_stopped)
95 return;
96 if(r.stayHidden)
97 return
98 os_fitContainer(r);
99 var c = document.getElementById(r.container);
100 r.selected = -1;
101 if(c != null){
102 c.scrollTop = 0;
103 c.style.visibility = "visible";
104 r.visible = true;
105 }
106 }
107
108 function os_operaWidthFix(x){
109 // For browsers that don't understand overflow-x, estimate scrollbar width
110 if(typeof document.body.style.overflowX != "string"){
111 return 30;
112 }
113 return 0;
114 }
115
116 function os_encodeQuery(value){
117 if (encodeURIComponent) {
118 return encodeURIComponent(value);
119 }
120 if(escape) {
121 return escape(value);
122 }
123 return null;
124 }
125 function os_decodeValue(value){
126 if (decodeURIComponent) {
127 return decodeURIComponent(value);
128 }
129 if(unescape){
130 return unescape(value);
131 }
132 return null;
133 }
134
135 /** Brower-dependent functions to find window inner size, and scroll status */
136 function f_clientWidth() {
137 return f_filterResults (
138 window.innerWidth ? window.innerWidth : 0,
139 document.documentElement ? document.documentElement.clientWidth : 0,
140 document.body ? document.body.clientWidth : 0
141 );
142 }
143 function f_clientHeight() {
144 return f_filterResults (
145 window.innerHeight ? window.innerHeight : 0,
146 document.documentElement ? document.documentElement.clientHeight : 0,
147 document.body ? document.body.clientHeight : 0
148 );
149 }
150 function f_scrollLeft() {
151 return f_filterResults (
152 window.pageXOffset ? window.pageXOffset : 0,
153 document.documentElement ? document.documentElement.scrollLeft : 0,
154 document.body ? document.body.scrollLeft : 0
155 );
156 }
157 function f_scrollTop() {
158 return f_filterResults (
159 window.pageYOffset ? window.pageYOffset : 0,
160 document.documentElement ? document.documentElement.scrollTop : 0,
161 document.body ? document.body.scrollTop : 0
162 );
163 }
164 function f_filterResults(n_win, n_docel, n_body) {
165 var n_result = n_win ? n_win : 0;
166 if (n_docel && (!n_result || (n_result > n_docel)))
167 n_result = n_docel;
168 return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
169 }
170
171 /** Get the height available for the results container */
172 function os_availableHeight(r){
173 var absTop = document.getElementById(r.container).style.top;
174 var px = absTop.lastIndexOf("px");
175 if(px > 0)
176 absTop = absTop.substring(0,px);
177 return f_clientHeight() - (absTop - f_scrollTop());
178 }
179
180
181 /** Get element absolute position {left,top} */
182 function os_getElementPosition(elemID){
183 var offsetTrail = document.getElementById(elemID);
184 var offsetLeft = 0;
185 var offsetTop = 0;
186 while (offsetTrail){
187 offsetLeft += offsetTrail.offsetLeft;
188 offsetTop += offsetTrail.offsetTop;
189 offsetTrail = offsetTrail.offsetParent;
190 }
191 if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined'){
192 offsetLeft += document.body.leftMargin;
193 offsetTop += document.body.topMargin;
194 }
195 return {left:offsetLeft,top:offsetTop};
196 }
197
198 /** Create the container div that will hold the suggested titles */
199 function os_createContainer(r){
200 var c = document.createElement("div");
201 var s = document.getElementById(r.searchbox);
202 var pos = os_getElementPosition(r.searchbox);
203 var left = pos.left;
204 var top = pos.top + s.offsetHeight;
205 c.className = "os-suggest";
206 c.setAttribute("id", r.container);
207 document.body.appendChild(c);
208
209 // dynamically generated style params
210 // IE workaround, cannot explicitely set "style" attribute
211 c = document.getElementById(r.container);
212 c.style.top = top+"px";
213 c.style.left = left+"px";
214 c.style.width = s.offsetWidth+"px";
215
216 // mouse event handlers
217 c.onmouseover = function(event) { os_eventMouseover(r.searchbox, event); };
218 c.onmousemove = function(event) { os_eventMousemove(r.searchbox, event); };
219 c.onmousedown = function(event) { return os_eventMousedown(r.searchbox, event); };
220 c.onmouseup = function(event) { os_eventMouseup(r.searchbox, event); };
221 return c;
222 }
223
224 /** change container height to fit to screen */
225 function os_fitContainer(r){
226 var c = document.getElementById(r.container);
227 var h = os_availableHeight(r) - 20;
228 var inc = r.containerRow;
229 h = parseInt(h/inc) * inc;
230 if(h < (2 * inc) && r.resultCount > 1) // min: two results
231 h = 2 * inc;
232 if((h/inc) > os_max_lines_per_suggest )
233 h = inc * os_max_lines_per_suggest;
234 if(h < r.containerTotal){
235 c.style.height = h +"px";
236 r.containerCount = parseInt(Math.round(h/inc));
237 } else{
238 c.style.height = r.containerTotal+"px";
239 r.containerCount = r.resultCount;
240 }
241 }
242 /** If some entries are longer than the box, replace text with "..." */
243 function os_trimResultText(r){
244 // find max width, first see if we could expand the container to fit it
245 var maxW = 0;
246 for(var i=0;i<r.resultCount;i++){
247 var e = document.getElementById(r.resultText+i);
248 if(e.offsetWidth > maxW)
249 maxW = e.offsetWidth;
250 }
251 var w = document.getElementById(r.container).offsetWidth;
252 var fix = 0;
253 if(r.containerCount < r.resultCount){
254 fix = 20; // give 20px for scrollbar
255 } else
256 fix = os_operaWidthFix(w);
257 if(fix < 4)
258 fix = 4; // basic padding
259 maxW += fix;
260
261 // resize container to fit more data if permitted
262 var normW = document.getElementById(r.searchbox).offsetWidth;
263 var prop = maxW / normW;
264 if(prop > os_container_max_width)
265 prop = os_container_max_width;
266 else if(prop < 1)
267 prop = 1;
268 var newW = Math.round( normW * prop );
269 if( w != newW ){
270 w = newW;
271 if( os_animation_timer != null )
272 clearInterval(os_animation_timer.id)
273 os_animation_timer = new os_AnimationTimer(r,w);
274 os_animation_timer.id = setInterval("os_animateChangeWidth()",os_animation_delay);
275 w -= fix; // this much is reserved
276 }
277
278 // trim results
279 if(w < 10)
280 return;
281 for(var i=0;i<r.resultCount;i++){
282 var e = document.getElementById(r.resultText+i);
283 var replace = 1;
284 var lastW = e.offsetWidth+1;
285 var iteration = 0;
286 var changedText = false;
287 while(e.offsetWidth > w && (e.offsetWidth < lastW || iteration<2)){
288 changedText = true;
289 lastW = e.offsetWidth;
290 var l = e.innerHTML;
291 e.innerHTML = l.substring(0,l.length-replace)+"...";
292 iteration++;
293 replace = 4; // how many chars to replace
294 }
295 if(changedText){
296 // show hint for trimmed titles
297 document.getElementById(r.resultTable+i).setAttribute("title",r.results[i]);
298 }
299 }
300 }
301
302 /** Invoked on timer to animate change in container width */
303 function os_animateChangeWidth(){
304 var r = os_animation_timer.r;
305 var c = document.getElementById(r.container);
306 var w = c.offsetWidth;
307 var normW = document.getElementById(r.searchbox).offsetWidth;
308 var normL = os_getElementPosition(r.searchbox).left;
309 var inc = os_animation_timer.inc;
310 var target = os_animation_timer.target;
311 var nw = w + inc;
312 if( (inc > 0 && nw >= target) || (inc <= 0 && nw <= target) ){
313 // finished !
314 c.style.width = target+"px";
315 clearInterval(os_animation_timer.id)
316 os_animation_timer = null;
317 } else{
318 // in-progress
319 c.style.width = nw+"px";
320 if(document.documentElement.dir == "rtl")
321 c.style.left = (normL + normW + (target - nw) - os_animation_timer.target - 1)+"px";
322 }
323 }
324
325 /** Handles data from XMLHttpRequest, and updates the suggest results */
326 function os_updateResults(r, query, text, cacheKey){
327 os_cache[cacheKey] = text;
328 r.query = query;
329 r.original = query;
330 if(text == ""){
331 r.results = null;
332 r.resultCount = 0;
333 os_hideResults(r);
334 } else{
335 try {
336 var p = eval('('+text+')'); // simple json parse, could do a safer one
337 if(p.length<2 || p[1].length == 0){
338 r.results = null;
339 r.resultCount = 0;
340 os_hideResults(r);
341 return;
342 }
343 var c = document.getElementById(r.container);
344 if(c == null)
345 c = os_createContainer(r);
346 c.innerHTML = os_createResultTable(r,p[1]);
347 // init container table sizes
348 var t = document.getElementById(r.resultTable);
349 r.containerTotal = t.offsetHeight;
350 r.containerRow = t.offsetHeight / r.resultCount;
351 os_fitContainer(r);
352 os_trimResultText(r);
353 os_showResults(r);
354 } catch(e){
355 // bad response from server or such
356 os_hideResults(r);
357 os_cache[cacheKey] = null;
358 }
359 }
360 }
361
362 /** Create the result table to be placed in the container div */
363 function os_createResultTable(r, results){
364 var c = document.getElementById(r.container);
365 var width = c.offsetWidth - os_operaWidthFix(c.offsetWidth);
366 var html = "<table class=\"os-suggest-results\" id=\""+r.resultTable+"\" style=\"width: "+width+"px;\">";
367 r.results = new Array();
368 r.resultCount = results.length;
369 for(i=0;i<results.length;i++){
370 var title = os_decodeValue(results[i]);
371 r.results[i] = title;
372 html += "<tr><td class=\"os-suggest-result\" id=\""+r.resultTable+i+"\"><span id=\""+r.resultText+i+"\">"+title+"</span></td></tr>";
373 }
374 html+="</table>"
375 return html;
376 }
377
378 /** Fetch namespaces from checkboxes or hidden fields in the search form,
379 if none defined use wgSearchNamespaces global */
380 function os_getNamespaces(r){
381 var namespaces = "";
382 var elements = document.forms[r.searchform].elements;
383 for(i=0; i < elements.length; i++){
384 var name = elements[i].name;
385 if(typeof name != 'undefined' && name.length > 2
386 && name[0]=='n' && name[1]=='s'
387 && ((elements[i].type=='checkbox' && elements[i].checked)
388 || (elements[i].type=='hidden' && elements[i].value=="1")) ){
389 if(namespaces!="")
390 namespaces+="|";
391 namespaces+=name.substring(2);
392 }
393 }
394 if(namespaces == "")
395 namespaces = wgSearchNamespaces.join("|");
396 return namespaces;
397 }
398
399 /** Update results if user hasn't already typed something else */
400 function os_updateIfRelevant(r, query, text, cacheKey){
401 var t = document.getElementById(r.searchbox);
402 if(t != null && t.value == query){ // check if response is still relevant
403 os_updateResults(r, query, text, cacheKey);
404 }
405 r.query = query;
406 }
407
408 /** Fetch results after some timeout */
409 function os_delayedFetch(){
410 if(os_timer == null)
411 return;
412 var r = os_timer.r;
413 var query = os_timer.query;
414 os_timer = null;
415 var path = wgMWSuggestTemplate.replace("{namespaces}",os_getNamespaces(r))
416 .replace("{dbname}",wgDBname)
417 .replace("{searchTerms}",os_encodeQuery(query));
418
419 // try to get from cache, if not fetch using ajax
420 var cached = os_cache[path];
421 if(cached != null){
422 os_updateIfRelevant(r, query, cached, path);
423 } else{
424 var xmlhttp = sajax_init_object();
425 if(xmlhttp){
426 try {
427 xmlhttp.open("GET", path, true);
428 xmlhttp.onreadystatechange=function(){
429 if (xmlhttp.readyState==4 && typeof os_updateIfRelevant == 'function') {
430 os_updateIfRelevant(r, query, xmlhttp.responseText, path);
431 }
432 };
433 xmlhttp.send(null);
434 } catch (e) {
435 if (window.location.hostname == "localhost") {
436 alert("Your browser blocks XMLHttpRequest to 'localhost', try using a real hostname for development/testing.");
437 }
438 throw e;
439 }
440 }
441 }
442 }
443
444 /** Init timed update via os_delayedUpdate() */
445 function os_fetchResults(r, query, timeout){
446 if(query == ""){
447 r.query = "";
448 os_hideResults(r);
449 return;
450 } else if(query == r.query)
451 return; // no change
452
453 os_is_stopped = false; // make sure we're running
454
455 /* var cacheKey = wgDBname+":"+query;
456 var cached = os_cache[cacheKey];
457 if(cached != null){
458 os_updateResults(r,wgDBname,query,cached);
459 return;
460 } */
461
462 // cancel any pending fetches
463 if(os_timer != null && os_timer.id != null)
464 clearTimeout(os_timer.id);
465 // schedule delayed fetching of results
466 if(timeout != 0){
467 os_timer = new os_Timer(setTimeout("os_delayedFetch()",timeout),r,query);
468 } else{
469 os_timer = new os_Timer(null,r,query);
470 os_delayedFetch(); // do it now!
471 }
472
473 }
474 /** Change the highlighted row (i.e. suggestion), from position cur to next */
475 function os_changeHighlight(r, cur, next, updateSearchBox){
476 if (next >= r.resultCount)
477 next = r.resultCount-1;
478 if (next < -1)
479 next = -1;
480 r.selected = next;
481 if (cur == next)
482 return; // nothing to do.
483
484 if(cur >= 0){
485 var curRow = document.getElementById(r.resultTable + cur);
486 if(curRow != null)
487 curRow.className = "os-suggest-result";
488 }
489 var newText;
490 if(next >= 0){
491 var nextRow = document.getElementById(r.resultTable + next);
492 if(nextRow != null)
493 nextRow.className = os_HighlightClass();
494 newText = r.results[next];
495 } else
496 newText = r.original;
497
498 // adjust the scrollbar if any
499 if(r.containerCount < r.resultCount){
500 var c = document.getElementById(r.container);
501 var vStart = c.scrollTop / r.containerRow;
502 var vEnd = vStart + r.containerCount;
503 if(next < vStart)
504 c.scrollTop = next * r.containerRow;
505 else if(next >= vEnd)
506 c.scrollTop = (next - r.containerCount + 1) * r.containerRow;
507 }
508
509 // update the contents of the search box
510 if(updateSearchBox){
511 os_updateSearchQuery(r,newText);
512 }
513 }
514
515 function os_HighlightClass() {
516 var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
517 if (match) {
518 var webKitVersion = parseInt(match[1]);
519 if (webKitVersion < 523) {
520 // CSS system highlight colors broken on old Safari
521 // https://bugs.webkit.org/show_bug.cgi?id=6129
522 // Safari 3.0.4, 3.1 known ok
523 return "os-suggest-result-hl-webkit";
524 }
525 }
526 return "os-suggest-result-hl";
527 }
528
529 function os_updateSearchQuery(r,newText){
530 document.getElementById(r.searchbox).value = newText;
531 r.query = newText;
532 }
533
534 /** Find event target */
535 function os_getTarget(e){
536 if (!e) e = window.event;
537 if (e.target) return e.target;
538 else if (e.srcElement) return e.srcElement;
539 else return null;
540 }
541
542
543
544 /********************
545 * Keyboard events
546 ********************/
547
548 /** Event handler that will fetch results on keyup */
549 function os_eventKeyup(e){
550 var targ = os_getTarget(e);
551 var r = os_map[targ.id];
552 if(r == null)
553 return; // not our event
554
555 // some browsers won't generate keypressed for arrow keys, catch it
556 if(os_keypressed_count == 0){
557 os_processKey(r,os_cur_keypressed,targ);
558 }
559 var query = targ.value;
560 os_fetchResults(r,query,os_search_timeout);
561 }
562
563 /** catch arrows up/down and escape to hide the suggestions */
564 function os_processKey(r,keypressed,targ){
565 if (keypressed == 40){ // Arrow Down
566 if (r.visible) {
567 os_changeHighlight(r, r.selected, r.selected+1, true);
568 } else if(os_timer == null){
569 // user wants to get suggestions now
570 r.query = "";
571 os_fetchResults(r,targ.value,0);
572 }
573 } else if (keypressed == 38){ // Arrow Up
574 if (r.visible){
575 os_changeHighlight(r, r.selected, r.selected-1, true);
576 }
577 } else if(keypressed == 27){ // Escape
578 document.getElementById(r.searchbox).value = r.original;
579 r.query = r.original;
580 os_hideResults(r);
581 } else if(r.query != document.getElementById(r.searchbox).value){
582 // os_hideResults(r); // don't show old suggestions
583 }
584 }
585
586 /** When keys is held down use a timer to output regular events */
587 function os_eventKeypress(e){
588 var targ = os_getTarget(e);
589 var r = os_map[targ.id];
590 if(r == null)
591 return; // not our event
592
593 var keypressed = os_cur_keypressed;
594
595 os_keypressed_count++;
596 os_processKey(r,keypressed,targ);
597 }
598
599 /** Catch the key code (Firefox bug) */
600 function os_eventKeydown(e){
601 if (!e) e = window.event;
602 var targ = os_getTarget(e);
603 var r = os_map[targ.id];
604 if(r == null)
605 return; // not our event
606
607 os_mouse_moved = false;
608
609 os_cur_keypressed = (e.keyCode == undefined) ? e.which : e.keyCode;
610 os_keypressed_count = 0;
611 }
612
613 /** Event: loss of focus of input box */
614 function os_eventBlur(e){
615 var targ = os_getTarget(e);
616 var r = os_map[targ.id];
617 if(r == null)
618 return; // not our event
619 if(!os_mouse_pressed){
620 os_hideResults(r);
621 // force canvas to stay hidden
622 r.stayHidden = true
623 // cancel any pending fetches
624 if(os_timer != null && os_timer.id != null)
625 clearTimeout(os_timer.id);
626 os_timer = null
627 }
628 }
629
630 /** Event: focus (catch only when stopped) */
631 function os_eventFocus(e){
632 var targ = os_getTarget(e);
633 var r = os_map[targ.id];
634 if(r == null)
635 return; // not our event
636 r.stayHidden = false
637 }
638
639
640
641 /********************
642 * Mouse events
643 ********************/
644
645 /** Mouse over the container */
646 function os_eventMouseover(srcId, e){
647 var targ = os_getTarget(e);
648 var r = os_map[srcId];
649 if(r == null || !os_mouse_moved)
650 return; // not our event
651 var num = os_getNumberSuffix(targ.id);
652 if(num >= 0)
653 os_changeHighlight(r,r.selected,num,false);
654
655 }
656
657 /* Get row where the event occured (from its id) */
658 function os_getNumberSuffix(id){
659 var num = id.substring(id.length-2);
660 if( ! (num.charAt(0) >= '0' && num.charAt(0) <= '9') )
661 num = num.substring(1);
662 if(os_isNumber(num))
663 return parseInt(num);
664 else
665 return -1;
666 }
667
668 /** Save mouse move as last action */
669 function os_eventMousemove(srcId, e){
670 os_mouse_moved = true;
671 }
672
673 /** Mouse button held down, register possible click */
674 function os_eventMousedown(srcId, e){
675 var targ = os_getTarget(e);
676 var r = os_map[srcId];
677 if(r == null)
678 return; // not our event
679 var num = os_getNumberSuffix(targ.id);
680
681 os_mouse_pressed = true;
682 if(num >= 0){
683 os_mouse_num = num;
684 // os_updateSearchQuery(r,r.results[num]);
685 }
686 // keep the focus on the search field
687 document.getElementById(r.searchbox).focus();
688
689 return false; // prevents selection
690 }
691
692 /** Mouse button released, check for click on some row */
693 function os_eventMouseup(srcId, e){
694 var targ = os_getTarget(e);
695 var r = os_map[srcId];
696 if(r == null)
697 return; // not our event
698 var num = os_getNumberSuffix(targ.id);
699
700 if(num >= 0 && os_mouse_num == num){
701 os_updateSearchQuery(r,r.results[num]);
702 os_hideResults(r);
703 document.getElementById(r.searchform).submit();
704 }
705 os_mouse_pressed = false;
706 // keep the focus on the search field
707 document.getElementById(r.searchbox).focus();
708 }
709
710 /** Check if x is a valid integer */
711 function os_isNumber(x){
712 if(x == "" || isNaN(x))
713 return false;
714 for(var i=0;i<x.length;i++){
715 var c = x.charAt(i);
716 if( ! (c >= '0' && c <= '9') )
717 return false;
718 }
719 return true;
720 }
721
722
723 /** When the form is submitted hide everything, cancel updates... */
724 function os_eventOnsubmit(e){
725 var targ = os_getTarget(e);
726
727 os_is_stopped = true;
728 // kill timed requests
729 if(os_timer != null && os_timer.id != null){
730 clearTimeout(os_timer.id);
731 os_timer = null;
732 }
733 // Hide all suggestions
734 for(i=0;i<os_autoload_inputs.length;i++){
735 var r = os_map[os_autoload_inputs[i]];
736 if(r != null){
737 var b = document.getElementById(r.searchform);
738 if(b != null && b == targ){
739 // set query value so the handler won't try to fetch additional results
740 r.query = document.getElementById(r.searchbox).value;
741 }
742 os_hideResults(r);
743 }
744 }
745 return true;
746 }
747
748 function os_hookEvent(element, hookName, hookFunct) {
749 if (element.addEventListener) {
750 element.addEventListener(hookName, hookFunct, false);
751 } else if (window.attachEvent) {
752 element.attachEvent("on" + hookName, hookFunct);
753 }
754 }
755
756 /** Init Result objects and event handlers */
757 function os_initHandlers(name, formname, element){
758 var r = new os_Results(name, formname);
759 // event handler
760 os_hookEvent(element, "keyup", function(event) { os_eventKeyup(event); });
761 os_hookEvent(element, "keydown", function(event) { os_eventKeydown(event); });
762 os_hookEvent(element, "keypress", function(event) { os_eventKeypress(event); });
763 os_hookEvent(element, "blur", function(event) { os_eventBlur(event); });
764 os_hookEvent(element, "focus", function(event) { os_eventFocus(event); });
765 element.setAttribute("autocomplete","off");
766 // stopping handler
767 os_hookEvent(document.getElementById(formname), "submit", function(event){ return os_eventOnsubmit(event); });
768 os_map[name] = r;
769 // toggle link
770 if(document.getElementById(r.toggle) == null){
771 // TODO: disable this while we figure out a way for this to work in all browsers
772 /* if(name=='searchInput'){
773 // special case: place above the main search box
774 var t = os_createToggle(r,"os-suggest-toggle");
775 var searchBody = document.getElementById('searchBody');
776 var first = searchBody.parentNode.firstChild.nextSibling.appendChild(t);
777 } else{
778 // default: place below search box to the right
779 var t = os_createToggle(r,"os-suggest-toggle-def");
780 var top = element.offsetTop + element.offsetHeight;
781 var left = element.offsetLeft + element.offsetWidth;
782 t.style.position = "absolute";
783 t.style.top = top + "px";
784 t.style.left = left + "px";
785 element.parentNode.appendChild(t);
786 // only now width gets calculated, shift right
787 left -= t.offsetWidth;
788 t.style.left = left + "px";
789 t.style.visibility = "visible";
790 } */
791 }
792
793 }
794
795 /** Return the span element that contains the toggle link */
796 function os_createToggle(r,className){
797 var t = document.createElement("span");
798 t.className = className;
799 t.setAttribute("id", r.toggle);
800 var link = document.createElement("a");
801 link.setAttribute("href","javascript:void(0);");
802 link.onclick = function(){ os_toggle(r.searchbox,r.searchform) };
803 var msg = document.createTextNode(wgMWSuggestMessages[0]);
804 link.appendChild(msg);
805 t.appendChild(link);
806 return t;
807 }
808
809 /** Call when user clicks on some of the toggle links */
810 function os_toggle(inputId,formName){
811 r = os_map[inputId];
812 var msg = '';
813 if(r == null){
814 os_enableSuggestionsOn(inputId,formName);
815 r = os_map[inputId];
816 msg = wgMWSuggestMessages[0];
817 } else{
818 os_disableSuggestionsOn(inputId,formName);
819 msg = wgMWSuggestMessages[1];
820 }
821 // change message
822 var link = document.getElementById(r.toggle).firstChild;
823 link.replaceChild(document.createTextNode(msg),link.firstChild);
824 }
825
826 /** Call this to enable suggestions on input (id=inputId), on a form (name=formName) */
827 function os_enableSuggestionsOn(inputId, formName){
828 os_initHandlers( inputId, formName, document.getElementById(inputId) );
829 }
830
831 /** Call this to disable suggestios on input box (id=inputId) */
832 function os_disableSuggestionsOn(inputId){
833 r = os_map[inputId];
834 if(r != null){
835 // cancel/hide results
836 os_timer = null;
837 os_hideResults(r);
838 // turn autocomplete on !
839 document.getElementById(inputId).setAttribute("autocomplete","on");
840 // remove descriptor
841 os_map[inputId] = null;
842 }
843 }
844
845 /** Initialization, call upon page onload */
846 function os_MWSuggestInit() {
847 for(i=0;i<os_autoload_inputs.length;i++){
848 var id = os_autoload_inputs[i];
849 var form = os_autoload_forms[i];
850 element = document.getElementById( id );
851 if(element != null)
852 os_initHandlers(id,form,element);
853 }
854 }
855
856 hookEvent("load", os_MWSuggestInit);