docs.js revision 4f7e5159409e71ecfeba86858f5ec044d043aff8
1var classesNav;
2var devdocNav;
3var sidenav;
4var cookie_namespace = 'android_developer';
5var NAV_PREF_TREE = "tree";
6var NAV_PREF_PANELS = "panels";
7var nav_pref;
8var isMobile = false; // true if mobile, so we can adjust some layout
9var mPagePath; // initialized in ready() function
10
11var basePath = getBaseUri(location.pathname);
12var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
13var GOOGLE_DATA; // combined data for google service apis, used for search suggest
14
15// Ensure that all ajax getScript() requests allow caching
16$.ajaxSetup({
17  cache: true
18});
19
20/******  ON LOAD SET UP STUFF *********/
21
22var navBarIsFixed = false;
23$(document).ready(function() {
24
25  // load json file for JD doc search suggestions
26  $.getScript(toRoot + 'reference/jd_lists.js');
27  // load json file for Android API search suggestions
28  $.getScript(toRoot + 'reference/lists.js');
29  // load json files for Google services API suggestions
30  $.getScript(toRoot + 'reference/gcm_lists.js', function(data, textStatus, jqxhr) {
31      // once the GCM json (GCM_DATA) is loaded, load the GMS json (GMS_DATA) and merge the data
32      if(jqxhr.status === 200) {
33          $.getScript(toRoot + 'reference/gms_lists.js', function(data, textStatus, jqxhr) {
34              if(jqxhr.status === 200) {
35                  // combine GCM and GMS data
36                  GOOGLE_DATA = GMS_DATA;
37                  var start = GOOGLE_DATA.length;
38                  for (var i=0; i<GCM_DATA.length; i++) {
39                      GOOGLE_DATA.push({id:start+i, label:GCM_DATA[i].label,
40                              link:GCM_DATA[i].link, type:GCM_DATA[i].type});
41                  }
42              }
43          });
44      }
45  });
46
47  // setup keyboard listener for search shortcut
48  $('body').keyup(function(event) {
49    if (event.which == 191) {
50      $('#search_autocomplete').focus();
51    }
52  });
53
54  // init the fullscreen toggle click event
55  $('#nav-swap .fullscreen').click(function(){
56    if ($(this).hasClass('disabled')) {
57      toggleFullscreen(true);
58    } else {
59      toggleFullscreen(false);
60    }
61  });
62
63  // initialize the divs with custom scrollbars
64  $('.scroll-pane').jScrollPane( {verticalGutter:0} );
65
66  // add HRs below all H2s (except for a few other h2 variants)
67  $('h2').not('#qv h2').not('#tb h2').not('.sidebox h2').not('#devdoc-nav h2').not('h2.norule').css({marginBottom:0}).after('<hr/>');
68
69  // set up the search close button
70  $('.search .close').click(function() {
71    $searchInput = $('#search_autocomplete');
72    $searchInput.attr('value', '');
73    $(this).addClass("hide");
74    $("#search-container").removeClass('active');
75    $("#search_autocomplete").blur();
76    search_focus_changed($searchInput.get(), false);
77    hideResults();
78  });
79
80  // Set up quicknav
81  var quicknav_open = false;
82  $("#btn-quicknav").click(function() {
83    if (quicknav_open) {
84      $(this).removeClass('active');
85      quicknav_open = false;
86      collapse();
87    } else {
88      $(this).addClass('active');
89      quicknav_open = true;
90      expand();
91    }
92  })
93
94  var expand = function() {
95   $('#header-wrap').addClass('quicknav');
96   $('#quicknav').stop().show().animate({opacity:'1'});
97  }
98
99  var collapse = function() {
100    $('#quicknav').stop().animate({opacity:'0'}, 100, function() {
101      $(this).hide();
102      $('#header-wrap').removeClass('quicknav');
103    });
104  }
105
106
107  //Set up search
108  $("#search_autocomplete").focus(function() {
109    $("#search-container").addClass('active');
110  })
111  $("#search-container").mouseover(function() {
112    $("#search-container").addClass('active');
113    $("#search_autocomplete").focus();
114  })
115  $("#search-container").mouseout(function() {
116    if ($("#search_autocomplete").is(":focus")) return;
117    if ($("#search_autocomplete").val() == '') {
118      setTimeout(function(){
119        $("#search-container").removeClass('active');
120        $("#search_autocomplete").blur();
121      },250);
122    }
123  })
124  $("#search_autocomplete").blur(function() {
125    if ($("#search_autocomplete").val() == '') {
126      $("#search-container").removeClass('active');
127    }
128  })
129
130
131  // prep nav expandos
132  var pagePath = document.location.pathname;
133  // account for intl docs by removing the intl/*/ path
134  if (pagePath.indexOf("/intl/") == 0) {
135    pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last /
136  }
137
138  if (pagePath.indexOf(SITE_ROOT) == 0) {
139    if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
140      pagePath += 'index.html';
141    }
142  }
143
144  // Need a copy of the pagePath before it gets changed in the next block;
145  // it's needed to perform proper tab highlighting in offline docs (see rootDir below)
146  var pagePathOriginal = pagePath;
147  if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
148    // If running locally, SITE_ROOT will be a relative path, so account for that by
149    // finding the relative URL to this page. This will allow us to find links on the page
150    // leading back to this page.
151    var pathParts = pagePath.split('/');
152    var relativePagePathParts = [];
153    var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
154    for (var i = 0; i < upDirs; i++) {
155      relativePagePathParts.push('..');
156    }
157    for (var i = 0; i < upDirs; i++) {
158      relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
159    }
160    relativePagePathParts.push(pathParts[pathParts.length - 1]);
161    pagePath = relativePagePathParts.join('/');
162  } else {
163    // Otherwise the page path is already an absolute URL
164  }
165
166  // Highlight the header tabs...
167  // highlight Design tab
168  if ($("body").hasClass("design")) {
169    $("#header li.design a").addClass("selected");
170
171  // highlight Develop tab
172  } else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
173    $("#header li.develop a").addClass("selected");
174    // In Develop docs, also highlight appropriate sub-tab
175    var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
176    if (rootDir == "training") {
177      $("#nav-x li.training a").addClass("selected");
178    } else if (rootDir == "guide") {
179      $("#nav-x li.guide a").addClass("selected");
180    } else if (rootDir == "reference") {
181      // If the root is reference, but page is also part of Google Services, select Google
182      if ($("body").hasClass("google")) {
183        $("#nav-x li.google a").addClass("selected");
184      } else {
185        $("#nav-x li.reference a").addClass("selected");
186      }
187    } else if ((rootDir == "tools") || (rootDir == "sdk")) {
188      $("#nav-x li.tools a").addClass("selected");
189    } else if ($("body").hasClass("google")) {
190      $("#nav-x li.google a").addClass("selected");
191    } else if ($("body").hasClass("samples")) {
192      $("#nav-x li.samples a").addClass("selected");
193    }
194
195  // highlight Distribute tab
196  } else if ($("body").hasClass("distribute")) {
197    $("#header li.distribute a").addClass("selected");
198  }
199
200  // set global variable so we can highlight the sidenav a bit later (such as for google reference)
201  // and highlight the sidenav
202  mPagePath = pagePath;
203  highlightSidenav();
204
205  // set up prev/next links if they exist
206  var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
207  var $selListItem;
208  if ($selNavLink.length) {
209    $selListItem = $selNavLink.closest('li');
210
211    // set up prev links
212    var $prevLink = [];
213    var $prevListItem = $selListItem.prev('li');
214
215    var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
216false; // navigate across topic boundaries only in design docs
217    if ($prevListItem.length) {
218      if ($prevListItem.hasClass('nav-section')) {
219        // jump to last topic of previous section
220        $prevLink = $prevListItem.find('a:last');
221      } else if (!$selListItem.hasClass('nav-section')) {
222        // jump to previous topic in this section
223        $prevLink = $prevListItem.find('a:eq(0)');
224      }
225    } else {
226      // jump to this section's index page (if it exists)
227      var $parentListItem = $selListItem.parents('li');
228      $prevLink = $selListItem.parents('li').find('a');
229
230      // except if cross boundaries aren't allowed, and we're at the top of a section already
231      // (and there's another parent)
232      if (!crossBoundaries && $parentListItem.hasClass('nav-section')
233                           && $selListItem.hasClass('nav-section')) {
234        $prevLink = [];
235      }
236    }
237
238    // set up next links
239    var $nextLink = [];
240    var startClass = false;
241    var training = $(".next-class-link").length; // decides whether to provide "next class" link
242    var isCrossingBoundary = false;
243
244    if ($selListItem.hasClass('nav-section')) {
245      // we're on an index page, jump to the first topic
246      $nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
247
248      // if there aren't any children, go to the next section (required for About pages)
249      if($nextLink.length == 0) {
250        $nextLink = $selListItem.next('li').find('a');
251      } else if ($('.topic-start-link').length) {
252        // as long as there's a child link and there is a "topic start link" (we're on a landing)
253        // then set the landing page "start link" text to be the first doc title
254        $('.topic-start-link').text($nextLink.text().toUpperCase());
255      }
256
257      // If the selected page has a description, then it's a class or article homepage
258      if ($selListItem.find('a[description]').length) {
259        // this means we're on a class landing page
260        startClass = true;
261      }
262    } else {
263      // jump to the next topic in this section (if it exists)
264      $nextLink = $selListItem.next('li').find('a:eq(0)');
265      if (!$nextLink.length) {
266        isCrossingBoundary = true;
267        // no more topics in this section, jump to the first topic in the next section
268        $nextLink = $selListItem.parents('li:eq(0)').next('li.nav-section').find('a:eq(0)');
269        if (!$nextLink.length) {  // Go up another layer to look for next page (lesson > class > course)
270          $nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
271        }
272      }
273    }
274
275    if (startClass) {
276      $('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
277
278      // if there's no training bar (below the start button),
279      // then we need to add a bottom border to button
280      if (!$("#tb").length) {
281        $('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
282      }
283    } else if (isCrossingBoundary && !$('body.design').length) {  // Design always crosses boundaries
284      $('.content-footer.next-class').show();
285      $('.next-page-link').attr('href','')
286                          .removeClass("hide").addClass("disabled")
287                          .click(function() { return false; });
288
289      $('.next-class-link').attr('href',$nextLink.attr('href'))
290                          .removeClass("hide").append($nextLink.html());
291      $('.next-class-link').find('.new').empty();
292    } else {
293      $('.next-page-link').attr('href', $nextLink.attr('href')).removeClass("hide");
294    }
295
296    if (!startClass && $prevLink.length) {
297      var prevHref = $prevLink.attr('href');
298      if (prevHref == SITE_ROOT + 'index.html') {
299        // Don't show Previous when it leads to the homepage
300      } else {
301        $('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide");
302      }
303    }
304
305    // If this is a training 'article', there should be no prev/next nav
306    // ... if the grandparent is the "nav" ... and it has no child list items...
307    if (training && $selListItem.parents('ul').eq(1).is('[id="nav"]') &&
308        !$selListItem.find('li').length) {
309      $('.next-page-link,.prev-page-link').attr('href','').addClass("disabled")
310                          .click(function() { return false; });
311    }
312
313  }
314
315
316
317  // Set up the course landing pages for Training with class names and descriptions
318  if ($('body.trainingcourse').length) {
319    var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
320    var $classDescriptions = $classLinks.attr('description');
321
322    var $olClasses  = $('<ol class="class-list"></ol>');
323    var $liClass;
324    var $imgIcon;
325    var $h2Title;
326    var $pSummary;
327    var $olLessons;
328    var $liLesson;
329    $classLinks.each(function(index) {
330      $liClass  = $('<li></li>');
331      $h2Title  = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
332      $pSummary = $('<p class="description">' + $(this).attr('description') + '</p>');
333
334      $olLessons  = $('<ol class="lesson-list"></ol>');
335
336      $lessons = $(this).closest('li').find('ul li a');
337
338      if ($lessons.length) {
339        $imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" '
340            + ' width="64" height="64" alt=""/>');
341        $lessons.each(function(index) {
342          $olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
343        });
344      } else {
345        $imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" '
346            + ' width="64" height="64" alt=""/>');
347        $pSummary.addClass('article');
348      }
349
350      $liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons);
351      $olClasses.append($liClass);
352    });
353    $('.jd-descr').append($olClasses);
354  }
355
356
357
358
359  // Set up expand/collapse behavior
360  $('#nav li.nav-section .nav-section-header').click(function() {
361    var section = $(this).closest('li.nav-section');
362    if (section.hasClass('expanded')) {
363    /* hide me */
364    //  if (section.hasClass('selected') || section.find('li').hasClass('selected')) {
365   //   /* but not if myself or my descendents are selected */
366   //     return;
367    //  }
368      section.children('ul').slideUp(250, function() {
369        section.closest('li').removeClass('expanded');
370        resizeNav();
371      });
372    } else {
373    /* show me */
374      // first hide all other siblings
375      var $others = $('li.nav-section.expanded', $(this).closest('ul'));
376      $others.removeClass('expanded').children('ul').slideUp(250);
377
378      // now expand me
379      section.closest('li').addClass('expanded');
380      section.children('ul').slideDown(250, function() {
381        resizeNav();
382      });
383    }
384  });
385
386  $(".scroll-pane").scroll(function(event) {
387      event.preventDefault();
388      return false;
389  });
390
391  /* Resize nav height when window height changes */
392  $(window).resize(function() {
393    if ($('#side-nav').length == 0) return;
394    var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
395    setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
396    // make sidenav behave when resizing the window and side-scolling is a concern
397    if (navBarIsFixed) {
398      if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
399        updateSideNavPosition();
400      } else {
401        updateSidenavFullscreenWidth();
402      }
403    }
404    resizeNav();
405  });
406
407
408  // Set up fixed navbar
409  var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
410  $(window).scroll(function(event) {
411    if ($('#side-nav').length == 0) return;
412    if (event.target.nodeName == "DIV") {
413      // Dump scroll event if the target is a DIV, because that means the event is coming
414      // from a scrollable div and so there's no need to make adjustments to our layout
415      return;
416    }
417    var scrollTop = $(window).scrollTop();
418    var headerHeight = $('#header').outerHeight();
419    var subheaderHeight = $('#nav-x').outerHeight();
420    var searchResultHeight = $('#searchResults').is(":visible") ?
421                             $('#searchResults').outerHeight() : 0;
422    var totalHeaderHeight = headerHeight + subheaderHeight + searchResultHeight;
423    // we set the navbar fixed when the scroll position is beyond the height of the site header...
424    var navBarShouldBeFixed = scrollTop > totalHeaderHeight;
425    // ... except if the document content is shorter than the sidenav height.
426    // (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
427    if ($("#doc-col").height() < $("#side-nav").height()) {
428      navBarShouldBeFixed = false;
429    }
430
431    var scrollLeft = $(window).scrollLeft();
432    // When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
433    if (navBarIsFixed && (scrollLeft != prevScrollLeft)) {
434      updateSideNavPosition();
435      prevScrollLeft = scrollLeft;
436    }
437
438    // Don't continue if the header is sufficently far away
439    // (to avoid intensive resizing that slows scrolling)
440    if (navBarIsFixed && navBarShouldBeFixed) {
441      return;
442    }
443
444    if (navBarIsFixed != navBarShouldBeFixed) {
445      if (navBarShouldBeFixed) {
446        // make it fixed
447        var width = $('#devdoc-nav').width();
448        $('#devdoc-nav')
449            .addClass('fixed')
450            .css({'width':width+'px'})
451            .prependTo('#body-content');
452        // add neato "back to top" button
453        $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
454
455        // update the sidenaav position for side scrolling
456        updateSideNavPosition();
457      } else {
458        // make it static again
459        $('#devdoc-nav')
460            .removeClass('fixed')
461            .css({'width':'auto','margin':''})
462            .prependTo('#side-nav');
463        $('#devdoc-nav a.totop').hide();
464      }
465      navBarIsFixed = navBarShouldBeFixed;
466    }
467
468    resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
469  });
470
471
472  var navBarLeftPos;
473  if ($('#devdoc-nav').length) {
474    setNavBarLeftPos();
475  }
476
477
478  // Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
479  // from the page)
480  $('.nav-section-header').find('a:eq(0)').click(function(evt) {
481    window.location.href = $(this).attr('href');
482    return false;
483  });
484
485  // Set up play-on-hover <video> tags.
486  $('video.play-on-hover').bind('click', function(){
487    $(this).get(0).load(); // in case the video isn't seekable
488    $(this).get(0).play();
489  });
490
491  // Set up tooltips
492  var TOOLTIP_MARGIN = 10;
493  $('acronym,.tooltip-link').each(function() {
494    var $target = $(this);
495    var $tooltip = $('<div>')
496        .addClass('tooltip-box')
497        .append($target.attr('title'))
498        .hide()
499        .appendTo('body');
500    $target.removeAttr('title');
501
502    $target.hover(function() {
503      // in
504      var targetRect = $target.offset();
505      targetRect.width = $target.width();
506      targetRect.height = $target.height();
507
508      $tooltip.css({
509        left: targetRect.left,
510        top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
511      });
512      $tooltip.addClass('below');
513      $tooltip.show();
514    }, function() {
515      // out
516      $tooltip.hide();
517    });
518  });
519
520  // Set up <h2> deeplinks
521  $('h2').click(function() {
522    var id = $(this).attr('id');
523    if (id) {
524      document.location.hash = id;
525    }
526  });
527
528  //Loads the +1 button
529  var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
530  po.src = 'https://apis.google.com/js/plusone.js';
531  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
532
533
534  // Revise the sidenav widths to make room for the scrollbar
535  // which avoids the visible width from changing each time the bar appears
536  var $sidenav = $("#side-nav");
537  var sidenav_width = parseInt($sidenav.innerWidth());
538
539  $("#devdoc-nav  #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
540
541
542  $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
543
544  if ($(".scroll-pane").length > 1) {
545    // Check if there's a user preference for the panel heights
546    var cookieHeight = readCookie("reference_height");
547    if (cookieHeight) {
548      restoreHeight(cookieHeight);
549    }
550  }
551
552  resizeNav();
553
554  /* init the language selector based on user cookie for lang */
555  loadLangPref();
556  changeNavLang(getLangPref());
557
558  /* setup event handlers to ensure the overflow menu is visible while picking lang */
559  $("#language select")
560      .mousedown(function() {
561        $("div.morehover").addClass("hover"); })
562      .blur(function() {
563        $("div.morehover").removeClass("hover"); });
564
565  /* some global variable setup */
566  resizePackagesNav = $("#resize-packages-nav");
567  classesNav = $("#classes-nav");
568  devdocNav = $("#devdoc-nav");
569
570  var cookiePath = "";
571  if (location.href.indexOf("/reference/") != -1) {
572    cookiePath = "reference_";
573  } else if (location.href.indexOf("/guide/") != -1) {
574    cookiePath = "guide_";
575  } else if (location.href.indexOf("/tools/") != -1) {
576    cookiePath = "tools_";
577  } else if (location.href.indexOf("/training/") != -1) {
578    cookiePath = "training_";
579  } else if (location.href.indexOf("/design/") != -1) {
580    cookiePath = "design_";
581  } else if (location.href.indexOf("/distribute/") != -1) {
582    cookiePath = "distribute_";
583  }
584
585});
586// END of the onload event
587
588
589function highlightSidenav() {
590  // select current page in sidenav and header, and set up prev/next links if they exist
591  var $selNavLink = $('#nav').find('a[href="' + mPagePath + '"]');
592  var $selListItem;
593  if ($selNavLink.length) {
594
595    // Find this page's <li> in sidenav and set selected
596    $selListItem = $selNavLink.closest('li');
597    $selListItem.addClass('selected');
598
599    // Traverse up the tree and expand all parent nav-sections
600    $selNavLink.parents('li.nav-section').each(function() {
601      $(this).addClass('expanded');
602      $(this).children('ul').show();
603    });
604  }
605}
606
607
608function toggleFullscreen(enable) {
609  var delay = 20;
610  var enabled = true;
611  var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
612  if (enable) {
613    // Currently NOT USING fullscreen; enable fullscreen
614    stylesheet.removeAttr('disabled');
615    $('#nav-swap .fullscreen').removeClass('disabled');
616    $('#devdoc-nav').css({left:''});
617    setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
618    enabled = true;
619  } else {
620    // Currently USING fullscreen; disable fullscreen
621    stylesheet.attr('disabled', 'disabled');
622    $('#nav-swap .fullscreen').addClass('disabled');
623    setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
624    enabled = false;
625  }
626  writeCookie("fullscreen", enabled, null, null);
627  setNavBarLeftPos();
628  resizeNav(delay);
629  updateSideNavPosition();
630  setTimeout(initSidenavHeightResize,delay);
631}
632
633
634function setNavBarLeftPos() {
635  navBarLeftPos = $('#body-content').offset().left;
636}
637
638
639function updateSideNavPosition() {
640  var newLeft = $(window).scrollLeft() - navBarLeftPos;
641  $('#devdoc-nav').css({left: -newLeft});
642  $('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
643}
644
645// TODO: use $(document).ready instead
646function addLoadEvent(newfun) {
647  var current = window.onload;
648  if (typeof window.onload != 'function') {
649    window.onload = newfun;
650  } else {
651    window.onload = function() {
652      current();
653      newfun();
654    }
655  }
656}
657
658var agent = navigator['userAgent'].toLowerCase();
659// If a mobile phone, set flag and do mobile setup
660if ((agent.indexOf("mobile") != -1) ||      // android, iphone, ipod
661    (agent.indexOf("blackberry") != -1) ||
662    (agent.indexOf("webos") != -1) ||
663    (agent.indexOf("mini") != -1)) {        // opera mini browsers
664  isMobile = true;
665}
666
667
668addLoadEvent( function() {
669  $("pre:not(.no-pretty-print)").addClass("prettyprint");
670  prettyPrint();
671} );
672
673
674
675
676/* ######### RESIZE THE SIDENAV HEIGHT ########## */
677
678function resizeNav(delay) {
679  var $nav = $("#devdoc-nav");
680  var $window = $(window);
681  var navHeight;
682
683  // Get the height of entire window and the total header height.
684  // Then figure out based on scroll position whether the header is visible
685  var windowHeight = $window.height();
686  var scrollTop = $window.scrollTop();
687  var headerHeight = $('#header').outerHeight();
688  var subheaderHeight = $('#nav-x').outerHeight();
689  var headerVisible = (scrollTop < (headerHeight + subheaderHeight));
690
691  // get the height of space between nav and top of window.
692  // Could be either margin or top position, depending on whether the nav is fixed.
693  var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
694  // add 1 for the #side-nav bottom margin
695
696  // Depending on whether the header is visible, set the side nav's height.
697  if (headerVisible) {
698    // The sidenav height grows as the header goes off screen
699    navHeight = windowHeight - (headerHeight + subheaderHeight - scrollTop) - topMargin;
700  } else {
701    // Once header is off screen, the nav height is almost full window height
702    navHeight = windowHeight - topMargin;
703  }
704
705
706
707  $scrollPanes = $(".scroll-pane");
708  if ($scrollPanes.length > 1) {
709    // subtract the height of the api level widget and nav swapper from the available nav height
710    navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
711
712    $("#swapper").css({height:navHeight + "px"});
713    if ($("#nav-tree").is(":visible")) {
714      $("#nav-tree").css({height:navHeight});
715    }
716
717    var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
718    //subtract 10px to account for drag bar
719
720    // if the window becomes small enough to make the class panel height 0,
721    // then the package panel should begin to shrink
722    if (parseInt(classesHeight) <= 0) {
723      $("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
724      $("#packages-nav").css({height:navHeight - 10});
725    }
726
727    $("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
728    $("#classes-nav .jspContainer").css({height:classesHeight});
729
730
731  } else {
732    $nav.height(navHeight);
733  }
734
735  if (delay) {
736    updateFromResize = true;
737    delayedReInitScrollbars(delay);
738  } else {
739    reInitScrollbars();
740  }
741
742}
743
744var updateScrollbars = false;
745var updateFromResize = false;
746
747/* Re-initialize the scrollbars to account for changed nav size.
748 * This method postpones the actual update by a 1/4 second in order to optimize the
749 * scroll performance while the header is still visible, because re-initializing the
750 * scroll panes is an intensive process.
751 */
752function delayedReInitScrollbars(delay) {
753  // If we're scheduled for an update, but have received another resize request
754  // before the scheduled resize has occured, just ignore the new request
755  // (and wait for the scheduled one).
756  if (updateScrollbars && updateFromResize) {
757    updateFromResize = false;
758    return;
759  }
760
761  // We're scheduled for an update and the update request came from this method's setTimeout
762  if (updateScrollbars && !updateFromResize) {
763    reInitScrollbars();
764    updateScrollbars = false;
765  } else {
766    updateScrollbars = true;
767    updateFromResize = false;
768    setTimeout('delayedReInitScrollbars()',delay);
769  }
770}
771
772/* Re-initialize the scrollbars to account for changed nav size. */
773function reInitScrollbars() {
774  var pane = $(".scroll-pane").each(function(){
775    var api = $(this).data('jsp');
776    if (!api) { setTimeout(reInitScrollbars,300); return;}
777    api.reinitialise( {verticalGutter:0} );
778  });
779  $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
780}
781
782
783/* Resize the height of the nav panels in the reference,
784 * and save the new size to a cookie */
785function saveNavPanels() {
786  var basePath = getBaseUri(location.pathname);
787  var section = basePath.substring(1,basePath.indexOf("/",1));
788  writeCookie("height", resizePackagesNav.css("height"), section, null);
789}
790
791
792
793function restoreHeight(packageHeight) {
794    $("#resize-packages-nav").height(packageHeight);
795    $("#packages-nav").height(packageHeight);
796  //  var classesHeight = navHeight - packageHeight;
797 //   $("#classes-nav").css({height:classesHeight});
798  //  $("#classes-nav .jspContainer").css({height:classesHeight});
799}
800
801
802
803/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
804
805
806
807
808
809/** Scroll the jScrollPane to make the currently selected item visible
810    This is called when the page finished loading. */
811function scrollIntoView(nav) {
812  var $nav = $("#"+nav);
813  var element = $nav.jScrollPane({/* ...settings... */});
814  var api = element.data('jsp');
815
816  if ($nav.is(':visible')) {
817    var $selected = $(".selected", $nav);
818    if ($selected.length == 0) {
819      // If no selected item found, exit
820      return;
821    }
822    // get the selected item's offset from its container nav by measuring the item's offset
823    // relative to the document then subtract the container nav's offset relative to the document
824    var selectedOffset = $selected.offset().top - $nav.offset().top;
825    if (selectedOffset > $nav.height() * .8) { // multiply nav height by .8 so we move up the item
826                                               // if it's more than 80% down the nav
827      // scroll the item up by an amount equal to 80% the container nav's height
828      api.scrollTo(0, selectedOffset - ($nav.height() * .8), false);
829    }
830  }
831}
832
833
834
835
836
837
838/* Show popup dialogs */
839function showDialog(id) {
840  $dialog = $("#"+id);
841  $dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>');
842  $dialog.wrapInner('<div/>');
843  $dialog.removeClass("hide");
844}
845
846
847
848
849
850/* #########    COOKIES!     ########## */
851
852function readCookie(cookie) {
853  var myCookie = cookie_namespace+"_"+cookie+"=";
854  if (document.cookie) {
855    var index = document.cookie.indexOf(myCookie);
856    if (index != -1) {
857      var valStart = index + myCookie.length;
858      var valEnd = document.cookie.indexOf(";", valStart);
859      if (valEnd == -1) {
860        valEnd = document.cookie.length;
861      }
862      var val = document.cookie.substring(valStart, valEnd);
863      return val;
864    }
865  }
866  return 0;
867}
868
869function writeCookie(cookie, val, section, expiration) {
870  if (val==undefined) return;
871  section = section == null ? "_" : "_"+section+"_";
872  if (expiration == null) {
873    var date = new Date();
874    date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
875    expiration = date.toGMTString();
876  }
877  var cookieValue = cookie_namespace + section + cookie + "=" + val
878                    + "; expires=" + expiration+"; path=/";
879  document.cookie = cookieValue;
880}
881
882/* #########     END COOKIES!     ########## */
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902/*      MISC LIBRARY FUNCTIONS     */
903
904
905
906
907
908function toggle(obj, slide) {
909  var ul = $("ul:first", obj);
910  var li = ul.parent();
911  if (li.hasClass("closed")) {
912    if (slide) {
913      ul.slideDown("fast");
914    } else {
915      ul.show();
916    }
917    li.removeClass("closed");
918    li.addClass("open");
919    $(".toggle-img", li).attr("title", "hide pages");
920  } else {
921    ul.slideUp("fast");
922    li.removeClass("open");
923    li.addClass("closed");
924    $(".toggle-img", li).attr("title", "show pages");
925  }
926}
927
928
929function buildToggleLists() {
930  $(".toggle-list").each(
931    function(i) {
932      $("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
933      $(this).addClass("closed");
934    });
935}
936
937
938
939function hideNestedItems(list, toggle) {
940  $list = $(list);
941  // hide nested lists
942  if($list.hasClass('showing')) {
943    $("li ol", $list).hide('fast');
944    $list.removeClass('showing');
945  // show nested lists
946  } else {
947    $("li ol", $list).show('fast');
948    $list.addClass('showing');
949  }
950  $(".more,.less",$(toggle)).toggle();
951}
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980/*      REFERENCE NAV SWAP     */
981
982
983function getNavPref() {
984  var v = readCookie('reference_nav');
985  if (v != NAV_PREF_TREE) {
986    v = NAV_PREF_PANELS;
987  }
988  return v;
989}
990
991function chooseDefaultNav() {
992  nav_pref = getNavPref();
993  if (nav_pref == NAV_PREF_TREE) {
994    $("#nav-panels").toggle();
995    $("#panel-link").toggle();
996    $("#nav-tree").toggle();
997    $("#tree-link").toggle();
998  }
999}
1000
1001function swapNav() {
1002  if (nav_pref == NAV_PREF_TREE) {
1003    nav_pref = NAV_PREF_PANELS;
1004  } else {
1005    nav_pref = NAV_PREF_TREE;
1006    init_default_navtree(toRoot);
1007  }
1008  var date = new Date();
1009  date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
1010  writeCookie("nav", nav_pref, "reference", date.toGMTString());
1011
1012  $("#nav-panels").toggle();
1013  $("#panel-link").toggle();
1014  $("#nav-tree").toggle();
1015  $("#tree-link").toggle();
1016
1017  resizeNav();
1018
1019  // Gross nasty hack to make tree view show up upon first swap by setting height manually
1020  $("#nav-tree .jspContainer:visible")
1021      .css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
1022  // Another nasty hack to make the scrollbar appear now that we have height
1023  resizeNav();
1024
1025  if ($("#nav-tree").is(':visible')) {
1026    scrollIntoView("nav-tree");
1027  } else {
1028    scrollIntoView("packages-nav");
1029    scrollIntoView("classes-nav");
1030  }
1031}
1032
1033
1034
1035/* ############################################ */
1036/* ##########     LOCALIZATION     ############ */
1037/* ############################################ */
1038
1039function getBaseUri(uri) {
1040  var intlUrl = (uri.substring(0,6) == "/intl/");
1041  if (intlUrl) {
1042    base = uri.substring(uri.indexOf('intl/')+5,uri.length);
1043    base = base.substring(base.indexOf('/')+1, base.length);
1044      //alert("intl, returning base url: /" + base);
1045    return ("/" + base);
1046  } else {
1047      //alert("not intl, returning uri as found.");
1048    return uri;
1049  }
1050}
1051
1052function requestAppendHL(uri) {
1053//append "?hl=<lang> to an outgoing request (such as to blog)
1054  var lang = getLangPref();
1055  if (lang) {
1056    var q = 'hl=' + lang;
1057    uri += '?' + q;
1058    window.location = uri;
1059    return false;
1060  } else {
1061    return true;
1062  }
1063}
1064
1065
1066function changeNavLang(lang) {
1067  var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
1068  $links.each(function(i){ // for each link with a translation
1069    var $link = $(this);
1070    if (lang != "en") { // No need to worry about English, because a language change invokes new request
1071      // put the desired language from the attribute as the text
1072      $link.text($link.attr(lang+"-lang"))
1073    }
1074  });
1075}
1076
1077function changeLangPref(lang, submit) {
1078  var date = new Date();
1079  expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000)));
1080  // keep this for 50 years
1081  //alert("expires: " + expires)
1082  writeCookie("pref_lang", lang, null, expires);
1083
1084  //  #######  TODO:  Remove this condition once we're stable on devsite #######
1085  //  This condition is only needed if we still need to support legacy GAE server
1086  if (devsite) {
1087    // Switch language when on Devsite server
1088    if (submit) {
1089      $("#setlang").submit();
1090    }
1091  } else {
1092    // Switch language when on legacy GAE server
1093    if (submit) {
1094      window.location = getBaseUri(location.pathname);
1095    }
1096  }
1097}
1098
1099function loadLangPref() {
1100  var lang = readCookie("pref_lang");
1101  if (lang != 0) {
1102    $("#language").find("option[value='"+lang+"']").attr("selected",true);
1103  }
1104}
1105
1106function getLangPref() {
1107  var lang = $("#language").find(":selected").attr("value");
1108  if (!lang) {
1109    lang = readCookie("pref_lang");
1110  }
1111  return (lang != 0) ? lang : 'en';
1112}
1113
1114/* ##########     END LOCALIZATION     ############ */
1115
1116
1117
1118
1119
1120
1121/* Used to hide and reveal supplemental content, such as long code samples.
1122   See the companion CSS in android-developer-docs.css */
1123function toggleContent(obj) {
1124  var div = $(obj.parentNode.parentNode);
1125  var toggleMe = $(".toggle-content-toggleme",div);
1126  if (div.hasClass("closed")) { // if it's closed, open it
1127    toggleMe.slideDown();
1128    $(".toggle-content-text", obj).toggle();
1129    div.removeClass("closed").addClass("open");
1130    $(".toggle-content-img", div).attr("title", "hide").attr("src", toRoot
1131                  + "assets/images/triangle-opened.png");
1132  } else { // if it's open, close it
1133    toggleMe.slideUp('fast', function() {  // Wait until the animation is done before closing arrow
1134      $(".toggle-content-text", obj).toggle();
1135      div.removeClass("open").addClass("closed");
1136      $(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
1137                  + "assets/images/triangle-closed.png");
1138    });
1139  }
1140  return false;
1141}
1142
1143
1144/* New version of expandable content */
1145function toggleExpandable(link,id) {
1146  if($(id).is(':visible')) {
1147    $(id).slideUp();
1148    $(link).removeClass('expanded');
1149  } else {
1150    $(id).slideDown();
1151    $(link).addClass('expanded');
1152  }
1153}
1154
1155function hideExpandable(ids) {
1156  $(ids).slideUp();
1157  $(ids).prev('h4').find('a.expandable').removeClass('expanded');
1158}
1159
1160
1161
1162
1163
1164/*
1165 *  Slideshow 1.0
1166 *  Used on /index.html and /develop/index.html for carousel
1167 *
1168 *  Sample usage:
1169 *  HTML -
1170 *  <div class="slideshow-container">
1171 *   <a href="" class="slideshow-prev">Prev</a>
1172 *   <a href="" class="slideshow-next">Next</a>
1173 *   <ul>
1174 *       <li class="item"><img src="images/marquee1.jpg"></li>
1175 *       <li class="item"><img src="images/marquee2.jpg"></li>
1176 *       <li class="item"><img src="images/marquee3.jpg"></li>
1177 *       <li class="item"><img src="images/marquee4.jpg"></li>
1178 *   </ul>
1179 *  </div>
1180 *
1181 *   <script type="text/javascript">
1182 *   $('.slideshow-container').dacSlideshow({
1183 *       auto: true,
1184 *       btnPrev: '.slideshow-prev',
1185 *       btnNext: '.slideshow-next'
1186 *   });
1187 *   </script>
1188 *
1189 *  Options:
1190 *  btnPrev:    optional identifier for previous button
1191 *  btnNext:    optional identifier for next button
1192 *  btnPause:   optional identifier for pause button
1193 *  auto:       whether or not to auto-proceed
1194 *  speed:      animation speed
1195 *  autoTime:   time between auto-rotation
1196 *  easing:     easing function for transition
1197 *  start:      item to select by default
1198 *  scroll:     direction to scroll in
1199 *  pagination: whether or not to include dotted pagination
1200 *
1201 */
1202
1203 (function($) {
1204 $.fn.dacSlideshow = function(o) {
1205
1206     //Options - see above
1207     o = $.extend({
1208         btnPrev:   null,
1209         btnNext:   null,
1210         btnPause:  null,
1211         auto:      true,
1212         speed:     500,
1213         autoTime:  12000,
1214         easing:    null,
1215         start:     0,
1216         scroll:    1,
1217         pagination: true
1218
1219     }, o || {});
1220
1221     //Set up a carousel for each
1222     return this.each(function() {
1223
1224         var running = false;
1225         var animCss = o.vertical ? "top" : "left";
1226         var sizeCss = o.vertical ? "height" : "width";
1227         var div = $(this);
1228         var ul = $("ul", div);
1229         var tLi = $("li", ul);
1230         var tl = tLi.size();
1231         var timer = null;
1232
1233         var li = $("li", ul);
1234         var itemLength = li.size();
1235         var curr = o.start;
1236
1237         li.css({float: o.vertical ? "none" : "left"});
1238         ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
1239         div.css({position: "relative", "z-index": "2", left: "0px"});
1240
1241         var liSize = o.vertical ? height(li) : width(li);
1242         var ulSize = liSize * itemLength;
1243         var divSize = liSize;
1244
1245         li.css({width: li.width(), height: li.height()});
1246         ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
1247
1248         div.css(sizeCss, divSize+"px");
1249
1250         //Pagination
1251         if (o.pagination) {
1252             var pagination = $("<div class='pagination'></div>");
1253             var pag_ul = $("<ul></ul>");
1254             if (tl > 1) {
1255               for (var i=0;i<tl;i++) {
1256                    var li = $("<li>"+i+"</li>");
1257                    pag_ul.append(li);
1258                    if (i==o.start) li.addClass('active');
1259                        li.click(function() {
1260                        go(parseInt($(this).text()));
1261                    })
1262                }
1263                pagination.append(pag_ul);
1264                div.append(pagination);
1265             }
1266         }
1267
1268         //Previous button
1269         if(o.btnPrev)
1270             $(o.btnPrev).click(function(e) {
1271                 e.preventDefault();
1272                 return go(curr-o.scroll);
1273             });
1274
1275         //Next button
1276         if(o.btnNext)
1277             $(o.btnNext).click(function(e) {
1278                 e.preventDefault();
1279                 return go(curr+o.scroll);
1280             });
1281
1282         //Pause button
1283         if(o.btnPause)
1284             $(o.btnPause).click(function(e) {
1285                 e.preventDefault();
1286                 if ($(this).hasClass('paused')) {
1287                     startRotateTimer();
1288                 } else {
1289                     pauseRotateTimer();
1290                 }
1291             });
1292
1293         //Auto rotation
1294         if(o.auto) startRotateTimer();
1295
1296         function startRotateTimer() {
1297             clearInterval(timer);
1298             timer = setInterval(function() {
1299                  if (curr == tl-1) {
1300                    go(0);
1301                  } else {
1302                    go(curr+o.scroll);
1303                  }
1304              }, o.autoTime);
1305             $(o.btnPause).removeClass('paused');
1306         }
1307
1308         function pauseRotateTimer() {
1309             clearInterval(timer);
1310             $(o.btnPause).addClass('paused');
1311         }
1312
1313         //Go to an item
1314         function go(to) {
1315             if(!running) {
1316
1317                 if(to<0) {
1318                    to = itemLength-1;
1319                 } else if (to>itemLength-1) {
1320                    to = 0;
1321                 }
1322                 curr = to;
1323
1324                 running = true;
1325
1326                 ul.animate(
1327                     animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
1328                     function() {
1329                         running = false;
1330                     }
1331                 );
1332
1333                 $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
1334                 $( (curr-o.scroll<0 && o.btnPrev)
1335                     ||
1336                    (curr+o.scroll > itemLength && o.btnNext)
1337                     ||
1338                    []
1339                  ).addClass("disabled");
1340
1341
1342                 var nav_items = $('li', pagination);
1343                 nav_items.removeClass('active');
1344                 nav_items.eq(to).addClass('active');
1345
1346
1347             }
1348             if(o.auto) startRotateTimer();
1349             return false;
1350         };
1351     });
1352 };
1353
1354 function css(el, prop) {
1355     return parseInt($.css(el[0], prop)) || 0;
1356 };
1357 function width(el) {
1358     return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
1359 };
1360 function height(el) {
1361     return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
1362 };
1363
1364 })(jQuery);
1365
1366
1367/*
1368 *  dacSlideshow 1.0
1369 *  Used on develop/index.html for side-sliding tabs
1370 *
1371 *  Sample usage:
1372 *  HTML -
1373 *  <div class="slideshow-container">
1374 *   <a href="" class="slideshow-prev">Prev</a>
1375 *   <a href="" class="slideshow-next">Next</a>
1376 *   <ul>
1377 *       <li class="item"><img src="images/marquee1.jpg"></li>
1378 *       <li class="item"><img src="images/marquee2.jpg"></li>
1379 *       <li class="item"><img src="images/marquee3.jpg"></li>
1380 *       <li class="item"><img src="images/marquee4.jpg"></li>
1381 *   </ul>
1382 *  </div>
1383 *
1384 *   <script type="text/javascript">
1385 *   $('.slideshow-container').dacSlideshow({
1386 *       auto: true,
1387 *       btnPrev: '.slideshow-prev',
1388 *       btnNext: '.slideshow-next'
1389 *   });
1390 *   </script>
1391 *
1392 *  Options:
1393 *  btnPrev:    optional identifier for previous button
1394 *  btnNext:    optional identifier for next button
1395 *  auto:       whether or not to auto-proceed
1396 *  speed:      animation speed
1397 *  autoTime:   time between auto-rotation
1398 *  easing:     easing function for transition
1399 *  start:      item to select by default
1400 *  scroll:     direction to scroll in
1401 *  pagination: whether or not to include dotted pagination
1402 *
1403 */
1404 (function($) {
1405 $.fn.dacTabbedList = function(o) {
1406
1407     //Options - see above
1408     o = $.extend({
1409         speed : 250,
1410         easing: null,
1411         nav_id: null,
1412         frame_id: null
1413     }, o || {});
1414
1415     //Set up a carousel for each
1416     return this.each(function() {
1417
1418         var curr = 0;
1419         var running = false;
1420         var animCss = "margin-left";
1421         var sizeCss = "width";
1422         var div = $(this);
1423
1424         var nav = $(o.nav_id, div);
1425         var nav_li = $("li", nav);
1426         var nav_size = nav_li.size();
1427         var frame = div.find(o.frame_id);
1428         var content_width = $(frame).find('ul').width();
1429         //Buttons
1430         $(nav_li).click(function(e) {
1431           go($(nav_li).index($(this)));
1432         })
1433
1434         //Go to an item
1435         function go(to) {
1436             if(!running) {
1437                 curr = to;
1438                 running = true;
1439
1440                 frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
1441                     function() {
1442                         running = false;
1443                     }
1444                 );
1445
1446
1447                 nav_li.removeClass('active');
1448                 nav_li.eq(to).addClass('active');
1449
1450
1451             }
1452             return false;
1453         };
1454     });
1455 };
1456
1457 function css(el, prop) {
1458     return parseInt($.css(el[0], prop)) || 0;
1459 };
1460 function width(el) {
1461     return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
1462 };
1463 function height(el) {
1464     return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
1465 };
1466
1467 })(jQuery);
1468
1469
1470
1471
1472
1473/* ######################################################## */
1474/* ################  SEARCH SUGGESTIONS  ################## */
1475/* ######################################################## */
1476
1477
1478
1479var gSelectedIndex = -1;  // the index position of currently highlighted suggestion
1480var gSelectedColumn = -1;  // which column of suggestion lists is currently focused
1481
1482var gMatches = new Array();
1483var gLastText = "";
1484var gInitialized = false;
1485var ROW_COUNT_FRAMEWORK = 20;       // max number of results in list
1486var gListLength = 0;
1487
1488
1489var gGoogleMatches = new Array();
1490var ROW_COUNT_GOOGLE = 15;          // max number of results in list
1491var gGoogleListLength = 0;
1492
1493var gDocsMatches = new Array();
1494var ROW_COUNT_DOCS = 100;          // max number of results in list
1495var gDocsListLength = 0;
1496
1497function onSuggestionClick(link) {
1498  // When user clicks a suggested document, track it
1499  _gaq.push(['_trackEvent', 'Suggestion Click', 'clicked: ' + $(link).text(),
1500            'from: ' + $("#search_autocomplete").val()]);
1501}
1502
1503function set_item_selected($li, selected)
1504{
1505    if (selected) {
1506        $li.attr('class','jd-autocomplete jd-selected');
1507    } else {
1508        $li.attr('class','jd-autocomplete');
1509    }
1510}
1511
1512function set_item_values(toroot, $li, match)
1513{
1514    var $link = $('a',$li);
1515    $link.html(match.__hilabel || match.label);
1516    $link.attr('href',toroot + match.link);
1517}
1518
1519function new_suggestion($list) {
1520    var $li = $("<li class='jd-autocomplete'></li>");
1521    $list.append($li);
1522
1523    $li.mousedown(function() {
1524        window.location = this.firstChild.getAttribute("href");
1525    });
1526    $li.mouseover(function() {
1527        $('.search_filtered_wrapper li').removeClass('jd-selected');
1528        $(this).addClass('jd-selected');
1529        gSelectedColumn = $(".search_filtered:visible").index($(this).closest('.search_filtered'));
1530        gSelectedIndex = $("li", $(".search_filtered:visible")[gSelectedColumn]).index(this);
1531    });
1532    $li.append("<a onclick='onSuggestionClick(this)'></a>");
1533    $li.attr('class','show-item');
1534    return $li;
1535}
1536
1537function sync_selection_table(toroot)
1538{
1539    var $li; //list item jquery object
1540    var i; //list item iterator
1541
1542    // if there are NO results at all, hide all columns
1543    if (!(gMatches.length > 0) && !(gGoogleMatches.length > 0) && !(gDocsMatches.length > 0)) {
1544        $('.suggest-card').hide(300);
1545        return;
1546    }
1547
1548    // if there are api results
1549    if ((gMatches.length > 0) || (gGoogleMatches.length > 0)) {
1550      // reveal suggestion list
1551      $('.suggest-card.dummy').show();
1552      $('.suggest-card.reference').show();
1553      var listIndex = 0; // list index position
1554
1555      // reset the lists
1556      $(".search_filtered_wrapper.reference li").remove();
1557
1558      // ########### ANDROID RESULTS #############
1559      if (gMatches.length > 0) {
1560
1561          // determine android results to show
1562          gListLength = gMatches.length < ROW_COUNT_FRAMEWORK ?
1563                        gMatches.length : ROW_COUNT_FRAMEWORK;
1564          for (i=0; i<gListLength; i++) {
1565              var $li = new_suggestion($(".suggest-card.reference ul"));
1566              set_item_values(toroot, $li, gMatches[i]);
1567              set_item_selected($li, i == gSelectedIndex);
1568          }
1569      }
1570
1571      // ########### GOOGLE RESULTS #############
1572      if (gGoogleMatches.length > 0) {
1573          // show header for list
1574          $(".suggest-card.reference ul").append("<li class='header'>in Google Services:</li>");
1575
1576          // determine google results to show
1577          gGoogleListLength = gGoogleMatches.length < ROW_COUNT_GOOGLE ? gGoogleMatches.length : ROW_COUNT_GOOGLE;
1578          for (i=0; i<gGoogleListLength; i++) {
1579              var $li = new_suggestion($(".suggest-card.reference ul"));
1580              set_item_values(toroot, $li, gGoogleMatches[i]);
1581              set_item_selected($li, i == gSelectedIndex);
1582          }
1583      }
1584    } else {
1585      $('.suggest-card.reference').hide();
1586      $('.suggest-card.dummy').hide();
1587    }
1588
1589    // ########### JD DOC RESULTS #############
1590    if (gDocsMatches.length > 0) {
1591        // reset the lists
1592        $(".search_filtered_wrapper.docs li").remove();
1593
1594        // determine google results to show
1595        gDocsListLength = gDocsMatches.length < ROW_COUNT_DOCS ? gDocsMatches.length : ROW_COUNT_DOCS;
1596        for (i=0; i<gDocsListLength; i++) {
1597            var sugg = gDocsMatches[i];
1598            var $li;
1599            if (sugg.type == "design") {
1600                $li = new_suggestion($(".suggest-card.design ul"));
1601            } else
1602            if (sugg.type == "distribute") {
1603                $li = new_suggestion($(".suggest-card.distribute ul"));
1604            } else
1605            if (sugg.type == "training") {
1606                $li = new_suggestion($(".suggest-card.develop .child-card.training"));
1607            } else
1608            if (sugg.type == "guide"||"google") {
1609                $li = new_suggestion($(".suggest-card.develop .child-card.guides"));
1610            } else {
1611              continue;
1612            }
1613
1614            set_item_values(toroot, $li, sugg);
1615            set_item_selected($li, i == gSelectedIndex);
1616        }
1617
1618        // add heading and show or hide card
1619        if ($(".suggest-card.design li").length > 0) {
1620          $(".suggest-card.design ul").prepend("<li class='header'>Design:</li>");
1621          $(".suggest-card.design").show(300);
1622        } else {
1623          $('.suggest-card.design').hide(300);
1624        }
1625        if ($(".suggest-card.distribute li").length > 0) {
1626          $(".suggest-card.distribute ul").prepend("<li class='header'>Distribute:</li>");
1627          $(".suggest-card.distribute").show(300);
1628        } else {
1629          $('.suggest-card.distribute').hide(300);
1630        }
1631        if ($(".child-card.guides li").length > 0) {
1632          $(".child-card.guides").prepend("<li class='header'>Guides:</li>");
1633          $(".child-card.guides li").appendTo(".suggest-card.develop ul");
1634        }
1635        if ($(".child-card.training li").length > 0) {
1636          $(".child-card.training").prepend("<li class='header'>Training:</li>");
1637          $(".child-card.training li").appendTo(".suggest-card.develop ul");
1638        }
1639
1640        if ($(".suggest-card.develop li").length > 0) {
1641          $(".suggest-card.develop").show(300);
1642        } else {
1643          $('.suggest-card.develop').hide(300);
1644        }
1645
1646    } else {
1647      $('.search_filtered_wrapper.docs .suggest-card:not(.dummy)').hide(300);
1648    }
1649}
1650
1651/** Called by the search input's onkeydown and onkeyup events.
1652  * Handles navigation with keyboard arrows, Enter key to invoke search,
1653  * otherwise invokes search suggestions on key-up event.
1654  * @param e       The JS event
1655  * @param kd      True if the event is key-down
1656  * @param toroot  A string for the site's root path
1657  * @returns       True if the event should bubble up
1658  */
1659function search_changed(e, kd, toroot)
1660{
1661    var search = document.getElementById("search_autocomplete");
1662    var text = search.value.replace(/(^ +)|( +$)/g, '');
1663    // get the ul hosting the currently selected item
1664    gSelectedColumn = gSelectedColumn >= 0 ? gSelectedColumn :  0;
1665    var $columns = $(".search_filtered_wrapper").find(".search_filtered:visible");
1666    var $selectedUl = $columns[gSelectedColumn];
1667
1668    // show/hide the close button
1669    if (text != '') {
1670        $(".search .close").removeClass("hide");
1671    } else {
1672        $(".search .close").addClass("hide");
1673    }
1674    // 27 = esc
1675    if (e.keyCode == 27) {
1676        // close all search results
1677        if (kd) $('.search .close').trigger('click');
1678        return true;
1679    }
1680    // 13 = enter
1681    else if (e.keyCode == 13) {
1682        if (gSelectedIndex < 0) {
1683            $('.suggest-card').hide();
1684            if ($("#searchResults").is(":hidden") && (search.value != "")) {
1685              // if results aren't showing (and text not empty), return true to allow search to execute
1686              return true;
1687            } else {
1688              // otherwise, results are already showing, so allow ajax to auto refresh the results
1689              // and ignore this Enter press to avoid the reload.
1690              return false;
1691            }
1692        } else if (kd && gSelectedIndex >= 0) {
1693            // click the link corresponding to selected item
1694            $("a",$("li",$selectedUl)[gSelectedIndex]).get()[0].click();
1695            return false;
1696        }
1697    }
1698    // Stop here if Google results are showing
1699    else if ($("#searchResults").is(":visible")) {
1700        return true;
1701    }
1702    // 38 UP ARROW
1703    else if (kd && (e.keyCode == 38)) {
1704        // if the next item is a header, skip it
1705        if ($($("li", $selectedUl)[gSelectedIndex-1]).hasClass("header")) {
1706            gSelectedIndex--;
1707        }
1708        if (gSelectedIndex >= 0) {
1709            $('li', $selectedUl).removeClass('jd-selected');
1710            gSelectedIndex--;
1711            $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1712            // If user reaches top, reset selected column
1713            if (gSelectedIndex < 0) {
1714              gSelectedColumn = -1;
1715            }
1716        }
1717        return false;
1718    }
1719    // 40 DOWN ARROW
1720    else if (kd && (e.keyCode == 40)) {
1721        // if the next item is a header, skip it
1722        if ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header")) {
1723            gSelectedIndex++;
1724        }
1725        if ((gSelectedIndex < $("li", $selectedUl).length-1) ||
1726                        ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header"))) {
1727            $('li', $selectedUl).removeClass('jd-selected');
1728            gSelectedIndex++;
1729            $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1730        }
1731        return false;
1732    }
1733    // Consider left/right arrow navigation
1734    // NOTE: Order of suggest columns are reverse order (index position 0 is on right)
1735    else if (kd && $columns.length > 1 && gSelectedColumn >= 0) {
1736      // 37 LEFT ARROW
1737      // go left only if current column is not left-most column (last column)
1738      if (e.keyCode == 37 && gSelectedColumn < $columns.length - 1) {
1739        $('li', $selectedUl).removeClass('jd-selected');
1740        gSelectedColumn++;
1741        $selectedUl = $columns[gSelectedColumn];
1742        // keep or reset the selected item to last item as appropriate
1743        gSelectedIndex = gSelectedIndex >
1744                $("li", $selectedUl).length-1 ?
1745                $("li", $selectedUl).length-1 : gSelectedIndex;
1746        // if the corresponding item is a header, move down
1747        if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
1748          gSelectedIndex++;
1749        }
1750        // set item selected
1751        $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1752        return false;
1753      }
1754      // 39 RIGHT ARROW
1755      // go right only if current column is not the right-most column (first column)
1756      else if (e.keyCode == 39 && gSelectedColumn > 0) {
1757        $('li', $selectedUl).removeClass('jd-selected');
1758        gSelectedColumn--;
1759        $selectedUl = $columns[gSelectedColumn];
1760        // keep or reset the selected item to last item as appropriate
1761        gSelectedIndex = gSelectedIndex >
1762                $("li", $selectedUl).length-1 ?
1763                $("li", $selectedUl).length-1 : gSelectedIndex;
1764        // if the corresponding item is a header, move down
1765        if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
1766          gSelectedIndex++;
1767        }
1768        // set item selected
1769        $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1770        return false;
1771      }
1772    }
1773
1774    // if key-up event and not arrow down/up,
1775    // read the search query and add suggestsions to gMatches
1776    else if (!kd && (e.keyCode != 40)
1777                 && (e.keyCode != 38)
1778                 && (e.keyCode != 37)
1779                 && (e.keyCode != 39)) {
1780        gSelectedIndex = -1;
1781        gMatches = new Array();
1782        matchedCount = 0;
1783        gGoogleMatches = new Array();
1784        matchedCountGoogle = 0;
1785        gDocsMatches = new Array();
1786        matchedCountDocs = 0;
1787
1788        // Search for Android matches
1789        for (var i=0; i<DATA.length; i++) {
1790            var s = DATA[i];
1791            if (text.length != 0 &&
1792                  s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
1793                gMatches[matchedCount] = s;
1794                matchedCount++;
1795            }
1796        }
1797        rank_autocomplete_api_results(text, gMatches);
1798        for (var i=0; i<gMatches.length; i++) {
1799            var s = gMatches[i];
1800        }
1801
1802
1803        // Search for Google matches
1804        for (var i=0; i<GOOGLE_DATA.length; i++) {
1805            var s = GOOGLE_DATA[i];
1806            if (text.length != 0 &&
1807                  s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
1808                gGoogleMatches[matchedCountGoogle] = s;
1809                matchedCountGoogle++;
1810            }
1811        }
1812        rank_autocomplete_api_results(text, gGoogleMatches);
1813        for (var i=0; i<gGoogleMatches.length; i++) {
1814            var s = gGoogleMatches[i];
1815        }
1816
1817        highlight_autocomplete_result_labels(text);
1818
1819
1820
1821        // Search for JD docs
1822        if (text.length >= 3) {
1823          for (var i=0; i<JD_DATA.length; i++) {
1824            // Regex to match only the beginning of a word
1825            var textRegex = new RegExp("\\b" + text.toLowerCase(), "g");
1826            // current search comparison, with counters for tag and title,
1827            // used later to improve ranking
1828            var s = JD_DATA[i];
1829            s.matched_tag = 0;
1830            s.matched_title = 0;
1831            var matched = false;
1832
1833            // Check if query matches any tags; work backwards toward 1 to assist ranking
1834            for (var j = s.tags.length - 1; j >= 0; j--) {
1835              // it matches a tag
1836              if (s.tags[j].toLowerCase().match(textRegex)) {
1837                matched = true;
1838                s.matched_tag = j + 1; // add 1 to index position
1839              }
1840            }
1841            // Don't consider doc title for lessons (only for class landing pages)
1842            // ...it is not a training lesson (or is but has matched a tag)
1843            if (!(s.type == "training" && s.link.indexOf("index.html") == -1) || matched) {
1844              // it matches the doc title
1845              if (s.label.toLowerCase().match(textRegex)) {
1846                matched = true;
1847                s.matched_title = 1;
1848              }
1849            }
1850            if (matched) {
1851              gDocsMatches[matchedCountDocs] = s;
1852              matchedCountDocs++;
1853            }
1854          }
1855          rank_autocomplete_doc_results(text, gDocsMatches);
1856        }
1857
1858        // draw the suggestions
1859        sync_selection_table(toroot);
1860        return true; // allow the event to bubble up to the search api
1861    }
1862}
1863
1864/* Order the jd doc result list based on match quality */
1865function rank_autocomplete_doc_results(query, matches) {
1866    query = query || '';
1867    if (!matches || !matches.length)
1868      return;
1869
1870    var _resultScoreFn = function(match) {
1871        var score = 1.0;
1872
1873        // if the query matched a tag
1874        if (match.matched_tag > 0) {
1875          // multiply score by factor relative to position in tags list (max of 3)
1876          score *= 3 / match.matched_tag;
1877
1878          // if it also matched the title
1879          if (match.matched_title > 0) {
1880            score *= 2;
1881          }
1882        } else if (match.matched_title > 0) {
1883          score *= 3;
1884        }
1885
1886        return score;
1887    };
1888
1889    for (var i=0; i<matches.length; i++) {
1890        matches[i].__resultScore = _resultScoreFn(matches[i]);
1891    }
1892
1893    matches.sort(function(a,b){
1894        var n = b.__resultScore - a.__resultScore;
1895        if (n == 0) // lexicographical sort if scores are the same
1896            n = (a.label < b.label) ? -1 : 1;
1897        return n;
1898    });
1899}
1900
1901/* Order the result list based on match quality */
1902function rank_autocomplete_api_results(query, matches) {
1903    query = query || '';
1904    if (!matches || !matches.length)
1905      return;
1906
1907    // helper function that gets the last occurence index of the given regex
1908    // in the given string, or -1 if not found
1909    var _lastSearch = function(s, re) {
1910      if (s == '')
1911        return -1;
1912      var l = -1;
1913      var tmp;
1914      while ((tmp = s.search(re)) >= 0) {
1915        if (l < 0) l = 0;
1916        l += tmp;
1917        s = s.substr(tmp + 1);
1918      }
1919      return l;
1920    };
1921
1922    // helper function that counts the occurrences of a given character in
1923    // a given string
1924    var _countChar = function(s, c) {
1925      var n = 0;
1926      for (var i=0; i<s.length; i++)
1927        if (s.charAt(i) == c) ++n;
1928      return n;
1929    };
1930
1931    var queryLower = query.toLowerCase();
1932    var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
1933    var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
1934    var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
1935
1936    var _resultScoreFn = function(result) {
1937        // scores are calculated based on exact and prefix matches,
1938        // and then number of path separators (dots) from the last
1939        // match (i.e. favoring classes and deep package names)
1940        var score = 1.0;
1941        var labelLower = result.label.toLowerCase();
1942        var t;
1943        t = _lastSearch(labelLower, partExactAlnumRE);
1944        if (t >= 0) {
1945            // exact part match
1946            var partsAfter = _countChar(labelLower.substr(t + 1), '.');
1947            score *= 200 / (partsAfter + 1);
1948        } else {
1949            t = _lastSearch(labelLower, partPrefixAlnumRE);
1950            if (t >= 0) {
1951                // part prefix match
1952                var partsAfter = _countChar(labelLower.substr(t + 1), '.');
1953                score *= 20 / (partsAfter + 1);
1954            }
1955        }
1956
1957        return score;
1958    };
1959
1960    for (var i=0; i<matches.length; i++) {
1961        // if the API is deprecated, default score is 0; otherwise, perform scoring
1962        if (matches[i].deprecated == "true") {
1963          matches[i].__resultScore = 0;
1964        } else {
1965          matches[i].__resultScore = _resultScoreFn(matches[i]);
1966        }
1967    }
1968
1969    matches.sort(function(a,b){
1970        var n = b.__resultScore - a.__resultScore;
1971        if (n == 0) // lexicographical sort if scores are the same
1972            n = (a.label < b.label) ? -1 : 1;
1973        return n;
1974    });
1975}
1976
1977/* Add emphasis to part of string that matches query */
1978function highlight_autocomplete_result_labels(query) {
1979    query = query || '';
1980    if ((!gMatches || !gMatches.length) && (!gGoogleMatches || !gGoogleMatches.length))
1981      return;
1982
1983    var queryLower = query.toLowerCase();
1984    var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
1985    var queryRE = new RegExp(
1986        '(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
1987    for (var i=0; i<gMatches.length; i++) {
1988        gMatches[i].__hilabel = gMatches[i].label.replace(
1989            queryRE, '<b>$1</b>');
1990    }
1991    for (var i=0; i<gGoogleMatches.length; i++) {
1992        gGoogleMatches[i].__hilabel = gGoogleMatches[i].label.replace(
1993            queryRE, '<b>$1</b>');
1994    }
1995}
1996
1997function search_focus_changed(obj, focused)
1998{
1999    if (!focused) {
2000        if(obj.value == ""){
2001          $(".search .close").addClass("hide");
2002        }
2003        $(".suggest-card").hide();
2004    }
2005}
2006
2007function submit_search() {
2008  var query = document.getElementById('search_autocomplete').value;
2009  location.hash = 'q=' + query;
2010  loadSearchResults();
2011  $("#searchResults").slideDown('slow');
2012  return false;
2013}
2014
2015
2016function hideResults() {
2017  $("#searchResults").slideUp();
2018  $(".search .close").addClass("hide");
2019  location.hash = '';
2020
2021  $("#search_autocomplete").val("").blur();
2022
2023  // reset the ajax search callback to nothing, so results don't appear unless ENTER
2024  searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
2025
2026  // forcefully regain key-up event control (previously jacked by search api)
2027  $("#search_autocomplete").keyup(function(event) {
2028    return search_changed(event, false, toRoot);
2029  });
2030
2031  return false;
2032}
2033
2034
2035
2036/* ########################################################## */
2037/* ################  CUSTOM SEARCH ENGINE  ################## */
2038/* ########################################################## */
2039
2040var searchControl;
2041google.load('search', '1', {"callback" : function() {
2042            searchControl = new google.search.SearchControl();
2043          } });
2044
2045function loadSearchResults() {
2046  document.getElementById("search_autocomplete").style.color = "#000";
2047
2048  searchControl = new google.search.SearchControl();
2049
2050  // use our existing search form and use tabs when multiple searchers are used
2051  drawOptions = new google.search.DrawOptions();
2052  drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
2053  drawOptions.setInput(document.getElementById("search_autocomplete"));
2054
2055  // configure search result options
2056  searchOptions = new google.search.SearcherOptions();
2057  searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
2058
2059  // configure each of the searchers, for each tab
2060  devSiteSearcher = new google.search.WebSearch();
2061  devSiteSearcher.setUserDefinedLabel("All");
2062  devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
2063
2064  designSearcher = new google.search.WebSearch();
2065  designSearcher.setUserDefinedLabel("Design");
2066  designSearcher.setSiteRestriction("http://developer.android.com/design/");
2067
2068  trainingSearcher = new google.search.WebSearch();
2069  trainingSearcher.setUserDefinedLabel("Training");
2070  trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
2071
2072  guidesSearcher = new google.search.WebSearch();
2073  guidesSearcher.setUserDefinedLabel("Guides");
2074  guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
2075
2076  referenceSearcher = new google.search.WebSearch();
2077  referenceSearcher.setUserDefinedLabel("Reference");
2078  referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
2079
2080  googleSearcher = new google.search.WebSearch();
2081  googleSearcher.setUserDefinedLabel("Google Services");
2082  googleSearcher.setSiteRestriction("http://developer.android.com/google/");
2083
2084  blogSearcher = new google.search.WebSearch();
2085  blogSearcher.setUserDefinedLabel("Blog");
2086  blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
2087
2088  // add each searcher to the search control
2089  searchControl.addSearcher(devSiteSearcher, searchOptions);
2090  searchControl.addSearcher(designSearcher, searchOptions);
2091  searchControl.addSearcher(trainingSearcher, searchOptions);
2092  searchControl.addSearcher(guidesSearcher, searchOptions);
2093  searchControl.addSearcher(referenceSearcher, searchOptions);
2094  searchControl.addSearcher(googleSearcher, searchOptions);
2095  searchControl.addSearcher(blogSearcher, searchOptions);
2096
2097  // configure result options
2098  searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
2099  searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
2100  searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
2101  searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
2102
2103  // upon ajax search, refresh the url and search title
2104  searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
2105    updateResultTitle(query);
2106    var query = document.getElementById('search_autocomplete').value;
2107    location.hash = 'q=' + query;
2108  });
2109
2110  // once search results load, set up click listeners
2111  searchControl.setSearchCompleteCallback(this, function(control, searcher, query) {
2112    addResultClickListeners();
2113  });
2114
2115  // draw the search results box
2116  searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
2117
2118  // get query and execute the search
2119  searchControl.execute(decodeURI(getQuery(location.hash)));
2120
2121  document.getElementById("search_autocomplete").focus();
2122  addTabListeners();
2123}
2124// End of loadSearchResults
2125
2126
2127google.setOnLoadCallback(function(){
2128  if (location.hash.indexOf("q=") == -1) {
2129    // if there's no query in the url, don't search and make sure results are hidden
2130    $('#searchResults').hide();
2131    return;
2132  } else {
2133    // first time loading search results for this page
2134    $('#searchResults').slideDown('slow');
2135    $(".search .close").removeClass("hide");
2136    loadSearchResults();
2137  }
2138}, true);
2139
2140// when an event on the browser history occurs (back, forward, load) requery hash and do search
2141$(window).hashchange( function(){
2142  // Exit if the hash isn't a search query or there's an error in the query
2143  if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
2144    // If the results pane is open, close it.
2145    if (!$("#searchResults").is(":hidden")) {
2146      hideResults();
2147    }
2148    return;
2149  }
2150
2151  // Otherwise, we have a search to do
2152  var query = decodeURI(getQuery(location.hash));
2153  searchControl.execute(query);
2154  $('#searchResults').slideDown('slow');
2155  $("#search_autocomplete").focus();
2156  $(".search .close").removeClass("hide");
2157
2158  updateResultTitle(query);
2159});
2160
2161function updateResultTitle(query) {
2162  $("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
2163}
2164
2165// forcefully regain key-up event control (previously jacked by search api)
2166$("#search_autocomplete").keyup(function(event) {
2167  return search_changed(event, false, toRoot);
2168});
2169
2170// add event listeners to each tab so we can track the browser history
2171function addTabListeners() {
2172  var tabHeaders = $(".gsc-tabHeader");
2173  for (var i = 0; i < tabHeaders.length; i++) {
2174    $(tabHeaders[i]).attr("id",i).click(function() {
2175    /*
2176      // make a copy of the page numbers for the search left pane
2177      setTimeout(function() {
2178        // remove any residual page numbers
2179        $('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
2180        // move the page numbers to the left position; make a clone,
2181        // because the element is drawn to the DOM only once
2182        // and because we're going to remove it (previous line),
2183        // we need it to be available to move again as the user navigates
2184        $('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
2185                        .clone().appendTo('#searchResults .gsc-tabsArea');
2186        }, 200);
2187      */
2188    });
2189  }
2190  setTimeout(function(){$(tabHeaders[0]).click()},200);
2191}
2192
2193// add analytics tracking events to each result link
2194function addResultClickListeners() {
2195  $("#searchResults a.gs-title").each(function(index, link) {
2196    // When user clicks enter for Google search results, track it
2197    $(link).click(function() {
2198      _gaq.push(['_trackEvent', 'Google Click', 'clicked: ' + $(this).text(),
2199                'from: ' + $("#search_autocomplete").val()]);
2200    });
2201  });
2202}
2203
2204
2205function getQuery(hash) {
2206  var queryParts = hash.split('=');
2207  return queryParts[1];
2208}
2209
2210/* returns the given string with all HTML brackets converted to entities
2211    TODO: move this to the site's JS library */
2212function escapeHTML(string) {
2213  return string.replace(/</g,"&lt;")
2214                .replace(/>/g,"&gt;");
2215}
2216
2217
2218
2219
2220
2221
2222
2223/* ######################################################## */
2224/* #################  JAVADOC REFERENCE ################### */
2225/* ######################################################## */
2226
2227/* Initialize some droiddoc stuff, but only if we're in the reference */
2228if (location.pathname.indexOf("/reference") == 0) {
2229  if(!(location.pathname.indexOf("/reference-gms/packages.html") == 0)
2230    && !(location.pathname.indexOf("/reference-gcm/packages.html") == 0)
2231    && !(location.pathname.indexOf("/reference/com/google") == 0)) {
2232    $(document).ready(function() {
2233      // init available apis based on user pref
2234      changeApiLevel();
2235      initSidenavHeightResize()
2236      });
2237  }
2238}
2239
2240var API_LEVEL_COOKIE = "api_level";
2241var minLevel = 1;
2242var maxLevel = 1;
2243
2244/******* SIDENAV DIMENSIONS ************/
2245
2246  function initSidenavHeightResize() {
2247    // Change the drag bar size to nicely fit the scrollbar positions
2248    var $dragBar = $(".ui-resizable-s");
2249    $dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
2250
2251    $( "#resize-packages-nav" ).resizable({
2252      containment: "#nav-panels",
2253      handles: "s",
2254      alsoResize: "#packages-nav",
2255      resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
2256      stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie  */
2257      });
2258
2259  }
2260
2261function updateSidenavFixedWidth() {
2262  if (!navBarIsFixed) return;
2263  $('#devdoc-nav').css({
2264    'width' : $('#side-nav').css('width'),
2265    'margin' : $('#side-nav').css('margin')
2266  });
2267  $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
2268
2269  initSidenavHeightResize();
2270}
2271
2272function updateSidenavFullscreenWidth() {
2273  if (!navBarIsFixed) return;
2274  $('#devdoc-nav').css({
2275    'width' : $('#side-nav').css('width'),
2276    'margin' : $('#side-nav').css('margin')
2277  });
2278  $('#devdoc-nav .totop').css({'left': 'inherit'});
2279
2280  initSidenavHeightResize();
2281}
2282
2283function buildApiLevelSelector() {
2284  maxLevel = SINCE_DATA.length;
2285  var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
2286  userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
2287
2288  minLevel = parseInt($("#doc-api-level").attr("class"));
2289  // Handle provisional api levels; the provisional level will always be the highest possible level
2290  // Provisional api levels will also have a length; other stuff that's just missing a level won't,
2291  // so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
2292  if (isNaN(minLevel) && minLevel.length) {
2293    minLevel = maxLevel;
2294  }
2295  var select = $("#apiLevelSelector").html("").change(changeApiLevel);
2296  for (var i = maxLevel-1; i >= 0; i--) {
2297    var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
2298  //  if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
2299    select.append(option);
2300  }
2301
2302  // get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
2303  var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
2304  selectedLevelItem.setAttribute('selected',true);
2305}
2306
2307function changeApiLevel() {
2308  maxLevel = SINCE_DATA.length;
2309  var selectedLevel = maxLevel;
2310
2311  selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
2312  toggleVisisbleApis(selectedLevel, "body");
2313
2314  var date = new Date();
2315  date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
2316  var expiration = date.toGMTString();
2317  writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
2318
2319  if (selectedLevel < minLevel) {
2320    var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
2321    $("#naMessage").show().html("<div><p><strong>This " + thing
2322              + " requires API level " + minLevel + " or higher.</strong></p>"
2323              + "<p>This document is hidden because your selected API level for the documentation is "
2324              + selectedLevel + ". You can change the documentation API level with the selector "
2325              + "above the left navigation.</p>"
2326              + "<p>For more information about specifying the API level your app requires, "
2327              + "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
2328              + ">Supporting Different Platform Versions</a>.</p>"
2329              + "<input type='button' value='OK, make this page visible' "
2330              + "title='Change the API level to " + minLevel + "' "
2331              + "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
2332              + "</div>");
2333  } else {
2334    $("#naMessage").hide();
2335  }
2336}
2337
2338function toggleVisisbleApis(selectedLevel, context) {
2339  var apis = $(".api",context);
2340  apis.each(function(i) {
2341    var obj = $(this);
2342    var className = obj.attr("class");
2343    var apiLevelIndex = className.lastIndexOf("-")+1;
2344    var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
2345    apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
2346    var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
2347    if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
2348      return;
2349    }
2350    apiLevel = parseInt(apiLevel);
2351
2352    // Handle provisional api levels; if this item's level is the provisional one, set it to the max
2353    var selectedLevelNum = parseInt(selectedLevel)
2354    var apiLevelNum = parseInt(apiLevel);
2355    if (isNaN(apiLevelNum)) {
2356        apiLevelNum = maxLevel;
2357    }
2358
2359    // Grey things out that aren't available and give a tooltip title
2360    if (apiLevelNum > selectedLevelNum) {
2361      obj.addClass("absent").attr("title","Requires API Level \""
2362            + apiLevel + "\" or higher");
2363    }
2364    else obj.removeClass("absent").removeAttr("title");
2365  });
2366}
2367
2368
2369
2370
2371/* #################  SIDENAV TREE VIEW ################### */
2372
2373function new_node(me, mom, text, link, children_data, api_level)
2374{
2375  var node = new Object();
2376  node.children = Array();
2377  node.children_data = children_data;
2378  node.depth = mom.depth + 1;
2379
2380  node.li = document.createElement("li");
2381  mom.get_children_ul().appendChild(node.li);
2382
2383  node.label_div = document.createElement("div");
2384  node.label_div.className = "label";
2385  if (api_level != null) {
2386    $(node.label_div).addClass("api");
2387    $(node.label_div).addClass("api-level-"+api_level);
2388  }
2389  node.li.appendChild(node.label_div);
2390
2391  if (children_data != null) {
2392    node.expand_toggle = document.createElement("a");
2393    node.expand_toggle.href = "javascript:void(0)";
2394    node.expand_toggle.onclick = function() {
2395          if (node.expanded) {
2396            $(node.get_children_ul()).slideUp("fast");
2397            node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
2398            node.expanded = false;
2399          } else {
2400            expand_node(me, node);
2401          }
2402       };
2403    node.label_div.appendChild(node.expand_toggle);
2404
2405    node.plus_img = document.createElement("img");
2406    node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
2407    node.plus_img.className = "plus";
2408    node.plus_img.width = "8";
2409    node.plus_img.border = "0";
2410    node.expand_toggle.appendChild(node.plus_img);
2411
2412    node.expanded = false;
2413  }
2414
2415  var a = document.createElement("a");
2416  node.label_div.appendChild(a);
2417  node.label = document.createTextNode(text);
2418  a.appendChild(node.label);
2419  if (link) {
2420    a.href = me.toroot + link;
2421  } else {
2422    if (children_data != null) {
2423      a.className = "nolink";
2424      a.href = "javascript:void(0)";
2425      a.onclick = node.expand_toggle.onclick;
2426      // This next line shouldn't be necessary.  I'll buy a beer for the first
2427      // person who figures out how to remove this line and have the link
2428      // toggle shut on the first try. --joeo@android.com
2429      node.expanded = false;
2430    }
2431  }
2432
2433
2434  node.children_ul = null;
2435  node.get_children_ul = function() {
2436      if (!node.children_ul) {
2437        node.children_ul = document.createElement("ul");
2438        node.children_ul.className = "children_ul";
2439        node.children_ul.style.display = "none";
2440        node.li.appendChild(node.children_ul);
2441      }
2442      return node.children_ul;
2443    };
2444
2445  return node;
2446}
2447
2448
2449
2450
2451function expand_node(me, node)
2452{
2453  if (node.children_data && !node.expanded) {
2454    if (node.children_visited) {
2455      $(node.get_children_ul()).slideDown("fast");
2456    } else {
2457      get_node(me, node);
2458      if ($(node.label_div).hasClass("absent")) {
2459        $(node.get_children_ul()).addClass("absent");
2460      }
2461      $(node.get_children_ul()).slideDown("fast");
2462    }
2463    node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
2464    node.expanded = true;
2465
2466    // perform api level toggling because new nodes are new to the DOM
2467    var selectedLevel = $("#apiLevelSelector option:selected").val();
2468    toggleVisisbleApis(selectedLevel, "#side-nav");
2469  }
2470}
2471
2472function get_node(me, mom)
2473{
2474  mom.children_visited = true;
2475  for (var i in mom.children_data) {
2476    var node_data = mom.children_data[i];
2477    mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
2478        node_data[2], node_data[3]);
2479  }
2480}
2481
2482function this_page_relative(toroot)
2483{
2484  var full = document.location.pathname;
2485  var file = "";
2486  if (toroot.substr(0, 1) == "/") {
2487    if (full.substr(0, toroot.length) == toroot) {
2488      return full.substr(toroot.length);
2489    } else {
2490      // the file isn't under toroot.  Fail.
2491      return null;
2492    }
2493  } else {
2494    if (toroot != "./") {
2495      toroot = "./" + toroot;
2496    }
2497    do {
2498      if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
2499        var pos = full.lastIndexOf("/");
2500        file = full.substr(pos) + file;
2501        full = full.substr(0, pos);
2502        toroot = toroot.substr(0, toroot.length-3);
2503      }
2504    } while (toroot != "" && toroot != "/");
2505    return file.substr(1);
2506  }
2507}
2508
2509function find_page(url, data)
2510{
2511  var nodes = data;
2512  var result = null;
2513  for (var i in nodes) {
2514    var d = nodes[i];
2515    if (d[1] == url) {
2516      return new Array(i);
2517    }
2518    else if (d[2] != null) {
2519      result = find_page(url, d[2]);
2520      if (result != null) {
2521        return (new Array(i).concat(result));
2522      }
2523    }
2524  }
2525  return null;
2526}
2527
2528function init_default_navtree(toroot) {
2529  // load json file for navtree data
2530  $.getScript(toRoot + 'navtree_data.js', function(data, textStatus, jqxhr) {
2531      // when the file is loaded, initialize the tree
2532      if(jqxhr.status === 200) {
2533          init_navtree("tree-list", toroot, NAVTREE_DATA);
2534      }
2535  });
2536
2537  // perform api level toggling because because the whole tree is new to the DOM
2538  var selectedLevel = $("#apiLevelSelector option:selected").val();
2539  toggleVisisbleApis(selectedLevel, "#side-nav");
2540}
2541
2542function init_navtree(navtree_id, toroot, root_nodes)
2543{
2544  var me = new Object();
2545  me.toroot = toroot;
2546  me.node = new Object();
2547
2548  me.node.li = document.getElementById(navtree_id);
2549  me.node.children_data = root_nodes;
2550  me.node.children = new Array();
2551  me.node.children_ul = document.createElement("ul");
2552  me.node.get_children_ul = function() { return me.node.children_ul; };
2553  //me.node.children_ul.className = "children_ul";
2554  me.node.li.appendChild(me.node.children_ul);
2555  me.node.depth = 0;
2556
2557  get_node(me, me.node);
2558
2559  me.this_page = this_page_relative(toroot);
2560  me.breadcrumbs = find_page(me.this_page, root_nodes);
2561  if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
2562    var mom = me.node;
2563    for (var i in me.breadcrumbs) {
2564      var j = me.breadcrumbs[i];
2565      mom = mom.children[j];
2566      expand_node(me, mom);
2567    }
2568    mom.label_div.className = mom.label_div.className + " selected";
2569    addLoadEvent(function() {
2570      scrollIntoView("nav-tree");
2571      });
2572  }
2573}
2574
2575
2576
2577
2578
2579
2580
2581
2582/* TODO: eliminate redundancy with non-google functions */
2583function init_google_navtree(navtree_id, toroot, root_nodes)
2584{
2585  var me = new Object();
2586  me.toroot = toroot;
2587  me.node = new Object();
2588
2589  me.node.li = document.getElementById(navtree_id);
2590  me.node.children_data = root_nodes;
2591  me.node.children = new Array();
2592  me.node.children_ul = document.createElement("ul");
2593  me.node.get_children_ul = function() { return me.node.children_ul; };
2594  //me.node.children_ul.className = "children_ul";
2595  me.node.li.appendChild(me.node.children_ul);
2596  me.node.depth = 0;
2597
2598  get_google_node(me, me.node);
2599}
2600
2601function new_google_node(me, mom, text, link, children_data, api_level)
2602{
2603  var node = new Object();
2604  var child;
2605  node.children = Array();
2606  node.children_data = children_data;
2607  node.depth = mom.depth + 1;
2608  node.get_children_ul = function() {
2609      if (!node.children_ul) {
2610        node.children_ul = document.createElement("ul");
2611        node.children_ul.className = "tree-list-children";
2612        node.li.appendChild(node.children_ul);
2613      }
2614      return node.children_ul;
2615    };
2616  node.li = document.createElement("li");
2617
2618  mom.get_children_ul().appendChild(node.li);
2619
2620
2621  if(link) {
2622    child = document.createElement("a");
2623
2624  }
2625  else {
2626    child = document.createElement("span");
2627    child.className = "tree-list-subtitle";
2628
2629  }
2630  if (children_data != null) {
2631    node.li.className="nav-section";
2632    node.label_div = document.createElement("div");
2633    node.label_div.className = "nav-section-header-ref";
2634    node.li.appendChild(node.label_div);
2635    get_google_node(me, node);
2636    node.label_div.appendChild(child);
2637  }
2638  else {
2639    node.li.appendChild(child);
2640  }
2641  if(link) {
2642    child.href = me.toroot + link;
2643  }
2644  node.label = document.createTextNode(text);
2645  child.appendChild(node.label);
2646
2647  node.children_ul = null;
2648
2649  return node;
2650}
2651
2652function get_google_node(me, mom)
2653{
2654  mom.children_visited = true;
2655  var linkText;
2656  for (var i in mom.children_data) {
2657    var node_data = mom.children_data[i];
2658    linkText = node_data[0];
2659
2660    if(linkText.match("^"+"com.google.android")=="com.google.android"){
2661      linkText = linkText.substr(19, linkText.length);
2662    }
2663      mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
2664          node_data[2], node_data[3]);
2665  }
2666}
2667function showGoogleRefTree() {
2668  init_default_google_navtree(toRoot);
2669  init_default_gcm_navtree(toRoot);
2670}
2671
2672function init_default_google_navtree(toroot) {
2673  // load json file for navtree data
2674  $.getScript(toRoot + 'gms_navtree_data.js', function(data, textStatus, jqxhr) {
2675      // when the file is loaded, initialize the tree
2676      if(jqxhr.status === 200) {
2677          init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
2678          highlightSidenav();
2679          resizeNav();
2680      }
2681  });
2682}
2683
2684function init_default_gcm_navtree(toroot) {
2685  // load json file for navtree data
2686  $.getScript(toRoot + 'gcm_navtree_data.js', function(data, textStatus, jqxhr) {
2687      // when the file is loaded, initialize the tree
2688      if(jqxhr.status === 200) {
2689          init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
2690          highlightSidenav();
2691          resizeNav();
2692      }
2693  });
2694}
2695
2696function showSamplesRefTree() {
2697  init_default_samples_navtree(toRoot);
2698}
2699
2700function init_default_samples_navtree(toroot) {
2701  // load json file for navtree data
2702  $.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
2703      // when the file is loaded, initialize the tree
2704      if(jqxhr.status === 200) {
2705          init_google_navtree("samples-tree-list", toroot, SAMPLES_NAVTREE_DATA);
2706          highlightSidenav();
2707          resizeNav();
2708      }
2709  });
2710}
2711
2712/* TOGGLE INHERITED MEMBERS */
2713
2714/* Toggle an inherited class (arrow toggle)
2715 * @param linkObj  The link that was clicked.
2716 * @param expand  'true' to ensure it's expanded. 'false' to ensure it's closed.
2717 *                'null' to simply toggle.
2718 */
2719function toggleInherited(linkObj, expand) {
2720    var base = linkObj.getAttribute("id");
2721    var list = document.getElementById(base + "-list");
2722    var summary = document.getElementById(base + "-summary");
2723    var trigger = document.getElementById(base + "-trigger");
2724    var a = $(linkObj);
2725    if ( (expand == null && a.hasClass("closed")) || expand ) {
2726        list.style.display = "none";
2727        summary.style.display = "block";
2728        trigger.src = toRoot + "assets/images/triangle-opened.png";
2729        a.removeClass("closed");
2730        a.addClass("opened");
2731    } else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
2732        list.style.display = "block";
2733        summary.style.display = "none";
2734        trigger.src = toRoot + "assets/images/triangle-closed.png";
2735        a.removeClass("opened");
2736        a.addClass("closed");
2737    }
2738    return false;
2739}
2740
2741/* Toggle all inherited classes in a single table (e.g. all inherited methods)
2742 * @param linkObj  The link that was clicked.
2743 * @param expand  'true' to ensure it's expanded. 'false' to ensure it's closed.
2744 *                'null' to simply toggle.
2745 */
2746function toggleAllInherited(linkObj, expand) {
2747  var a = $(linkObj);
2748  var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
2749  var expandos = $(".jd-expando-trigger", table);
2750  if ( (expand == null && a.text() == "[Expand]") || expand ) {
2751    expandos.each(function(i) {
2752      toggleInherited(this, true);
2753    });
2754    a.text("[Collapse]");
2755  } else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
2756    expandos.each(function(i) {
2757      toggleInherited(this, false);
2758    });
2759    a.text("[Expand]");
2760  }
2761  return false;
2762}
2763
2764/* Toggle all inherited members in the class (link in the class title)
2765 */
2766function toggleAllClassInherited() {
2767  var a = $("#toggleAllClassInherited"); // get toggle link from class title
2768  var toggles = $(".toggle-all", $("#body-content"));
2769  if (a.text() == "[Expand All]") {
2770    toggles.each(function(i) {
2771      toggleAllInherited(this, true);
2772    });
2773    a.text("[Collapse All]");
2774  } else {
2775    toggles.each(function(i) {
2776      toggleAllInherited(this, false);
2777    });
2778    a.text("[Expand All]");
2779  }
2780  return false;
2781}
2782
2783/* Expand all inherited members in the class. Used when initiating page search */
2784function ensureAllInheritedExpanded() {
2785  var toggles = $(".toggle-all", $("#body-content"));
2786  toggles.each(function(i) {
2787    toggleAllInherited(this, true);
2788  });
2789  $("#toggleAllClassInherited").text("[Collapse All]");
2790}
2791
2792
2793/* HANDLE KEY EVENTS
2794 * - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
2795 */
2796var agent = navigator['userAgent'].toLowerCase();
2797var mac = agent.indexOf("macintosh") != -1;
2798
2799$(document).keydown( function(e) {
2800var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
2801  if (control && e.which == 70) {  // 70 is "F"
2802    ensureAllInheritedExpanded();
2803  }
2804});
2805