* (bug 30497) Add client-nojs and client-js classes on document element to let styles...
[lhc/web/wiklou.git] / resources / mediawiki.page / mediawiki.page.mwsuggest.js
1 jQuery( document ).ready( function( $ ) {
2 var $container = $( '<div>', { 'class' : 'open-search-suggestions' } ),
3 cache = {},
4 $suggestionList,
5 url = mw.util.wikiScript( 'api' ),
6 maxRowWindow;
7
8 //Append the container which will hold the menu to the body
9 $( 'body' ).append( $container );
10
11 /* Grabs namespaces from search form or
12 * in case we're not on a search page, take it from wgSearchNamespaces.
13 * @return Array: List of Namespaces that should be searched
14 */
15 var getNamespaces = function() {
16 var namespaces = [];
17 $( 'form#powersearch, form#search' ).find( '[name^="ns"]' ).each(function() {
18 if ( this.checked || ( this.type == 'hidden' && this.value == '1' ) ) {
19 namespaces.push( this.name.substring( 2 ) );
20 }
21 });
22 if ( !namespaces.length ) {
23 namespaces = mw.config.get( 'wgSearchNamespaces' );
24 }
25 return namespaces.join('|');
26 };
27
28 /* Helper function to make sure that the list doesn't expand below the visible part of the window */
29 var deliverResult = function( obj, response ) {
30 if ( obj && obj.length > 1 ) {
31 response( obj[1] );
32 // Get the lowest from multiple numbers using fn.apply
33 var maxRow = Math.min.apply( Math, [7, obj[1].length, maxRowWindow] );
34 $suggestionList.css( 'height', maxRow * $suggestionList.find( '.ui-menu-item' ).eq( 0 ).height() );
35 } else {
36 response( [] );
37 }
38 };
39
40 /* The actual autocomplete setup */
41 $( "#searchInput" ).autocomplete({
42 minLength: 2,
43 source: function ( request, response ) {
44 var namespaces = getNamespaces();
45 // We're caching queries for performance
46 var term = request.term + namespaces;
47 if ( term in cache ) {
48 deliverResult( cache[term], response );
49 return;
50 }
51 var params = {
52 format : 'json',
53 action : 'opensearch',
54 search : request.term,
55 namespace : namespaces
56 };
57 $.getJSON( url, params, function ( obj ) {
58 // Save to cache
59 cache[ term ] = obj;
60 deliverResult( obj, response );
61 });
62 },
63 select : function() {
64 $( '#searchGoButton' ).click();
65 },
66 create : function() {
67 $suggestionList = $container.find( 'ul' );
68 },
69 appendTo : '.open-search-suggestions',
70 open : function() {
71 maxRowWindow = Math.floor(
72 ( $( window ).height() - $suggestionList.offset().top + $( window ).scrollTop() ) /
73 $suggestionList.find( '.ui-menu-item' ).eq( 0 ).height()
74 );
75 }
76 });
77
78 /* Legacy teardown, called when things like SimpleSearch need to disable MWSuggest */
79 window.os_MWSuggestDisable = function() {
80 return $("#searchInput").autocomplete( "destroy" );
81 };
82 });