blob: 1f21ae37f378f2eac271b7a4502c24dfdda9fbc2 [file] [log] [blame]
Scott Maine4d8f1b2012-06-21 18:03:05 -07001var classesNav;
2var devdocNav;
3var sidenav;
4var cookie_namespace = 'android_developer';
5var NAV_PREF_TREE = "tree";
6var NAV_PREF_PANELS = "panels";
7var nav_pref;
Scott Maine4d8f1b2012-06-21 18:03:05 -07008var isMobile = false; // true if mobile, so we can adjust some layout
Scott Mainf6145542013-04-01 16:38:11 -07009var mPagePath; // initialized in ready() function
Scott Maine4d8f1b2012-06-21 18:03:05 -070010
Scott Main1b3db112012-07-03 14:06:22 -070011var basePath = getBaseUri(location.pathname);
12var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
Scott Main7e447ed2013-02-19 17:22:37 -080013var GOOGLE_DATA; // combined data for google service apis, used for search suggest
Scott Main3b90aff2013-08-01 18:09:35 -070014
Scott Main25e73002013-03-27 15:24:06 -070015// Ensure that all ajax getScript() requests allow caching
16$.ajaxSetup({
17 cache: true
18});
Scott Maine4d8f1b2012-06-21 18:03:05 -070019
20/****** ON LOAD SET UP STUFF *********/
21
22var navBarIsFixed = false;
23$(document).ready(function() {
Scott Main7e447ed2013-02-19 17:22:37 -080024
Scott Main0e76e7e2013-03-12 10:24:07 -070025 // load json file for JD doc search suggestions
26 $.getScript(toRoot + 'reference/jd_lists.js');
Scott Main7e447ed2013-02-19 17:22:37 -080027 // load json file for Android API search suggestions
28 $.getScript(toRoot + 'reference/lists.js');
29 // load json files for Google services API suggestions
Scott Main9f2971d2013-02-26 13:07:41 -080030 $.getScript(toRoot + 'reference/gcm_lists.js', function(data, textStatus, jqxhr) {
Scott Main7e447ed2013-02-19 17:22:37 -080031 // once the GCM json (GCM_DATA) is loaded, load the GMS json (GMS_DATA) and merge the data
32 if(jqxhr.status === 200) {
Scott Main9f2971d2013-02-26 13:07:41 -080033 $.getScript(toRoot + 'reference/gms_lists.js', function(data, textStatus, jqxhr) {
Scott Main7e447ed2013-02-19 17:22:37 -080034 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
Scott Main0e76e7e2013-03-12 10:24:07 -070047 // setup keyboard listener for search shortcut
48 $('body').keyup(function(event) {
49 if (event.which == 191) {
50 $('#search_autocomplete').focus();
51 }
52 });
Scott Main015d6162013-01-29 09:01:52 -080053
Scott Maine4d8f1b2012-06-21 18:03:05 -070054 // 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 });
Scott Main3b90aff2013-08-01 18:09:35 -070062
Scott Maine4d8f1b2012-06-21 18:03:05 -070063 // initialize the divs with custom scrollbars
64 $('.scroll-pane').jScrollPane( {verticalGutter:0} );
Scott Main3b90aff2013-08-01 18:09:35 -070065
Scott Maine4d8f1b2012-06-21 18:03:05 -070066 // add HRs below all H2s (except for a few other h2 variants)
Scott Maindb3678b2012-10-23 14:13:41 -070067 $('h2').not('#qv h2').not('#tb h2').not('.sidebox h2').not('#devdoc-nav h2').not('h2.norule').css({marginBottom:0}).after('<hr/>');
Scott Maine4d8f1b2012-06-21 18:03:05 -070068
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();
Scott Main0e76e7e2013-03-12 10:24:07 -070076 search_focus_changed($searchInput.get(), false);
77 hideResults();
Scott Maine4d8f1b2012-06-21 18:03:05 -070078 });
79
80 // Set up quicknav
Scott Main3b90aff2013-08-01 18:09:35 -070081 var quicknav_open = false;
Scott Maine4d8f1b2012-06-21 18:03:05 -070082 $("#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 })
Scott Main3b90aff2013-08-01 18:09:35 -070093
Scott Maine4d8f1b2012-06-21 18:03:05 -070094 var expand = function() {
95 $('#header-wrap').addClass('quicknav');
96 $('#quicknav').stop().show().animate({opacity:'1'});
97 }
Scott Main3b90aff2013-08-01 18:09:35 -070098
Scott Maine4d8f1b2012-06-21 18:03:05 -070099 var collapse = function() {
100 $('#quicknav').stop().animate({opacity:'0'}, 100, function() {
101 $(this).hide();
102 $('#header-wrap').removeClass('quicknav');
103 });
104 }
Scott Main3b90aff2013-08-01 18:09:35 -0700105
106
Scott Maine4d8f1b2012-06-21 18:03:05 -0700107 //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
Scott Main3b90aff2013-08-01 18:09:35 -0700130
Scott Maine4d8f1b2012-06-21 18:03:05 -0700131 // 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 }
Scott Mainac2aef52013-02-12 14:15:23 -0800137
Scott Maine4d8f1b2012-06-21 18:03:05 -0700138 if (pagePath.indexOf(SITE_ROOT) == 0) {
139 if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
140 pagePath += 'index.html';
141 }
142 }
143
Scott Main01a25452013-02-12 17:32:27 -0800144 // 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;
Scott Maine4d8f1b2012-06-21 18:03:05 -0700147 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
Scott Mainac2aef52013-02-12 14:15:23 -0800166 // 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");
Scott Mainac2aef52013-02-12 14:15:23 -0800174 // In Develop docs, also highlight appropriate sub-tab
Scott Main01a25452013-02-12 17:32:27 -0800175 var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
Scott Mainac2aef52013-02-12 14:15:23 -0800176 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");
Dirk Dougherty4f7e5152010-09-16 10:43:40 -0700191 } else if ($("body").hasClass("samples")) {
192 $("#nav-x li.samples a").addClass("selected");
Scott Mainac2aef52013-02-12 14:15:23 -0800193 }
194
195 // highlight Distribute tab
196 } else if ($("body").hasClass("distribute")) {
197 $("#header li.distribute a").addClass("selected");
198 }
199
Scott Mainf6145542013-04-01 16:38:11 -0700200 // 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();
Scott Mainac2aef52013-02-12 14:15:23 -0800204
Scott Mainf6145542013-04-01 16:38:11 -0700205 // set up prev/next links if they exist
Scott Maine4d8f1b2012-06-21 18:03:05 -0700206 var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
Scott Main5a1123e2012-09-26 12:51:28 -0700207 var $selListItem;
Scott Maine4d8f1b2012-06-21 18:03:05 -0700208 if ($selNavLink.length) {
Scott Mainac2aef52013-02-12 14:15:23 -0800209 $selListItem = $selNavLink.closest('li');
Scott Maine4d8f1b2012-06-21 18:03:05 -0700210
211 // set up prev links
212 var $prevLink = [];
213 var $prevListItem = $selListItem.prev('li');
Scott Main3b90aff2013-08-01 18:09:35 -0700214
Scott Maine4d8f1b2012-06-21 18:03:05 -0700215 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')) {
Scott Main5a1123e2012-09-26 12:51:28 -0700219 // jump to last topic of previous section
220 $prevLink = $prevListItem.find('a:last');
221 } else if (!$selListItem.hasClass('nav-section')) {
Scott Maine4d8f1b2012-06-21 18:03:05 -0700222 // 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');
Scott Main3b90aff2013-08-01 18:09:35 -0700229
Scott Maine4d8f1b2012-06-21 18:03:05 -0700230 // except if cross boundaries aren't allowed, and we're at the top of a section already
231 // (and there's another parent)
Scott Main3b90aff2013-08-01 18:09:35 -0700232 if (!crossBoundaries && $parentListItem.hasClass('nav-section')
Scott Maine4d8f1b2012-06-21 18:03:05 -0700233 && $selListItem.hasClass('nav-section')) {
234 $prevLink = [];
235 }
236 }
237
Scott Maine4d8f1b2012-06-21 18:03:05 -0700238 // set up next links
239 var $nextLink = [];
Scott Maine4d8f1b2012-06-21 18:03:05 -0700240 var startClass = false;
241 var training = $(".next-class-link").length; // decides whether to provide "next class" link
242 var isCrossingBoundary = false;
Scott Main3b90aff2013-08-01 18:09:35 -0700243
Scott Maine4d8f1b2012-06-21 18:03:05 -0700244 if ($selListItem.hasClass('nav-section')) {
245 // we're on an index page, jump to the first topic
Scott Mainb505ca62012-07-26 18:00:14 -0700246 $nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
Scott Maine4d8f1b2012-06-21 18:03:05 -0700247
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');
Scott Mainb505ca62012-07-26 18:00:14 -0700251 } 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());
Scott Maine4d8f1b2012-06-21 18:03:05 -0700255 }
Scott Main3b90aff2013-08-01 18:09:35 -0700256
Scott Main5a1123e2012-09-26 12:51:28 -0700257 // 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
Scott Maine4d8f1b2012-06-21 18:03:05 -0700260 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) {
Scott Main5a1123e2012-09-26 12:51:28 -0700266 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)');
Scott Maine4d8f1b2012-06-21 18:03:05 -0700271 }
272 }
273 }
Scott Main5a1123e2012-09-26 12:51:28 -0700274
275 if (startClass) {
276 $('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
277
Scott Main3b90aff2013-08-01 18:09:35 -0700278 // if there's no training bar (below the start button),
Scott Main5a1123e2012-09-26 12:51:28 -0700279 // then we need to add a bottom border to button
280 if (!$("#tb").length) {
281 $('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
Scott Maine4d8f1b2012-06-21 18:03:05 -0700282 }
Scott Main5a1123e2012-09-26 12:51:28 -0700283 } 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; });
Scott Main3b90aff2013-08-01 18:09:35 -0700288
Scott Main5a1123e2012-09-26 12:51:28 -0700289 $('.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 }
Scott Main3b90aff2013-08-01 18:09:35 -0700303 }
Scott Main5a1123e2012-09-26 12:51:28 -0700304
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; });
Scott Maine4d8f1b2012-06-21 18:03:05 -0700311 }
Scott Main3b90aff2013-08-01 18:09:35 -0700312
Scott Maine4d8f1b2012-06-21 18:03:05 -0700313 }
Scott Main3b90aff2013-08-01 18:09:35 -0700314
315
316
Scott Main5a1123e2012-09-26 12:51:28 -0700317 // 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');
Scott Main3b90aff2013-08-01 18:09:35 -0700321
Scott Main5a1123e2012-09-26 12:51:28 -0700322 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>');
Scott Main3b90aff2013-08-01 18:09:35 -0700333
Scott Main5a1123e2012-09-26 12:51:28 -0700334 $olLessons = $('<ol class="lesson-list"></ol>');
Scott Main3b90aff2013-08-01 18:09:35 -0700335
Scott Main5a1123e2012-09-26 12:51:28 -0700336 $lessons = $(this).closest('li').find('ul li a');
Scott Main3b90aff2013-08-01 18:09:35 -0700337
Scott Main5a1123e2012-09-26 12:51:28 -0700338 if ($lessons.length) {
Scott Main3b90aff2013-08-01 18:09:35 -0700339 $imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" '
340 + ' width="64" height="64" alt=""/>');
Scott Main5a1123e2012-09-26 12:51:28 -0700341 $lessons.each(function(index) {
342 $olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
343 });
344 } else {
Scott Main3b90aff2013-08-01 18:09:35 -0700345 $imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" '
346 + ' width="64" height="64" alt=""/>');
Scott Main5a1123e2012-09-26 12:51:28 -0700347 $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
Scott Maine4d8f1b2012-06-21 18:03:05 -0700356 // Set up expand/collapse behavior
Scott Mainad08f072013-08-20 16:49:57 -0700357 initExpandableNavItems("#nav");
Scott Main3b90aff2013-08-01 18:09:35 -0700358
Scott Main3b90aff2013-08-01 18:09:35 -0700359
Scott Maine4d8f1b2012-06-21 18:03:05 -0700360 $(".scroll-pane").scroll(function(event) {
361 event.preventDefault();
362 return false;
363 });
364
365 /* Resize nav height when window height changes */
366 $(window).resize(function() {
367 if ($('#side-nav').length == 0) return;
368 var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
369 setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
370 // make sidenav behave when resizing the window and side-scolling is a concern
371 if (navBarIsFixed) {
372 if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
373 updateSideNavPosition();
374 } else {
375 updateSidenavFullscreenWidth();
376 }
377 }
378 resizeNav();
379 });
380
381
382 // Set up fixed navbar
383 var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
384 $(window).scroll(function(event) {
385 if ($('#side-nav').length == 0) return;
386 if (event.target.nodeName == "DIV") {
387 // Dump scroll event if the target is a DIV, because that means the event is coming
388 // from a scrollable div and so there's no need to make adjustments to our layout
389 return;
390 }
Scott Main3b90aff2013-08-01 18:09:35 -0700391 var scrollTop = $(window).scrollTop();
Scott Maine4d8f1b2012-06-21 18:03:05 -0700392 var headerHeight = $('#header').outerHeight();
393 var subheaderHeight = $('#nav-x').outerHeight();
Scott Main3b90aff2013-08-01 18:09:35 -0700394 var searchResultHeight = $('#searchResults').is(":visible") ?
Scott Maine4d8f1b2012-06-21 18:03:05 -0700395 $('#searchResults').outerHeight() : 0;
396 var totalHeaderHeight = headerHeight + subheaderHeight + searchResultHeight;
Scott Mainb8d06a52012-12-19 18:38:24 -0800397 // we set the navbar fixed when the scroll position is beyond the height of the site header...
Scott Maine4d8f1b2012-06-21 18:03:05 -0700398 var navBarShouldBeFixed = scrollTop > totalHeaderHeight;
Scott Mainb8d06a52012-12-19 18:38:24 -0800399 // ... except if the document content is shorter than the sidenav height.
400 // (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
401 if ($("#doc-col").height() < $("#side-nav").height()) {
402 navBarShouldBeFixed = false;
403 }
Scott Main3b90aff2013-08-01 18:09:35 -0700404
Scott Maine4d8f1b2012-06-21 18:03:05 -0700405 var scrollLeft = $(window).scrollLeft();
406 // When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
407 if (navBarIsFixed && (scrollLeft != prevScrollLeft)) {
408 updateSideNavPosition();
409 prevScrollLeft = scrollLeft;
410 }
Scott Main3b90aff2013-08-01 18:09:35 -0700411
412 // Don't continue if the header is sufficently far away
Scott Maine4d8f1b2012-06-21 18:03:05 -0700413 // (to avoid intensive resizing that slows scrolling)
414 if (navBarIsFixed && navBarShouldBeFixed) {
415 return;
416 }
Scott Main3b90aff2013-08-01 18:09:35 -0700417
Scott Maine4d8f1b2012-06-21 18:03:05 -0700418 if (navBarIsFixed != navBarShouldBeFixed) {
419 if (navBarShouldBeFixed) {
420 // make it fixed
421 var width = $('#devdoc-nav').width();
422 $('#devdoc-nav')
423 .addClass('fixed')
424 .css({'width':width+'px'})
425 .prependTo('#body-content');
426 // add neato "back to top" button
427 $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
Scott Main3b90aff2013-08-01 18:09:35 -0700428
Scott Maine4d8f1b2012-06-21 18:03:05 -0700429 // update the sidenaav position for side scrolling
430 updateSideNavPosition();
431 } else {
432 // make it static again
433 $('#devdoc-nav')
434 .removeClass('fixed')
435 .css({'width':'auto','margin':''})
436 .prependTo('#side-nav');
437 $('#devdoc-nav a.totop').hide();
438 }
439 navBarIsFixed = navBarShouldBeFixed;
Scott Main3b90aff2013-08-01 18:09:35 -0700440 }
441
Scott Maine4d8f1b2012-06-21 18:03:05 -0700442 resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
443 });
444
Scott Main3b90aff2013-08-01 18:09:35 -0700445
Scott Maine4d8f1b2012-06-21 18:03:05 -0700446 var navBarLeftPos;
447 if ($('#devdoc-nav').length) {
448 setNavBarLeftPos();
449 }
450
451
452 // Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
453 // from the page)
454 $('.nav-section-header').find('a:eq(0)').click(function(evt) {
455 window.location.href = $(this).attr('href');
456 return false;
457 });
458
459 // Set up play-on-hover <video> tags.
460 $('video.play-on-hover').bind('click', function(){
461 $(this).get(0).load(); // in case the video isn't seekable
462 $(this).get(0).play();
463 });
464
465 // Set up tooltips
466 var TOOLTIP_MARGIN = 10;
Scott Maindb3678b2012-10-23 14:13:41 -0700467 $('acronym,.tooltip-link').each(function() {
Scott Maine4d8f1b2012-06-21 18:03:05 -0700468 var $target = $(this);
469 var $tooltip = $('<div>')
470 .addClass('tooltip-box')
Scott Maindb3678b2012-10-23 14:13:41 -0700471 .append($target.attr('title'))
Scott Maine4d8f1b2012-06-21 18:03:05 -0700472 .hide()
473 .appendTo('body');
474 $target.removeAttr('title');
475
476 $target.hover(function() {
477 // in
478 var targetRect = $target.offset();
479 targetRect.width = $target.width();
480 targetRect.height = $target.height();
481
482 $tooltip.css({
483 left: targetRect.left,
484 top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
485 });
486 $tooltip.addClass('below');
487 $tooltip.show();
488 }, function() {
489 // out
490 $tooltip.hide();
491 });
492 });
493
494 // Set up <h2> deeplinks
495 $('h2').click(function() {
496 var id = $(this).attr('id');
497 if (id) {
498 document.location.hash = id;
499 }
500 });
501
502 //Loads the +1 button
503 var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
504 po.src = 'https://apis.google.com/js/plusone.js';
505 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
506
507
Scott Main3b90aff2013-08-01 18:09:35 -0700508 // Revise the sidenav widths to make room for the scrollbar
Scott Maine4d8f1b2012-06-21 18:03:05 -0700509 // which avoids the visible width from changing each time the bar appears
510 var $sidenav = $("#side-nav");
511 var sidenav_width = parseInt($sidenav.innerWidth());
Scott Main3b90aff2013-08-01 18:09:35 -0700512
Scott Maine4d8f1b2012-06-21 18:03:05 -0700513 $("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
514
515
516 $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
Scott Main3b90aff2013-08-01 18:09:35 -0700517
Scott Maine4d8f1b2012-06-21 18:03:05 -0700518 if ($(".scroll-pane").length > 1) {
519 // Check if there's a user preference for the panel heights
520 var cookieHeight = readCookie("reference_height");
521 if (cookieHeight) {
522 restoreHeight(cookieHeight);
523 }
524 }
Scott Main3b90aff2013-08-01 18:09:35 -0700525
Scott Maine4d8f1b2012-06-21 18:03:05 -0700526 resizeNav();
527
Scott Main015d6162013-01-29 09:01:52 -0800528 /* init the language selector based on user cookie for lang */
529 loadLangPref();
530 changeNavLang(getLangPref());
531
532 /* setup event handlers to ensure the overflow menu is visible while picking lang */
533 $("#language select")
534 .mousedown(function() {
535 $("div.morehover").addClass("hover"); })
536 .blur(function() {
537 $("div.morehover").removeClass("hover"); });
538
539 /* some global variable setup */
540 resizePackagesNav = $("#resize-packages-nav");
541 classesNav = $("#classes-nav");
542 devdocNav = $("#devdoc-nav");
543
544 var cookiePath = "";
545 if (location.href.indexOf("/reference/") != -1) {
546 cookiePath = "reference_";
547 } else if (location.href.indexOf("/guide/") != -1) {
548 cookiePath = "guide_";
549 } else if (location.href.indexOf("/tools/") != -1) {
550 cookiePath = "tools_";
551 } else if (location.href.indexOf("/training/") != -1) {
552 cookiePath = "training_";
553 } else if (location.href.indexOf("/design/") != -1) {
554 cookiePath = "design_";
555 } else if (location.href.indexOf("/distribute/") != -1) {
556 cookiePath = "distribute_";
557 }
Scott Maine4d8f1b2012-06-21 18:03:05 -0700558
559});
Scott Main7e447ed2013-02-19 17:22:37 -0800560// END of the onload event
Scott Maine4d8f1b2012-06-21 18:03:05 -0700561
562
Scott Mainad08f072013-08-20 16:49:57 -0700563function initExpandableNavItems(rootTag) {
564 $(rootTag + ' li.nav-section .nav-section-header').click(function() {
565 var section = $(this).closest('li.nav-section');
566 if (section.hasClass('expanded')) {
567 /* hide me */
568 section.children('ul').slideUp(250, function() {
569 section.closest('li').removeClass('expanded');
570 resizeNav();
571 });
572 } else {
573 /* show me */
574 // first hide all other siblings
575 var $others = $('li.nav-section.expanded', $(this).closest('ul'));
576 $others.removeClass('expanded').children('ul').slideUp(250);
577
578 // now expand me
579 section.closest('li').addClass('expanded');
580 section.children('ul').slideDown(250, function() {
581 resizeNav();
582 });
583 }
584 });
585}
586
Scott Mainf6145542013-04-01 16:38:11 -0700587function highlightSidenav() {
588 // select current page in sidenav and header, and set up prev/next links if they exist
589 var $selNavLink = $('#nav').find('a[href="' + mPagePath + '"]');
590 var $selListItem;
591 if ($selNavLink.length) {
592
593 // Find this page's <li> in sidenav and set selected
594 $selListItem = $selNavLink.closest('li');
595 $selListItem.addClass('selected');
Scott Main3b90aff2013-08-01 18:09:35 -0700596
Scott Mainf6145542013-04-01 16:38:11 -0700597 // Traverse up the tree and expand all parent nav-sections
598 $selNavLink.parents('li.nav-section').each(function() {
599 $(this).addClass('expanded');
600 $(this).children('ul').show();
601 });
602 }
603}
604
Scott Maine4d8f1b2012-06-21 18:03:05 -0700605
606function toggleFullscreen(enable) {
607 var delay = 20;
608 var enabled = true;
609 var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
610 if (enable) {
611 // Currently NOT USING fullscreen; enable fullscreen
612 stylesheet.removeAttr('disabled');
613 $('#nav-swap .fullscreen').removeClass('disabled');
614 $('#devdoc-nav').css({left:''});
615 setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
616 enabled = true;
617 } else {
618 // Currently USING fullscreen; disable fullscreen
619 stylesheet.attr('disabled', 'disabled');
620 $('#nav-swap .fullscreen').addClass('disabled');
621 setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
622 enabled = false;
623 }
624 writeCookie("fullscreen", enabled, null, null);
625 setNavBarLeftPos();
626 resizeNav(delay);
627 updateSideNavPosition();
628 setTimeout(initSidenavHeightResize,delay);
629}
630
631
632function setNavBarLeftPos() {
633 navBarLeftPos = $('#body-content').offset().left;
634}
635
636
637function updateSideNavPosition() {
638 var newLeft = $(window).scrollLeft() - navBarLeftPos;
639 $('#devdoc-nav').css({left: -newLeft});
640 $('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
641}
Scott Main3b90aff2013-08-01 18:09:35 -0700642
Scott Maine4d8f1b2012-06-21 18:03:05 -0700643// TODO: use $(document).ready instead
644function addLoadEvent(newfun) {
645 var current = window.onload;
646 if (typeof window.onload != 'function') {
647 window.onload = newfun;
648 } else {
649 window.onload = function() {
650 current();
651 newfun();
652 }
653 }
654}
655
656var agent = navigator['userAgent'].toLowerCase();
657// If a mobile phone, set flag and do mobile setup
658if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
659 (agent.indexOf("blackberry") != -1) ||
660 (agent.indexOf("webos") != -1) ||
661 (agent.indexOf("mini") != -1)) { // opera mini browsers
662 isMobile = true;
663}
664
665
Scott Main498d7102013-08-21 15:47:38 -0700666$(document).ready(function() {
Scott Maine4d8f1b2012-06-21 18:03:05 -0700667 $("pre:not(.no-pretty-print)").addClass("prettyprint");
668 prettyPrint();
Scott Main498d7102013-08-21 15:47:38 -0700669});
Scott Maine4d8f1b2012-06-21 18:03:05 -0700670
Scott Maine4d8f1b2012-06-21 18:03:05 -0700671
672
673
674/* ######### RESIZE THE SIDENAV HEIGHT ########## */
675
676function resizeNav(delay) {
677 var $nav = $("#devdoc-nav");
678 var $window = $(window);
679 var navHeight;
Scott Main3b90aff2013-08-01 18:09:35 -0700680
Scott Maine4d8f1b2012-06-21 18:03:05 -0700681 // Get the height of entire window and the total header height.
682 // Then figure out based on scroll position whether the header is visible
683 var windowHeight = $window.height();
684 var scrollTop = $window.scrollTop();
685 var headerHeight = $('#header').outerHeight();
686 var subheaderHeight = $('#nav-x').outerHeight();
687 var headerVisible = (scrollTop < (headerHeight + subheaderHeight));
Scott Main3b90aff2013-08-01 18:09:35 -0700688
689 // get the height of space between nav and top of window.
Scott Maine4d8f1b2012-06-21 18:03:05 -0700690 // Could be either margin or top position, depending on whether the nav is fixed.
Scott Main3b90aff2013-08-01 18:09:35 -0700691 var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
Scott Maine4d8f1b2012-06-21 18:03:05 -0700692 // add 1 for the #side-nav bottom margin
Scott Main3b90aff2013-08-01 18:09:35 -0700693
Scott Maine4d8f1b2012-06-21 18:03:05 -0700694 // Depending on whether the header is visible, set the side nav's height.
695 if (headerVisible) {
696 // The sidenav height grows as the header goes off screen
697 navHeight = windowHeight - (headerHeight + subheaderHeight - scrollTop) - topMargin;
698 } else {
699 // Once header is off screen, the nav height is almost full window height
700 navHeight = windowHeight - topMargin;
701 }
Scott Main3b90aff2013-08-01 18:09:35 -0700702
703
704
Scott Maine4d8f1b2012-06-21 18:03:05 -0700705 $scrollPanes = $(".scroll-pane");
706 if ($scrollPanes.length > 1) {
707 // subtract the height of the api level widget and nav swapper from the available nav height
708 navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
Scott Main3b90aff2013-08-01 18:09:35 -0700709
Scott Maine4d8f1b2012-06-21 18:03:05 -0700710 $("#swapper").css({height:navHeight + "px"});
711 if ($("#nav-tree").is(":visible")) {
712 $("#nav-tree").css({height:navHeight});
713 }
Scott Main3b90aff2013-08-01 18:09:35 -0700714
715 var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
Scott Maine4d8f1b2012-06-21 18:03:05 -0700716 //subtract 10px to account for drag bar
Scott Main3b90aff2013-08-01 18:09:35 -0700717
718 // if the window becomes small enough to make the class panel height 0,
Scott Maine4d8f1b2012-06-21 18:03:05 -0700719 // then the package panel should begin to shrink
720 if (parseInt(classesHeight) <= 0) {
721 $("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
722 $("#packages-nav").css({height:navHeight - 10});
723 }
Scott Main3b90aff2013-08-01 18:09:35 -0700724
Scott Maine4d8f1b2012-06-21 18:03:05 -0700725 $("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
726 $("#classes-nav .jspContainer").css({height:classesHeight});
Scott Main3b90aff2013-08-01 18:09:35 -0700727
728
Scott Maine4d8f1b2012-06-21 18:03:05 -0700729 } else {
730 $nav.height(navHeight);
731 }
Scott Main3b90aff2013-08-01 18:09:35 -0700732
Scott Maine4d8f1b2012-06-21 18:03:05 -0700733 if (delay) {
734 updateFromResize = true;
735 delayedReInitScrollbars(delay);
736 } else {
737 reInitScrollbars();
738 }
Scott Main3b90aff2013-08-01 18:09:35 -0700739
Scott Maine4d8f1b2012-06-21 18:03:05 -0700740}
741
742var updateScrollbars = false;
743var updateFromResize = false;
744
745/* Re-initialize the scrollbars to account for changed nav size.
746 * This method postpones the actual update by a 1/4 second in order to optimize the
747 * scroll performance while the header is still visible, because re-initializing the
748 * scroll panes is an intensive process.
749 */
750function delayedReInitScrollbars(delay) {
751 // If we're scheduled for an update, but have received another resize request
752 // before the scheduled resize has occured, just ignore the new request
753 // (and wait for the scheduled one).
754 if (updateScrollbars && updateFromResize) {
755 updateFromResize = false;
756 return;
757 }
Scott Main3b90aff2013-08-01 18:09:35 -0700758
Scott Maine4d8f1b2012-06-21 18:03:05 -0700759 // We're scheduled for an update and the update request came from this method's setTimeout
760 if (updateScrollbars && !updateFromResize) {
761 reInitScrollbars();
762 updateScrollbars = false;
763 } else {
764 updateScrollbars = true;
765 updateFromResize = false;
766 setTimeout('delayedReInitScrollbars()',delay);
767 }
768}
769
770/* Re-initialize the scrollbars to account for changed nav size. */
771function reInitScrollbars() {
772 var pane = $(".scroll-pane").each(function(){
773 var api = $(this).data('jsp');
774 if (!api) { setTimeout(reInitScrollbars,300); return;}
775 api.reinitialise( {verticalGutter:0} );
Scott Main3b90aff2013-08-01 18:09:35 -0700776 });
Scott Maine4d8f1b2012-06-21 18:03:05 -0700777 $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
778}
779
780
781/* Resize the height of the nav panels in the reference,
782 * and save the new size to a cookie */
783function saveNavPanels() {
784 var basePath = getBaseUri(location.pathname);
785 var section = basePath.substring(1,basePath.indexOf("/",1));
786 writeCookie("height", resizePackagesNav.css("height"), section, null);
787}
788
789
790
791function restoreHeight(packageHeight) {
792 $("#resize-packages-nav").height(packageHeight);
793 $("#packages-nav").height(packageHeight);
794 // var classesHeight = navHeight - packageHeight;
795 // $("#classes-nav").css({height:classesHeight});
796 // $("#classes-nav .jspContainer").css({height:classesHeight});
797}
798
799
800
801/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
802
803
804
805
806
Scott Main3b90aff2013-08-01 18:09:35 -0700807/** Scroll the jScrollPane to make the currently selected item visible
Scott Maine4d8f1b2012-06-21 18:03:05 -0700808 This is called when the page finished loading. */
809function scrollIntoView(nav) {
810 var $nav = $("#"+nav);
811 var element = $nav.jScrollPane({/* ...settings... */});
812 var api = element.data('jsp');
813
814 if ($nav.is(':visible')) {
815 var $selected = $(".selected", $nav);
Scott Mainbc729572013-07-30 18:00:51 -0700816 if ($selected.length == 0) {
817 // If no selected item found, exit
818 return;
819 }
Scott Main52dd2062013-08-15 12:22:28 -0700820 // get the selected item's offset from its container nav by measuring the item's offset
821 // relative to the document then subtract the container nav's offset relative to the document
822 var selectedOffset = $selected.offset().top - $nav.offset().top;
823 if (selectedOffset > $nav.height() * .8) { // multiply nav height by .8 so we move up the item
824 // if it's more than 80% down the nav
825 // scroll the item up by an amount equal to 80% the container nav's height
826 api.scrollTo(0, selectedOffset - ($nav.height() * .8), false);
Scott Maine4d8f1b2012-06-21 18:03:05 -0700827 }
828 }
829}
830
831
832
833
834
835
836/* Show popup dialogs */
837function showDialog(id) {
838 $dialog = $("#"+id);
839 $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>');
840 $dialog.wrapInner('<div/>');
841 $dialog.removeClass("hide");
842}
843
844
845
846
847
848/* ######### COOKIES! ########## */
849
850function readCookie(cookie) {
851 var myCookie = cookie_namespace+"_"+cookie+"=";
852 if (document.cookie) {
853 var index = document.cookie.indexOf(myCookie);
854 if (index != -1) {
855 var valStart = index + myCookie.length;
856 var valEnd = document.cookie.indexOf(";", valStart);
857 if (valEnd == -1) {
858 valEnd = document.cookie.length;
859 }
860 var val = document.cookie.substring(valStart, valEnd);
861 return val;
862 }
863 }
864 return 0;
865}
866
867function writeCookie(cookie, val, section, expiration) {
868 if (val==undefined) return;
869 section = section == null ? "_" : "_"+section+"_";
870 if (expiration == null) {
871 var date = new Date();
872 date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
873 expiration = date.toGMTString();
874 }
Scott Main3b90aff2013-08-01 18:09:35 -0700875 var cookieValue = cookie_namespace + section + cookie + "=" + val
Scott Maine4d8f1b2012-06-21 18:03:05 -0700876 + "; expires=" + expiration+"; path=/";
877 document.cookie = cookieValue;
878}
879
880/* ######### END COOKIES! ########## */
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
Scott Maind7026f72013-06-17 15:08:49 -0700900/* MISC LIBRARY FUNCTIONS */
Scott Maine4d8f1b2012-06-21 18:03:05 -0700901
902
903
904
905
906function toggle(obj, slide) {
907 var ul = $("ul:first", obj);
908 var li = ul.parent();
909 if (li.hasClass("closed")) {
910 if (slide) {
911 ul.slideDown("fast");
912 } else {
913 ul.show();
914 }
915 li.removeClass("closed");
916 li.addClass("open");
917 $(".toggle-img", li).attr("title", "hide pages");
918 } else {
919 ul.slideUp("fast");
920 li.removeClass("open");
921 li.addClass("closed");
922 $(".toggle-img", li).attr("title", "show pages");
923 }
924}
925
926
Scott Maine4d8f1b2012-06-21 18:03:05 -0700927function buildToggleLists() {
928 $(".toggle-list").each(
929 function(i) {
930 $("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
931 $(this).addClass("closed");
932 });
933}
934
935
936
Scott Maind7026f72013-06-17 15:08:49 -0700937function hideNestedItems(list, toggle) {
938 $list = $(list);
939 // hide nested lists
940 if($list.hasClass('showing')) {
941 $("li ol", $list).hide('fast');
942 $list.removeClass('showing');
943 // show nested lists
944 } else {
945 $("li ol", $list).show('fast');
946 $list.addClass('showing');
947 }
948 $(".more,.less",$(toggle)).toggle();
949}
Scott Maine4d8f1b2012-06-21 18:03:05 -0700950
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/* REFERENCE NAV SWAP */
979
980
981function getNavPref() {
982 var v = readCookie('reference_nav');
983 if (v != NAV_PREF_TREE) {
984 v = NAV_PREF_PANELS;
985 }
986 return v;
987}
988
989function chooseDefaultNav() {
990 nav_pref = getNavPref();
991 if (nav_pref == NAV_PREF_TREE) {
992 $("#nav-panels").toggle();
993 $("#panel-link").toggle();
994 $("#nav-tree").toggle();
995 $("#tree-link").toggle();
996 }
997}
998
999function swapNav() {
1000 if (nav_pref == NAV_PREF_TREE) {
1001 nav_pref = NAV_PREF_PANELS;
1002 } else {
1003 nav_pref = NAV_PREF_TREE;
1004 init_default_navtree(toRoot);
1005 }
1006 var date = new Date();
1007 date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
1008 writeCookie("nav", nav_pref, "reference", date.toGMTString());
1009
1010 $("#nav-panels").toggle();
1011 $("#panel-link").toggle();
1012 $("#nav-tree").toggle();
1013 $("#tree-link").toggle();
Scott Main3b90aff2013-08-01 18:09:35 -07001014
Scott Maine4d8f1b2012-06-21 18:03:05 -07001015 resizeNav();
1016
1017 // Gross nasty hack to make tree view show up upon first swap by setting height manually
1018 $("#nav-tree .jspContainer:visible")
1019 .css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
1020 // Another nasty hack to make the scrollbar appear now that we have height
1021 resizeNav();
Scott Main3b90aff2013-08-01 18:09:35 -07001022
Scott Maine4d8f1b2012-06-21 18:03:05 -07001023 if ($("#nav-tree").is(':visible')) {
1024 scrollIntoView("nav-tree");
1025 } else {
1026 scrollIntoView("packages-nav");
1027 scrollIntoView("classes-nav");
1028 }
1029}
1030
1031
1032
Scott Mainf5089842012-08-14 16:31:07 -07001033/* ############################################ */
Scott Maine4d8f1b2012-06-21 18:03:05 -07001034/* ########## LOCALIZATION ############ */
Scott Mainf5089842012-08-14 16:31:07 -07001035/* ############################################ */
Scott Maine4d8f1b2012-06-21 18:03:05 -07001036
1037function getBaseUri(uri) {
1038 var intlUrl = (uri.substring(0,6) == "/intl/");
1039 if (intlUrl) {
1040 base = uri.substring(uri.indexOf('intl/')+5,uri.length);
1041 base = base.substring(base.indexOf('/')+1, base.length);
1042 //alert("intl, returning base url: /" + base);
1043 return ("/" + base);
1044 } else {
1045 //alert("not intl, returning uri as found.");
1046 return uri;
1047 }
1048}
1049
1050function requestAppendHL(uri) {
1051//append "?hl=<lang> to an outgoing request (such as to blog)
1052 var lang = getLangPref();
1053 if (lang) {
1054 var q = 'hl=' + lang;
1055 uri += '?' + q;
1056 window.location = uri;
1057 return false;
1058 } else {
1059 return true;
1060 }
1061}
1062
1063
Scott Maine4d8f1b2012-06-21 18:03:05 -07001064function changeNavLang(lang) {
Scott Main6eb95f12012-10-02 17:12:23 -07001065 var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
1066 $links.each(function(i){ // for each link with a translation
1067 var $link = $(this);
1068 if (lang != "en") { // No need to worry about English, because a language change invokes new request
1069 // put the desired language from the attribute as the text
1070 $link.text($link.attr(lang+"-lang"))
Scott Maine4d8f1b2012-06-21 18:03:05 -07001071 }
Scott Main6eb95f12012-10-02 17:12:23 -07001072 });
Scott Maine4d8f1b2012-06-21 18:03:05 -07001073}
1074
Scott Main015d6162013-01-29 09:01:52 -08001075function changeLangPref(lang, submit) {
Scott Maine4d8f1b2012-06-21 18:03:05 -07001076 var date = new Date();
Scott Main3b90aff2013-08-01 18:09:35 -07001077 expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000)));
Scott Maine4d8f1b2012-06-21 18:03:05 -07001078 // keep this for 50 years
1079 //alert("expires: " + expires)
1080 writeCookie("pref_lang", lang, null, expires);
Scott Main015d6162013-01-29 09:01:52 -08001081
1082 // ####### TODO: Remove this condition once we're stable on devsite #######
1083 // This condition is only needed if we still need to support legacy GAE server
1084 if (devsite) {
1085 // Switch language when on Devsite server
1086 if (submit) {
1087 $("#setlang").submit();
1088 }
1089 } else {
1090 // Switch language when on legacy GAE server
Scott Main015d6162013-01-29 09:01:52 -08001091 if (submit) {
1092 window.location = getBaseUri(location.pathname);
1093 }
Scott Maine4d8f1b2012-06-21 18:03:05 -07001094 }
1095}
1096
1097function loadLangPref() {
1098 var lang = readCookie("pref_lang");
1099 if (lang != 0) {
1100 $("#language").find("option[value='"+lang+"']").attr("selected",true);
1101 }
1102}
1103
1104function getLangPref() {
1105 var lang = $("#language").find(":selected").attr("value");
1106 if (!lang) {
1107 lang = readCookie("pref_lang");
1108 }
1109 return (lang != 0) ? lang : 'en';
1110}
1111
1112/* ########## END LOCALIZATION ############ */
1113
1114
1115
1116
1117
1118
1119/* Used to hide and reveal supplemental content, such as long code samples.
1120 See the companion CSS in android-developer-docs.css */
1121function toggleContent(obj) {
Scott Maindc63dda2013-08-22 16:03:21 -07001122 var div = $(obj).closest(".toggle-content");
1123 var toggleMe = $(".toggle-content-toggleme:eq(0)",div);
Scott Maine4d8f1b2012-06-21 18:03:05 -07001124 if (div.hasClass("closed")) { // if it's closed, open it
1125 toggleMe.slideDown();
Scott Maindc63dda2013-08-22 16:03:21 -07001126 $(".toggle-content-text:eq(0)", obj).toggle();
Scott Maine4d8f1b2012-06-21 18:03:05 -07001127 div.removeClass("closed").addClass("open");
Scott Maindc63dda2013-08-22 16:03:21 -07001128 $(".toggle-content-img:eq(0)", div).attr("title", "hide").attr("src", toRoot
Scott Maine4d8f1b2012-06-21 18:03:05 -07001129 + "assets/images/triangle-opened.png");
1130 } else { // if it's open, close it
1131 toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
Scott Maindc63dda2013-08-22 16:03:21 -07001132 $(".toggle-content-text:eq(0)", obj).toggle();
Scott Maine4d8f1b2012-06-21 18:03:05 -07001133 div.removeClass("open").addClass("closed");
Scott Maindc63dda2013-08-22 16:03:21 -07001134 div.find(".toggle-content").removeClass("open").addClass("closed")
1135 .find(".toggle-content-toggleme").hide();
Scott Main3b90aff2013-08-01 18:09:35 -07001136 $(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
Scott Maine4d8f1b2012-06-21 18:03:05 -07001137 + "assets/images/triangle-closed.png");
1138 });
1139 }
1140 return false;
1141}
Scott Mainf5089842012-08-14 16:31:07 -07001142
1143
Scott Maindb3678b2012-10-23 14:13:41 -07001144/* 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();
Scott Main55d99832012-11-12 23:03:59 -08001157 $(ids).prev('h4').find('a.expandable').removeClass('expanded');
Scott Maindb3678b2012-10-23 14:13:41 -07001158}
1159
Scott Mainf5089842012-08-14 16:31:07 -07001160
1161
1162
1163
Scott Main3b90aff2013-08-01 18:09:35 -07001164/*
Scott Mainf5089842012-08-14 16:31:07 -07001165 * 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
Scott Maineb410352013-01-14 19:03:40 -08001192 * btnPause: optional identifier for pause button
Scott Mainf5089842012-08-14 16:31:07 -07001193 * 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) {
Scott Main3b90aff2013-08-01 18:09:35 -07001205
Scott Mainf5089842012-08-14 16:31:07 -07001206 //Options - see above
1207 o = $.extend({
1208 btnPrev: null,
1209 btnNext: null,
Scott Maineb410352013-01-14 19:03:40 -08001210 btnPause: null,
Scott Mainf5089842012-08-14 16:31:07 -07001211 auto: true,
1212 speed: 500,
1213 autoTime: 12000,
1214 easing: null,
1215 start: 0,
1216 scroll: 1,
1217 pagination: true
1218
1219 }, o || {});
Scott Main3b90aff2013-08-01 18:09:35 -07001220
1221 //Set up a carousel for each
Scott Mainf5089842012-08-14 16:31:07 -07001222 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);
Scott Main3b90aff2013-08-01 18:09:35 -07001230 var tl = tLi.size();
Scott Mainf5089842012-08-14 16:31:07 -07001231 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");
Scott Main3b90aff2013-08-01 18:09:35 -07001249
Scott Mainf5089842012-08-14 16:31:07 -07001250 //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 }
Scott Main3b90aff2013-08-01 18:09:35 -07001267
Scott Mainf5089842012-08-14 16:31:07 -07001268 //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 });
Scott Maineb410352013-01-14 19:03:40 -08001281
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 });
Scott Main3b90aff2013-08-01 18:09:35 -07001292
Scott Mainf5089842012-08-14 16:31:07 -07001293 //Auto rotation
1294 if(o.auto) startRotateTimer();
Scott Main3b90aff2013-08-01 18:09:35 -07001295
Scott Mainf5089842012-08-14 16:31:07 -07001296 function startRotateTimer() {
1297 clearInterval(timer);
1298 timer = setInterval(function() {
1299 if (curr == tl-1) {
1300 go(0);
1301 } else {
Scott Main3b90aff2013-08-01 18:09:35 -07001302 go(curr+o.scroll);
1303 }
Scott Mainf5089842012-08-14 16:31:07 -07001304 }, o.autoTime);
Scott Maineb410352013-01-14 19:03:40 -08001305 $(o.btnPause).removeClass('paused');
1306 }
1307
1308 function pauseRotateTimer() {
1309 clearInterval(timer);
1310 $(o.btnPause).addClass('paused');
Scott Mainf5089842012-08-14 16:31:07 -07001311 }
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
Scott Main3b90aff2013-08-01 18:09:35 -07001341
Scott Mainf5089842012-08-14 16:31:07 -07001342 var nav_items = $('li', pagination);
1343 nav_items.removeClass('active');
1344 nav_items.eq(to).addClass('active');
Scott Main3b90aff2013-08-01 18:09:35 -07001345
Scott Mainf5089842012-08-14 16:31:07 -07001346
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
Scott Main3b90aff2013-08-01 18:09:35 -07001367/*
Scott Mainf5089842012-08-14 16:31:07 -07001368 * 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) {
Scott Main3b90aff2013-08-01 18:09:35 -07001406
Scott Mainf5089842012-08-14 16:31:07 -07001407 //Options - see above
1408 o = $.extend({
1409 speed : 250,
1410 easing: null,
1411 nav_id: null,
1412 frame_id: null
1413 }, o || {});
Scott Main3b90aff2013-08-01 18:09:35 -07001414
1415 //Set up a carousel for each
Scott Mainf5089842012-08-14 16:31:07 -07001416 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);
Scott Main3b90aff2013-08-01 18:09:35 -07001423
Scott Mainf5089842012-08-14 16:31:07 -07001424 var nav = $(o.nav_id, div);
1425 var nav_li = $("li", nav);
Scott Main3b90aff2013-08-01 18:09:35 -07001426 var nav_size = nav_li.size();
Scott Mainf5089842012-08-14 16:31:07 -07001427 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 })
Scott Main3b90aff2013-08-01 18:09:35 -07001433
Scott Mainf5089842012-08-14 16:31:07 -07001434 //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
Scott Main3b90aff2013-08-01 18:09:35 -07001446
Scott Mainf5089842012-08-14 16:31:07 -07001447 nav_li.removeClass('active');
1448 nav_li.eq(to).addClass('active');
Scott Main3b90aff2013-08-01 18:09:35 -07001449
Scott Mainf5089842012-08-14 16:31:07 -07001450
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
Scott Main7e447ed2013-02-19 17:22:37 -08001478
Scott Main0e76e7e2013-03-12 10:24:07 -07001479var gSelectedIndex = -1; // the index position of currently highlighted suggestion
1480var gSelectedColumn = -1; // which column of suggestion lists is currently focused
1481
Scott Mainf5089842012-08-14 16:31:07 -07001482var gMatches = new Array();
1483var gLastText = "";
Scott Mainf5089842012-08-14 16:31:07 -07001484var gInitialized = false;
Scott Main7e447ed2013-02-19 17:22:37 -08001485var 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;
Scott Mainf5089842012-08-14 16:31:07 -07001492
Scott Main0e76e7e2013-03-12 10:24:07 -07001493var gDocsMatches = new Array();
1494var ROW_COUNT_DOCS = 100; // max number of results in list
1495var gDocsListLength = 0;
1496
Scott Mainde295272013-03-25 15:48:35 -07001497function 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
Scott Mainf5089842012-08-14 16:31:07 -07001503function 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
Scott Main0e76e7e2013-03-12 10:24:07 -07001519function new_suggestion($list) {
Scott Main7e447ed2013-02-19 17:22:37 -08001520 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() {
Scott Main0e76e7e2013-03-12 10:24:07 -07001527 $('.search_filtered_wrapper li').removeClass('jd-selected');
Scott Main7e447ed2013-02-19 17:22:37 -08001528 $(this).addClass('jd-selected');
Scott Main0e76e7e2013-03-12 10:24:07 -07001529 gSelectedColumn = $(".search_filtered:visible").index($(this).closest('.search_filtered'));
1530 gSelectedIndex = $("li", $(".search_filtered:visible")[gSelectedColumn]).index(this);
Scott Main7e447ed2013-02-19 17:22:37 -08001531 });
Scott Mainde295272013-03-25 15:48:35 -07001532 $li.append("<a onclick='onSuggestionClick(this)'></a>");
Scott Main7e447ed2013-02-19 17:22:37 -08001533 $li.attr('class','show-item');
1534 return $li;
1535}
1536
Scott Mainf5089842012-08-14 16:31:07 -07001537function sync_selection_table(toroot)
1538{
Scott Mainf5089842012-08-14 16:31:07 -07001539 var $li; //list item jquery object
1540 var i; //list item iterator
Scott Main7e447ed2013-02-19 17:22:37 -08001541
Scott Main0e76e7e2013-03-12 10:24:07 -07001542 // 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
Scott Main7e447ed2013-02-19 17:22:37 -08001549 if ((gMatches.length > 0) || (gGoogleMatches.length > 0)) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001550 // reveal suggestion list
1551 $('.suggest-card.dummy').show();
1552 $('.suggest-card.reference').show();
1553 var listIndex = 0; // list index position
Scott Main7e447ed2013-02-19 17:22:37 -08001554
Scott Main0e76e7e2013-03-12 10:24:07 -07001555 // reset the lists
1556 $(".search_filtered_wrapper.reference li").remove();
Scott Main7e447ed2013-02-19 17:22:37 -08001557
Scott Main0e76e7e2013-03-12 10:24:07 -07001558 // ########### ANDROID RESULTS #############
1559 if (gMatches.length > 0) {
Scott Main7e447ed2013-02-19 17:22:37 -08001560
Scott Main0e76e7e2013-03-12 10:24:07 -07001561 // 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 }
Scott Main7e447ed2013-02-19 17:22:37 -08001570
Scott Main0e76e7e2013-03-12 10:24:07 -07001571 // ########### 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>");
Scott Main7e447ed2013-02-19 17:22:37 -08001575
Scott Main0e76e7e2013-03-12 10:24:07 -07001576 // 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 }
Scott Mainf5089842012-08-14 16:31:07 -07001584 } else {
Scott Main0e76e7e2013-03-12 10:24:07 -07001585 $('.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);
Scott Mainf5089842012-08-14 16:31:07 -07001648 }
1649}
1650
Scott Main0e76e7e2013-03-12 10:24:07 -07001651/** 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
Scott Main3b90aff2013-08-01 18:09:35 -07001656 * @param toroot A string for the site's root path
Scott Main0e76e7e2013-03-12 10:24:07 -07001657 * @returns True if the event should bubble up
1658 */
Scott Mainf5089842012-08-14 16:31:07 -07001659function search_changed(e, kd, toroot)
1660{
1661 var search = document.getElementById("search_autocomplete");
1662 var text = search.value.replace(/(^ +)|( +$)/g, '');
Scott Main0e76e7e2013-03-12 10:24:07 -07001663 // 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
Scott Mainf5089842012-08-14 16:31:07 -07001668 // show/hide the close button
1669 if (text != '') {
1670 $(".search .close").removeClass("hide");
1671 } else {
1672 $(".search .close").addClass("hide");
1673 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001674 // 27 = esc
1675 if (e.keyCode == 27) {
1676 // close all search results
1677 if (kd) $('.search .close').trigger('click');
1678 return true;
1679 }
Scott Mainf5089842012-08-14 16:31:07 -07001680 // 13 = enter
Scott Main0e76e7e2013-03-12 10:24:07 -07001681 else if (e.keyCode == 13) {
1682 if (gSelectedIndex < 0) {
1683 $('.suggest-card').hide();
Scott Main7e447ed2013-02-19 17:22:37 -08001684 if ($("#searchResults").is(":hidden") && (search.value != "")) {
1685 // if results aren't showing (and text not empty), return true to allow search to execute
Scott Mainf5089842012-08-14 16:31:07 -07001686 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) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001693 // click the link corresponding to selected item
1694 $("a",$("li",$selectedUl)[gSelectedIndex]).get()[0].click();
Scott Mainf5089842012-08-14 16:31:07 -07001695 return false;
1696 }
1697 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001698 // Stop here if Google results are showing
1699 else if ($("#searchResults").is(":visible")) {
1700 return true;
1701 }
1702 // 38 UP ARROW
Scott Mainf5089842012-08-14 16:31:07 -07001703 else if (kd && (e.keyCode == 38)) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001704 // if the next item is a header, skip it
1705 if ($($("li", $selectedUl)[gSelectedIndex-1]).hasClass("header")) {
Scott Mainf5089842012-08-14 16:31:07 -07001706 gSelectedIndex--;
Scott Main7e447ed2013-02-19 17:22:37 -08001707 }
1708 if (gSelectedIndex >= 0) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001709 $('li', $selectedUl).removeClass('jd-selected');
Scott Main7e447ed2013-02-19 17:22:37 -08001710 gSelectedIndex--;
Scott Main0e76e7e2013-03-12 10:24:07 -07001711 $('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 }
Scott Mainf5089842012-08-14 16:31:07 -07001716 }
1717 return false;
1718 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001719 // 40 DOWN ARROW
Scott Mainf5089842012-08-14 16:31:07 -07001720 else if (kd && (e.keyCode == 40)) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001721 // if the next item is a header, skip it
1722 if ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header")) {
Scott Mainf5089842012-08-14 16:31:07 -07001723 gSelectedIndex++;
Scott Main7e447ed2013-02-19 17:22:37 -08001724 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001725 if ((gSelectedIndex < $("li", $selectedUl).length-1) ||
1726 ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header"))) {
1727 $('li', $selectedUl).removeClass('jd-selected');
Scott Main7e447ed2013-02-19 17:22:37 -08001728 gSelectedIndex++;
Scott Main0e76e7e2013-03-12 10:24:07 -07001729 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
Scott Mainf5089842012-08-14 16:31:07 -07001730 }
1731 return false;
1732 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001733 // 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 }
Scott Main3b90aff2013-08-01 18:09:35 -07001750 // set item selected
Scott Main0e76e7e2013-03-12 10:24:07 -07001751 $('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 }
Scott Main3b90aff2013-08-01 18:09:35 -07001768 // set item selected
Scott Main0e76e7e2013-03-12 10:24:07 -07001769 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1770 return false;
1771 }
1772 }
1773
Scott Main7e447ed2013-02-19 17:22:37 -08001774 // if key-up event and not arrow down/up,
1775 // read the search query and add suggestsions to gMatches
Scott Main0e76e7e2013-03-12 10:24:07 -07001776 else if (!kd && (e.keyCode != 40)
1777 && (e.keyCode != 38)
1778 && (e.keyCode != 37)
1779 && (e.keyCode != 39)) {
1780 gSelectedIndex = -1;
Scott Mainf5089842012-08-14 16:31:07 -07001781 gMatches = new Array();
1782 matchedCount = 0;
Scott Main7e447ed2013-02-19 17:22:37 -08001783 gGoogleMatches = new Array();
1784 matchedCountGoogle = 0;
Scott Main0e76e7e2013-03-12 10:24:07 -07001785 gDocsMatches = new Array();
1786 matchedCountDocs = 0;
Scott Main7e447ed2013-02-19 17:22:37 -08001787
1788 // Search for Android matches
Scott Mainf5089842012-08-14 16:31:07 -07001789 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 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001797 rank_autocomplete_api_results(text, gMatches);
Scott Mainf5089842012-08-14 16:31:07 -07001798 for (var i=0; i<gMatches.length; i++) {
1799 var s = gMatches[i];
Scott Main7e447ed2013-02-19 17:22:37 -08001800 }
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++;
Scott Mainf5089842012-08-14 16:31:07 -07001810 }
1811 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001812 rank_autocomplete_api_results(text, gGoogleMatches);
Scott Main7e447ed2013-02-19 17:22:37 -08001813 for (var i=0; i<gGoogleMatches.length; i++) {
1814 var s = gGoogleMatches[i];
1815 }
1816
Scott Mainf5089842012-08-14 16:31:07 -07001817 highlight_autocomplete_result_labels(text);
Scott Main0e76e7e2013-03-12 10:24:07 -07001818
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
Scott Mainf5089842012-08-14 16:31:07 -07001859 sync_selection_table(toroot);
1860 return true; // allow the event to bubble up to the search api
1861 }
1862}
1863
Scott Main0e76e7e2013-03-12 10:24:07 -07001864/* 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
Scott Main7e447ed2013-02-19 17:22:37 -08001901/* Order the result list based on match quality */
Scott Main0e76e7e2013-03-12 10:24:07 -07001902function rank_autocomplete_api_results(query, matches) {
Scott Mainf5089842012-08-14 16:31:07 -07001903 query = query || '';
Scott Main7e447ed2013-02-19 17:22:37 -08001904 if (!matches || !matches.length)
Scott Mainf5089842012-08-14 16:31:07 -07001905 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
Scott Main7e447ed2013-02-19 17:22:37 -08001960 for (var i=0; i<matches.length; i++) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001961 // 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 }
Scott Mainf5089842012-08-14 16:31:07 -07001967 }
1968
Scott Main7e447ed2013-02-19 17:22:37 -08001969 matches.sort(function(a,b){
Scott Mainf5089842012-08-14 16:31:07 -07001970 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
Scott Main7e447ed2013-02-19 17:22:37 -08001977/* Add emphasis to part of string that matches query */
Scott Mainf5089842012-08-14 16:31:07 -07001978function highlight_autocomplete_result_labels(query) {
1979 query = query || '';
Scott Main7e447ed2013-02-19 17:22:37 -08001980 if ((!gMatches || !gMatches.length) && (!gGoogleMatches || !gGoogleMatches.length))
Scott Mainf5089842012-08-14 16:31:07 -07001981 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 }
Scott Main7e447ed2013-02-19 17:22:37 -08001991 for (var i=0; i<gGoogleMatches.length; i++) {
1992 gGoogleMatches[i].__hilabel = gGoogleMatches[i].label.replace(
1993 queryRE, '<b>$1</b>');
1994 }
Scott Mainf5089842012-08-14 16:31:07 -07001995}
1996
1997function search_focus_changed(obj, focused)
1998{
Scott Main3b90aff2013-08-01 18:09:35 -07001999 if (!focused) {
Scott Mainf5089842012-08-14 16:31:07 -07002000 if(obj.value == ""){
2001 $(".search .close").addClass("hide");
2002 }
Scott Main0e76e7e2013-03-12 10:24:07 -07002003 $(".suggest-card").hide();
Scott Mainf5089842012-08-14 16:31:07 -07002004 }
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 = '';
Scott Main3b90aff2013-08-01 18:09:35 -07002020
Scott Mainf5089842012-08-14 16:31:07 -07002021 $("#search_autocomplete").val("").blur();
Scott Main3b90aff2013-08-01 18:09:35 -07002022
Scott Mainf5089842012-08-14 16:31:07 -07002023 // reset the ajax search callback to nothing, so results don't appear unless ENTER
2024 searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
Scott Main0e76e7e2013-03-12 10:24:07 -07002025
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
Scott Mainf5089842012-08-14 16:31:07 -07002031 return false;
2032}
2033
2034
2035
2036/* ########################################################## */
2037/* ################ CUSTOM SEARCH ENGINE ################## */
2038/* ########################################################## */
2039
Scott Mainf5089842012-08-14 16:31:07 -07002040var searchControl;
Scott Main0e76e7e2013-03-12 10:24:07 -07002041google.load('search', '1', {"callback" : function() {
2042 searchControl = new google.search.SearchControl();
2043 } });
Scott Mainf5089842012-08-14 16:31:07 -07002044
2045function loadSearchResults() {
2046 document.getElementById("search_autocomplete").style.color = "#000";
2047
Scott Mainf5089842012-08-14 16:31:07 -07002048 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
Scott Maindf08ada2012-12-03 08:54:37 -08002080 googleSearcher = new google.search.WebSearch();
2081 googleSearcher.setUserDefinedLabel("Google Services");
2082 googleSearcher.setSiteRestriction("http://developer.android.com/google/");
2083
Scott Mainf5089842012-08-14 16:31:07 -07002084 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);
Scott Maindf08ada2012-12-03 08:54:37 -08002094 searchControl.addSearcher(googleSearcher, searchOptions);
Scott Mainf5089842012-08-14 16:31:07 -07002095 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
Scott Mainde295272013-03-25 15:48:35 -07002110 // once search results load, set up click listeners
2111 searchControl.setSearchCompleteCallback(this, function(control, searcher, query) {
2112 addResultClickListeners();
2113 });
2114
Scott Mainf5089842012-08-14 16:31:07 -07002115 // 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();
Scott Main3b90aff2013-08-01 18:09:35 -07002180 // move the page numbers to the left position; make a clone,
Scott Mainf5089842012-08-14 16:31:07 -07002181 // because the element is drawn to the DOM only once
Scott Main3b90aff2013-08-01 18:09:35 -07002182 // and because we're going to remove it (previous line),
2183 // we need it to be available to move again as the user navigates
Scott Mainf5089842012-08-14 16:31:07 -07002184 $('#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
Scott Mainde295272013-03-25 15:48:35 -07002193// 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
Scott Mainf5089842012-08-14 16:31:07 -07002204
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
Scott Main65511c02012-09-07 15:51:32 -07002227/* Initialize some droiddoc stuff, but only if we're in the reference */
Scott Main52dd2062013-08-15 12:22:28 -07002228if (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)) {
Robert Ly67d75f12012-12-03 12:53:42 -08002232 $(document).ready(function() {
2233 // init available apis based on user pref
2234 changeApiLevel();
2235 initSidenavHeightResize()
2236 });
2237 }
Scott Main65511c02012-09-07 15:51:32 -07002238}
Scott Mainf5089842012-08-14 16:31:07 -07002239
2240var API_LEVEL_COOKIE = "api_level";
2241var minLevel = 1;
2242var maxLevel = 1;
2243
2244/******* SIDENAV DIMENSIONS ************/
Scott Main3b90aff2013-08-01 18:09:35 -07002245
Scott Mainf5089842012-08-14 16:31:07 -07002246 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"});
Scott Main3b90aff2013-08-01 18:09:35 -07002250
2251 $( "#resize-packages-nav" ).resizable({
Scott Mainf5089842012-08-14 16:31:07 -07002252 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 });
Scott Main3b90aff2013-08-01 18:09:35 -07002258
Scott Mainf5089842012-08-14 16:31:07 -07002259 }
Scott Main3b90aff2013-08-01 18:09:35 -07002260
Scott Mainf5089842012-08-14 16:31:07 -07002261function 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'});
Scott Main3b90aff2013-08-01 18:09:35 -07002268
Scott Mainf5089842012-08-14 16:31:07 -07002269 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'});
Scott Main3b90aff2013-08-01 18:09:35 -07002279
Scott Mainf5089842012-08-14 16:31:07 -07002280 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";
Scott Main8f24ca82012-11-16 10:34:22 -08002321 $("#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>");
Scott Mainf5089842012-08-14 16:31:07 -07002333 } 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");
Scott Main3b90aff2013-08-01 18:09:35 -07002363 }
Scott Mainf5089842012-08-14 16:31:07 -07002364 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 }
Scott Main3b90aff2013-08-01 18:09:35 -07002432
Scott Mainf5089842012-08-14 16:31:07 -07002433
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
Robert Lyd2dd6e52012-11-29 21:28:48 -08002448
2449
2450
Scott Mainf5089842012-08-14 16:31:07 -07002451function 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");
Scott Main3b90aff2013-08-01 18:09:35 -07002460 }
Scott Mainf5089842012-08-14 16:31:07 -07002461 $(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
Scott Mainf5089842012-08-14 16:31:07 -07002528function init_default_navtree(toroot) {
Scott Main25e73002013-03-27 15:24:06 -07002529 // 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 });
Scott Main3b90aff2013-08-01 18:09:35 -07002536
Scott Mainf5089842012-08-14 16:31:07 -07002537 // 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
Dirk Dougherty4f7e5152010-09-16 10:43:40 -07002575
2576
2577
2578
2579
2580
2581
Robert Lyd2dd6e52012-11-29 21:28:48 -08002582/* 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);
Robert Lyd2dd6e52012-11-29 21:28:48 -08002599}
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) {
Scott Main3b90aff2013-08-01 18:09:35 -07002610 node.children_ul = document.createElement("ul");
2611 node.children_ul.className = "tree-list-children";
Robert Lyd2dd6e52012-11-29 21:28:48 -08002612 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);
Scott Main3b90aff2013-08-01 18:09:35 -07002619
2620
Robert Lyd2dd6e52012-11-29 21:28:48 -08002621 if(link) {
2622 child = document.createElement("a");
2623
2624 }
2625 else {
2626 child = document.createElement("span");
Scott Mainac71b2b2012-11-30 14:40:58 -08002627 child.className = "tree-list-subtitle";
Robert Lyd2dd6e52012-11-29 21:28:48 -08002628
2629 }
2630 if (children_data != null) {
2631 node.li.className="nav-section";
2632 node.label_div = document.createElement("div");
Scott Main3b90aff2013-08-01 18:09:35 -07002633 node.label_div.className = "nav-section-header-ref";
Robert Lyd2dd6e52012-11-29 21:28:48 -08002634 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}
Scott Mainad08f072013-08-20 16:49:57 -07002667
2668
2669
2670
2671
2672
2673/****** NEW version of script to build google and sample navs dynamically ******/
2674// TODO: update Google reference docs to tolerate this new implementation
2675
2676function init_google_navtree2(navtree_id, data)
2677{
2678 var $containerUl = $("#"+navtree_id);
2679 var linkText;
2680 for (var i in data) {
2681 var node_data = data[i];
2682 $containerUl.append(new_google_node2(node_data));
2683 }
2684
2685 initExpandableNavItems("#"+navtree_id);
2686}
2687
2688function new_google_node2(node_data)
2689{
2690 var linkText = node_data[0];
2691 if(linkText.match("^"+"com.google.android")=="com.google.android"){
2692 linkText = linkText.substr(19, linkText.length);
2693 }
2694 var $li = $('<li>');
2695 var $a;
2696 if (node_data[1] != null) {
2697 $a = $('<a href="' + toRoot + node_data[1] + '">' + linkText + '</a>');
2698 } else {
2699 $a = $('<a href="#" onclick="return false;">' + linkText + '/</a>');
2700 }
2701 var $childUl = $('<ul>');
2702 if (node_data[2] != null) {
2703 $li.addClass("nav-section");
2704 $a = $('<div class="nav-section-header">').append($a);
2705 if (node_data[1] == null) $a.addClass('empty');
2706
2707 for (var i in node_data[2]) {
2708 var child_node_data = node_data[2][i];
2709 $childUl.append(new_google_node2(child_node_data));
2710 }
2711 $li.append($childUl);
2712 }
2713 $li.prepend($a);
2714
2715 return $li;
2716}
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
Robert Lyd2dd6e52012-11-29 21:28:48 -08002728function showGoogleRefTree() {
2729 init_default_google_navtree(toRoot);
2730 init_default_gcm_navtree(toRoot);
Robert Lyd2dd6e52012-11-29 21:28:48 -08002731}
2732
2733function init_default_google_navtree(toroot) {
Scott Mainf6145542013-04-01 16:38:11 -07002734 // load json file for navtree data
2735 $.getScript(toRoot + 'gms_navtree_data.js', function(data, textStatus, jqxhr) {
2736 // when the file is loaded, initialize the tree
2737 if(jqxhr.status === 200) {
2738 init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
2739 highlightSidenav();
2740 resizeNav();
2741 }
2742 });
Robert Lyd2dd6e52012-11-29 21:28:48 -08002743}
2744
2745function init_default_gcm_navtree(toroot) {
Scott Mainf6145542013-04-01 16:38:11 -07002746 // load json file for navtree data
2747 $.getScript(toRoot + 'gcm_navtree_data.js', function(data, textStatus, jqxhr) {
2748 // when the file is loaded, initialize the tree
2749 if(jqxhr.status === 200) {
2750 init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
2751 highlightSidenav();
2752 resizeNav();
2753 }
2754 });
Robert Lyd2dd6e52012-11-29 21:28:48 -08002755}
2756
Dirk Dougherty4f7e5152010-09-16 10:43:40 -07002757function showSamplesRefTree() {
2758 init_default_samples_navtree(toRoot);
2759}
2760
2761function init_default_samples_navtree(toroot) {
2762 // load json file for navtree data
2763 $.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
2764 // when the file is loaded, initialize the tree
2765 if(jqxhr.status === 200) {
Scott Mainad08f072013-08-20 16:49:57 -07002766 init_google_navtree2("nav.samples-nav", SAMPLES_NAVTREE_DATA);
Dirk Dougherty4f7e5152010-09-16 10:43:40 -07002767 highlightSidenav();
2768 resizeNav();
2769 }
2770 });
2771}
2772
Scott Mainf5089842012-08-14 16:31:07 -07002773/* TOGGLE INHERITED MEMBERS */
2774
2775/* Toggle an inherited class (arrow toggle)
2776 * @param linkObj The link that was clicked.
2777 * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
2778 * 'null' to simply toggle.
2779 */
2780function toggleInherited(linkObj, expand) {
2781 var base = linkObj.getAttribute("id");
2782 var list = document.getElementById(base + "-list");
2783 var summary = document.getElementById(base + "-summary");
2784 var trigger = document.getElementById(base + "-trigger");
2785 var a = $(linkObj);
2786 if ( (expand == null && a.hasClass("closed")) || expand ) {
2787 list.style.display = "none";
2788 summary.style.display = "block";
2789 trigger.src = toRoot + "assets/images/triangle-opened.png";
2790 a.removeClass("closed");
2791 a.addClass("opened");
2792 } else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
2793 list.style.display = "block";
2794 summary.style.display = "none";
2795 trigger.src = toRoot + "assets/images/triangle-closed.png";
2796 a.removeClass("opened");
2797 a.addClass("closed");
2798 }
2799 return false;
2800}
2801
2802/* Toggle all inherited classes in a single table (e.g. all inherited methods)
2803 * @param linkObj The link that was clicked.
2804 * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
2805 * 'null' to simply toggle.
2806 */
2807function toggleAllInherited(linkObj, expand) {
2808 var a = $(linkObj);
2809 var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
2810 var expandos = $(".jd-expando-trigger", table);
2811 if ( (expand == null && a.text() == "[Expand]") || expand ) {
2812 expandos.each(function(i) {
2813 toggleInherited(this, true);
2814 });
2815 a.text("[Collapse]");
2816 } else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
2817 expandos.each(function(i) {
2818 toggleInherited(this, false);
2819 });
2820 a.text("[Expand]");
2821 }
2822 return false;
2823}
2824
2825/* Toggle all inherited members in the class (link in the class title)
2826 */
2827function toggleAllClassInherited() {
2828 var a = $("#toggleAllClassInherited"); // get toggle link from class title
2829 var toggles = $(".toggle-all", $("#body-content"));
2830 if (a.text() == "[Expand All]") {
2831 toggles.each(function(i) {
2832 toggleAllInherited(this, true);
2833 });
2834 a.text("[Collapse All]");
2835 } else {
2836 toggles.each(function(i) {
2837 toggleAllInherited(this, false);
2838 });
2839 a.text("[Expand All]");
2840 }
2841 return false;
2842}
2843
2844/* Expand all inherited members in the class. Used when initiating page search */
2845function ensureAllInheritedExpanded() {
2846 var toggles = $(".toggle-all", $("#body-content"));
2847 toggles.each(function(i) {
2848 toggleAllInherited(this, true);
2849 });
2850 $("#toggleAllClassInherited").text("[Collapse All]");
2851}
2852
2853
2854/* HANDLE KEY EVENTS
2855 * - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
2856 */
2857var agent = navigator['userAgent'].toLowerCase();
2858var mac = agent.indexOf("macintosh") != -1;
2859
2860$(document).keydown( function(e) {
2861var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
2862 if (control && e.which == 70) { // 70 is "F"
2863 ensureAllInheritedExpanded();
2864 }
2865});
Scott Main498d7102013-08-21 15:47:38 -07002866
2867
2868
2869
2870
2871
2872/* On-demand functions */
2873
2874/** Move sample code line numbers out of PRE block and into non-copyable column */
2875function initCodeLineNumbers() {
2876 var numbers = $("#codesample-block a.number");
2877 if (numbers.length) {
2878 $("#codesample-line-numbers").removeClass("hidden").append(numbers);
2879 }
2880
2881 $(document).ready(function() {
2882 // select entire line when clicked
2883 $("span.code-line").click(function() {
2884 if (!shifted) {
2885 selectText(this);
2886 }
2887 });
2888 // invoke line link on double click
2889 $(".code-line").dblclick(function() {
2890 document.location.hash = $(this).attr('id');
2891 });
2892 // highlight the line when hovering on the number
2893 $("#codesample-line-numbers a.number").mouseover(function() {
2894 var id = $(this).attr('href');
2895 $(id).css('background','#e7e7e7');
2896 });
2897 $("#codesample-line-numbers a.number").mouseout(function() {
2898 var id = $(this).attr('href');
2899 $(id).css('background','none');
2900 });
2901 });
2902}
2903
2904// create SHIFT key binder to avoid the selectText method when selecting multiple lines
2905var shifted = false;
2906$(document).bind('keyup keydown', function(e){shifted = e.shiftKey; return true;} );
2907
2908// courtesy of jasonedelman.com
2909function selectText(element) {
2910 var doc = document
2911 , range, selection
2912 ;
2913 if (doc.body.createTextRange) { //ms
2914 range = doc.body.createTextRange();
2915 range.moveToElementText(element);
2916 range.select();
2917 } else if (window.getSelection) { //all others
2918 selection = window.getSelection();
2919 range = doc.createRange();
2920 range.selectNodeContents(element);
2921 selection.removeAllRanges();
2922 selection.addRange(range);
2923 }
2924}