]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - skins/common/mwsuggest.js
MediaWiki 1.14.0
[autoinstalls/mediawiki.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 normW = document.getElementById(r.searchbox).offsetWidth;
306         var normL = os_getElementPosition(r.searchbox).left;
307         var inc = os_animation_timer.inc;
308         var target = os_animation_timer.target;
309         var nw = w + inc;
310         if( (inc > 0 && nw >= target) || (inc <= 0 && nw <= target) ){
311                 // finished !
312                 c.style.width = target+"px";
313                 clearInterval(os_animation_timer.id)
314                 os_animation_timer = null;
315         } else{
316                 // in-progress
317                 c.style.width = nw+"px";
318                 if(document.documentElement.dir == "rtl")
319                         c.style.left = (normL + normW + (target - nw) - os_animation_timer.target - 1)+"px";
320         }
321 }
322
323 /** Handles data from XMLHttpRequest, and updates the suggest results */
324 function os_updateResults(r, query, text, cacheKey){
325         os_cache[cacheKey] = text;
326         r.query = query;
327         r.original = query;
328         if(text == ""){
329                 r.results = null;
330                 r.resultCount = 0;
331                 os_hideResults(r);
332         } else{
333                 try {
334                         var p = eval('('+text+')'); // simple json parse, could do a safer one
335                         if(p.length<2 || p[1].length == 0){
336                                 r.results = null;
337                                 r.resultCount = 0;
338                                 os_hideResults(r);
339                                 return;
340                         }
341                         var c = document.getElementById(r.container);
342                         if(c == null)
343                                 c = os_createContainer(r);
344                         c.innerHTML = os_createResultTable(r,p[1]);
345                         // init container table sizes
346                         var t = document.getElementById(r.resultTable);
347                         r.containerTotal = t.offsetHeight;
348                         r.containerRow = t.offsetHeight / r.resultCount;
349                         os_fitContainer(r);
350                         os_trimResultText(r);
351                         os_showResults(r);
352                 } catch(e){
353                         // bad response from server or such
354                         os_hideResults(r);
355                         os_cache[cacheKey] = null;
356                 }
357         }
358 }
359
360 /** Create the result table to be placed in the container div */
361 function os_createResultTable(r, results){
362         var c = document.getElementById(r.container);
363         var width = c.offsetWidth - os_operaWidthFix(c.offsetWidth);
364         var html = "<table class=\"os-suggest-results\" id=\""+r.resultTable+"\" style=\"width: "+width+"px;\">";
365         r.results = new Array();
366         r.resultCount = results.length;
367         for(i=0;i<results.length;i++){
368                 var title = os_decodeValue(results[i]);
369                 r.results[i] = title;
370                 html += "<tr><td class=\"os-suggest-result\" id=\""+r.resultTable+i+"\"><span id=\""+r.resultText+i+"\">"+title+"</span></td></tr>";
371         }
372         html+="</table>"
373         return html;
374 }
375
376 /** Fetch namespaces from checkboxes or hidden fields in the search form,
377     if none defined use wgSearchNamespaces global */
378 function os_getNamespaces(r){
379         var namespaces = "";
380         var elements = document.forms[r.searchform].elements;
381         for(i=0; i < elements.length; i++){
382                 var name = elements[i].name;
383                 if(typeof name != 'undefined' && name.length > 2
384                 && name[0]=='n' && name[1]=='s'
385                 && ((elements[i].type=='checkbox' && elements[i].checked)
386                         || (elements[i].type=='hidden' && elements[i].value=="1")) ){
387                         if(namespaces!="")
388                                 namespaces+="|";
389                         namespaces+=name.substring(2);
390                 }
391         }
392         if(namespaces == "")
393                 namespaces = wgSearchNamespaces.join("|");
394         return namespaces;
395 }
396
397 /** Update results if user hasn't already typed something else */
398 function os_updateIfRelevant(r, query, text, cacheKey){
399         var t = document.getElementById(r.searchbox);
400         if(t != null && t.value == query){ // check if response is still relevant
401                 os_updateResults(r, query, text, cacheKey);
402         }
403         r.query = query;
404 }
405
406 /** Fetch results after some timeout */
407 function os_delayedFetch(){
408         if(os_timer == null)
409                 return;
410         var r = os_timer.r;
411         var query = os_timer.query;
412         os_timer = null;
413         var path = wgMWSuggestTemplate.replace("{namespaces}",os_getNamespaces(r))
414                                                                   .replace("{dbname}",wgDBname)
415                                                                   .replace("{searchTerms}",os_encodeQuery(query));
416
417         // try to get from cache, if not fetch using ajax
418         var cached = os_cache[path];
419         if(cached != null){
420                 os_updateIfRelevant(r, query, cached, path);
421         } else{
422                 var xmlhttp = sajax_init_object();
423                 if(xmlhttp){
424                         try {
425                                 xmlhttp.open("GET", path, true);
426                                 xmlhttp.onreadystatechange=function(){
427                                 if (xmlhttp.readyState==4 && typeof os_updateIfRelevant == 'function') {
428                                         os_updateIfRelevant(r, query, xmlhttp.responseText, path);
429                                 }
430                         };
431                         xmlhttp.send(null);
432                 } catch (e) {
433                                 if (window.location.hostname == "localhost") {
434                                         alert("Your browser blocks XMLHttpRequest to 'localhost', try using a real hostname for development/testing.");
435                                 }
436                                 throw e;
437                         }
438                 }
439         }
440 }
441
442 /** Init timed update via os_delayedUpdate() */
443 function os_fetchResults(r, query, timeout){
444         if(query == ""){
445                 os_hideResults(r);
446                 return;
447         } else if(query == r.query)
448                 return; // no change
449
450         os_is_stopped = false; // make sure we're running
451
452         /* var cacheKey = wgDBname+":"+query;
453         var cached = os_cache[cacheKey];
454         if(cached != null){
455                 os_updateResults(r,wgDBname,query,cached);
456                 return;
457         } */
458
459         // cancel any pending fetches
460         if(os_timer != null && os_timer.id != null)
461                 clearTimeout(os_timer.id);
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 /** Change the highlighted row (i.e. suggestion), from position cur to next */
472 function os_changeHighlight(r, cur, next, updateSearchBox){
473         if (next >= r.resultCount)
474                 next = r.resultCount-1;
475         if (next < -1)
476                 next = -1;
477         r.selected = next;
478         if (cur == next)
479         return; // nothing to do.
480
481     if(cur >= 0){
482         var curRow = document.getElementById(r.resultTable + cur);
483         if(curRow != null)
484                 curRow.className = "os-suggest-result";
485     }
486     var newText;
487     if(next >= 0){
488         var nextRow = document.getElementById(r.resultTable + next);
489         if(nextRow != null)
490                 nextRow.className = os_HighlightClass();
491         newText = r.results[next];
492     } else
493         newText = r.original;
494
495     // adjust the scrollbar if any
496     if(r.containerCount < r.resultCount){
497         var c = document.getElementById(r.container);
498         var vStart = c.scrollTop / r.containerRow;
499         var vEnd = vStart + r.containerCount;
500         if(next < vStart)
501                 c.scrollTop = next * r.containerRow;
502         else if(next >= vEnd)
503                 c.scrollTop = (next - r.containerCount + 1) * r.containerRow;
504     }
505
506     // update the contents of the search box
507     if(updateSearchBox){
508         os_updateSearchQuery(r,newText);
509     }
510 }
511
512 function os_HighlightClass() {
513         var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
514         if (match) {
515                 var webKitVersion = parseInt(match[1]);
516                 if (webKitVersion < 523) {
517                         // CSS system highlight colors broken on old Safari
518                         // https://bugs.webkit.org/show_bug.cgi?id=6129
519                         // Safari 3.0.4, 3.1 known ok
520                         return "os-suggest-result-hl-webkit";
521                 }
522         }
523         return "os-suggest-result-hl";
524 }
525
526 function os_updateSearchQuery(r,newText){
527         document.getElementById(r.searchbox).value = newText;
528     r.query = newText;
529 }
530
531 /** Find event target */
532 function os_getTarget(e){
533         if (!e) e = window.event;
534         if (e.target) return e.target;
535         else if (e.srcElement) return e.srcElement;
536         else return null;
537 }
538
539
540
541 /********************
542  *  Keyboard events
543  ********************/
544
545 /** Event handler that will fetch results on keyup */
546 function os_eventKeyup(e){
547         var targ = os_getTarget(e);
548         var r = os_map[targ.id];
549         if(r == null)
550                 return; // not our event
551
552         // some browsers won't generate keypressed for arrow keys, catch it
553         if(os_keypressed_count == 0){
554                 os_processKey(r,os_cur_keypressed,targ);
555         }
556         var query = targ.value;
557         os_fetchResults(r,query,os_search_timeout);
558 }
559
560 /** catch arrows up/down and escape to hide the suggestions */
561 function os_processKey(r,keypressed,targ){
562         if (keypressed == 40){ // Arrow Down
563         if (r.visible) {
564                 os_changeHighlight(r, r.selected, r.selected+1, true);
565         } else if(os_timer == null){
566                 // user wants to get suggestions now
567                 r.query = "";
568                         os_fetchResults(r,targ.value,0);
569         }
570         } else if (keypressed == 38){ // Arrow Up
571                 if (r.visible){
572                         os_changeHighlight(r, r.selected, r.selected-1, true);
573                 }
574         } else if(keypressed == 27){ // Escape
575                 document.getElementById(r.searchbox).value = r.original;
576                 r.query = r.original;
577                 os_hideResults(r);
578         } else if(r.query != document.getElementById(r.searchbox).value){
579                 // os_hideResults(r); // don't show old suggestions
580         }
581 }
582
583 /** When keys is held down use a timer to output regular events */
584 function os_eventKeypress(e){
585         var targ = os_getTarget(e);
586         var r = os_map[targ.id];
587         if(r == null)
588                 return; // not our event
589
590         var keypressed = os_cur_keypressed;
591         if(keypressed == 38 || keypressed == 40){
592                 var d = new Date()
593                 var now = d.getTime();
594                 if(now - os_last_keypress < 120){
595                         os_last_keypress = now;
596                         return;
597                 }
598         }
599
600         os_keypressed_count++;
601         os_processKey(r,keypressed,targ);
602 }
603
604 /** Catch the key code (Firefox bug)  */
605 function os_eventKeydown(e){
606         if (!e) e = window.event;
607         var targ = os_getTarget(e);
608         var r = os_map[targ.id];
609         if(r == null)
610                 return; // not our event
611
612         os_mouse_moved = false;
613
614         os_cur_keypressed = (e.keyCode == undefined) ? e.which : e.keyCode;
615         os_last_keypress = 0;
616         os_keypressed_count = 0;
617 }
618
619 /** Event: loss of focus of input box */
620 function os_eventBlur(e){
621         var targ = os_getTarget(e);
622         var r = os_map[targ.id];
623         if(r == null)
624                 return; // not our event
625         if(!os_mouse_pressed)
626                 os_hideResults(r);
627 }
628
629 /** Event: focus (catch only when stopped) */
630 function os_eventFocus(e){
631         // nothing happens here?
632 }
633
634
635
636 /********************
637  *  Mouse events
638  ********************/
639
640 /** Mouse over the container */
641 function os_eventMouseover(srcId, e){
642         var targ = os_getTarget(e);
643         var r = os_map[srcId];
644         if(r == null || !os_mouse_moved)
645                 return; // not our event
646         var num = os_getNumberSuffix(targ.id);
647         if(num >= 0)
648                 os_changeHighlight(r,r.selected,num,false);
649
650 }
651
652 /* Get row where the event occured (from its id) */
653 function os_getNumberSuffix(id){
654         var num = id.substring(id.length-2);
655         if( ! (num.charAt(0) >= '0' && num.charAt(0) <= '9') )
656                 num = num.substring(1);
657         if(os_isNumber(num))
658                 return parseInt(num);
659         else
660                 return -1;
661 }
662
663 /** Save mouse move as last action */
664 function os_eventMousemove(srcId, e){
665         os_mouse_moved = true;
666 }
667
668 /** Mouse button held down, register possible click  */
669 function os_eventMousedown(srcId, e){
670         var targ = os_getTarget(e);
671         var r = os_map[srcId];
672         if(r == null)
673                 return; // not our event
674         var num = os_getNumberSuffix(targ.id);
675
676         os_mouse_pressed = true;
677         if(num >= 0){
678                 os_mouse_num = num;
679                 // os_updateSearchQuery(r,r.results[num]);
680         }
681         // keep the focus on the search field
682         document.getElementById(r.searchbox).focus();
683
684         return false; // prevents selection
685 }
686
687 /** Mouse button released, check for click on some row */
688 function os_eventMouseup(srcId, e){
689         var targ = os_getTarget(e);
690         var r = os_map[srcId];
691         if(r == null)
692                 return; // not our event
693         var num = os_getNumberSuffix(targ.id);
694
695         if(num >= 0 && os_mouse_num == num){
696                 os_updateSearchQuery(r,r.results[num]);
697                 os_hideResults(r);
698                 document.getElementById(r.searchform).submit();
699         }
700         os_mouse_pressed = false;
701         // keep the focus on the search field
702         document.getElementById(r.searchbox).focus();
703 }
704
705 /** Check if x is a valid integer */
706 function os_isNumber(x){
707         if(x == "" || isNaN(x))
708                 return false;
709         for(var i=0;i<x.length;i++){
710                 var c = x.charAt(i);
711                 if( ! (c >= '0' && c <= '9') )
712                         return false;
713         }
714         return true;
715 }
716
717
718 /** When the form is submitted hide everything, cancel updates... */
719 function os_eventOnsubmit(e){
720         var targ = os_getTarget(e);
721
722         os_is_stopped = true;
723         // kill timed requests
724         if(os_timer != null && os_timer.id != null){
725                 clearTimeout(os_timer.id);
726                 os_timer = null;
727         }
728         // Hide all suggestions
729         for(i=0;i<os_autoload_inputs.length;i++){
730                 var r = os_map[os_autoload_inputs[i]];
731                 if(r != null){
732                         var b = document.getElementById(r.searchform);
733                         if(b != null && b == targ){
734                                 // set query value so the handler won't try to fetch additional results
735                                 r.query = document.getElementById(r.searchbox).value;
736                         }
737                         os_hideResults(r);
738                 }
739         }
740         return true;
741 }
742
743 function os_hookEvent(element, hookName, hookFunct) {
744         if (element.addEventListener) {
745                 element.addEventListener(hookName, hookFunct, false);
746         } else if (window.attachEvent) {
747                 element.attachEvent("on" + hookName, hookFunct);
748         }
749 }
750
751 /** Init Result objects and event handlers */
752 function os_initHandlers(name, formname, element){
753         var r = new os_Results(name, formname);
754         // event handler
755         os_hookEvent(element, "keyup", function(event) { os_eventKeyup(event); });
756         os_hookEvent(element, "keydown", function(event) { os_eventKeydown(event); });
757         os_hookEvent(element, "keypress", function(event) { os_eventKeypress(event); });
758         os_hookEvent(element, "blur", function(event) { os_eventBlur(event); });
759         os_hookEvent(element, "focus", function(event) { os_eventFocus(event); });
760         element.setAttribute("autocomplete","off");
761         // stopping handler
762         os_hookEvent(document.getElementById(formname), "submit", function(event){ return os_eventOnsubmit(event); });
763         os_map[name] = r;
764         // toggle link
765         if(document.getElementById(r.toggle) == null){
766                 // TODO: disable this while we figure out a way for this to work in all browsers
767                 /* if(name=='searchInput'){
768                         // special case: place above the main search box
769                         var t = os_createToggle(r,"os-suggest-toggle");
770                         var searchBody = document.getElementById('searchBody');
771                         var first = searchBody.parentNode.firstChild.nextSibling.appendChild(t);
772                 } else{
773                         // default: place below search box to the right
774                         var t = os_createToggle(r,"os-suggest-toggle-def");
775                         var top = element.offsetTop + element.offsetHeight;
776                         var left = element.offsetLeft + element.offsetWidth;
777                         t.style.position = "absolute";
778                         t.style.top = top + "px";
779                         t.style.left = left + "px";
780                         element.parentNode.appendChild(t);
781                         // only now width gets calculated, shift right
782                         left -= t.offsetWidth;
783                         t.style.left = left + "px";
784                         t.style.visibility = "visible";
785                 } */
786         }
787
788 }
789
790 /** Return the span element that contains the toggle link */
791 function os_createToggle(r,className){
792         var t = document.createElement("span");
793         t.className = className;
794         t.setAttribute("id", r.toggle);
795         var link = document.createElement("a");
796         link.setAttribute("href","javascript:void(0);");
797         link.onclick = function(){ os_toggle(r.searchbox,r.searchform) };
798         var msg = document.createTextNode(wgMWSuggestMessages[0]);
799         link.appendChild(msg);
800         t.appendChild(link);
801         return t;
802 }
803
804 /** Call when user clicks on some of the toggle links */
805 function os_toggle(inputId,formName){
806         r = os_map[inputId];
807         var msg = '';
808         if(r == null){
809                 os_enableSuggestionsOn(inputId,formName);
810                 r = os_map[inputId];
811                 msg = wgMWSuggestMessages[0];
812         } else{
813                 os_disableSuggestionsOn(inputId,formName);
814                 msg = wgMWSuggestMessages[1];
815         }
816         // change message
817         var link = document.getElementById(r.toggle).firstChild;
818         link.replaceChild(document.createTextNode(msg),link.firstChild);
819 }
820
821 /** Call this to enable suggestions on input (id=inputId), on a form (name=formName) */
822 function os_enableSuggestionsOn(inputId, formName){
823         os_initHandlers( inputId, formName, document.getElementById(inputId) );
824 }
825
826 /** Call this to disable suggestios on input box (id=inputId) */
827 function os_disableSuggestionsOn(inputId){
828         r = os_map[inputId];
829         if(r != null){
830                 // cancel/hide results
831                 os_timer = null;
832                 os_hideResults(r);
833                 // turn autocomplete on !
834                 document.getElementById(inputId).setAttribute("autocomplete","on");
835                 // remove descriptor
836                 os_map[inputId] = null;
837         }
838 }
839
840 /** Initialization, call upon page onload */
841 function os_MWSuggestInit() {
842         for(i=0;i<os_autoload_inputs.length;i++){
843                 var id = os_autoload_inputs[i];
844                 var form = os_autoload_forms[i];
845                 element = document.getElementById( id );
846                 if(element != null)
847                         os_initHandlers(id,form,element);
848         }
849 }
850
851 hookEvent("load", os_MWSuggestInit);