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