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