blob: 87cbcd3544fe9504284889701859a4d66d326b1f [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
Scott Maine4d8f1b2012-06-21 18:03:05 -0700452 // Set up play-on-hover <video> tags.
453 $('video.play-on-hover').bind('click', function(){
454 $(this).get(0).load(); // in case the video isn't seekable
455 $(this).get(0).play();
456 });
457
458 // Set up tooltips
459 var TOOLTIP_MARGIN = 10;
Scott Maindb3678b2012-10-23 14:13:41 -0700460 $('acronym,.tooltip-link').each(function() {
Scott Maine4d8f1b2012-06-21 18:03:05 -0700461 var $target = $(this);
462 var $tooltip = $('<div>')
463 .addClass('tooltip-box')
Scott Maindb3678b2012-10-23 14:13:41 -0700464 .append($target.attr('title'))
Scott Maine4d8f1b2012-06-21 18:03:05 -0700465 .hide()
466 .appendTo('body');
467 $target.removeAttr('title');
468
469 $target.hover(function() {
470 // in
471 var targetRect = $target.offset();
472 targetRect.width = $target.width();
473 targetRect.height = $target.height();
474
475 $tooltip.css({
476 left: targetRect.left,
477 top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
478 });
479 $tooltip.addClass('below');
480 $tooltip.show();
481 }, function() {
482 // out
483 $tooltip.hide();
484 });
485 });
486
487 // Set up <h2> deeplinks
488 $('h2').click(function() {
489 var id = $(this).attr('id');
490 if (id) {
491 document.location.hash = id;
492 }
493 });
494
495 //Loads the +1 button
496 var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
497 po.src = 'https://apis.google.com/js/plusone.js';
498 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
499
500
Scott Main3b90aff2013-08-01 18:09:35 -0700501 // Revise the sidenav widths to make room for the scrollbar
Scott Maine4d8f1b2012-06-21 18:03:05 -0700502 // which avoids the visible width from changing each time the bar appears
503 var $sidenav = $("#side-nav");
504 var sidenav_width = parseInt($sidenav.innerWidth());
Scott Main3b90aff2013-08-01 18:09:35 -0700505
Scott Maine4d8f1b2012-06-21 18:03:05 -0700506 $("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
507
508
509 $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
Scott Main3b90aff2013-08-01 18:09:35 -0700510
Scott Maine4d8f1b2012-06-21 18:03:05 -0700511 if ($(".scroll-pane").length > 1) {
512 // Check if there's a user preference for the panel heights
513 var cookieHeight = readCookie("reference_height");
514 if (cookieHeight) {
515 restoreHeight(cookieHeight);
516 }
517 }
Scott Main3b90aff2013-08-01 18:09:35 -0700518
Scott Maine4d8f1b2012-06-21 18:03:05 -0700519 resizeNav();
520
Scott Main015d6162013-01-29 09:01:52 -0800521 /* init the language selector based on user cookie for lang */
522 loadLangPref();
523 changeNavLang(getLangPref());
524
525 /* setup event handlers to ensure the overflow menu is visible while picking lang */
526 $("#language select")
527 .mousedown(function() {
528 $("div.morehover").addClass("hover"); })
529 .blur(function() {
530 $("div.morehover").removeClass("hover"); });
531
532 /* some global variable setup */
533 resizePackagesNav = $("#resize-packages-nav");
534 classesNav = $("#classes-nav");
535 devdocNav = $("#devdoc-nav");
536
537 var cookiePath = "";
538 if (location.href.indexOf("/reference/") != -1) {
539 cookiePath = "reference_";
540 } else if (location.href.indexOf("/guide/") != -1) {
541 cookiePath = "guide_";
542 } else if (location.href.indexOf("/tools/") != -1) {
543 cookiePath = "tools_";
544 } else if (location.href.indexOf("/training/") != -1) {
545 cookiePath = "training_";
546 } else if (location.href.indexOf("/design/") != -1) {
547 cookiePath = "design_";
548 } else if (location.href.indexOf("/distribute/") != -1) {
549 cookiePath = "distribute_";
550 }
Scott Maine4d8f1b2012-06-21 18:03:05 -0700551
552});
Scott Main7e447ed2013-02-19 17:22:37 -0800553// END of the onload event
Scott Maine4d8f1b2012-06-21 18:03:05 -0700554
555
Scott Mainad08f072013-08-20 16:49:57 -0700556function initExpandableNavItems(rootTag) {
557 $(rootTag + ' li.nav-section .nav-section-header').click(function() {
558 var section = $(this).closest('li.nav-section');
559 if (section.hasClass('expanded')) {
Scott Mainf0093852013-08-22 11:37:11 -0700560 /* hide me and descendants */
561 section.find('ul').slideUp(250, function() {
562 // remove 'expanded' class from my section and any children
Scott Mainad08f072013-08-20 16:49:57 -0700563 section.closest('li').removeClass('expanded');
Scott Mainf0093852013-08-22 11:37:11 -0700564 $('li.nav-section', section).removeClass('expanded');
Scott Mainad08f072013-08-20 16:49:57 -0700565 resizeNav();
566 });
567 } else {
568 /* show me */
569 // first hide all other siblings
570 var $others = $('li.nav-section.expanded', $(this).closest('ul'));
571 $others.removeClass('expanded').children('ul').slideUp(250);
572
573 // now expand me
574 section.closest('li').addClass('expanded');
575 section.children('ul').slideDown(250, function() {
576 resizeNav();
577 });
578 }
579 });
Scott Mainf0093852013-08-22 11:37:11 -0700580
581 // Stop expand/collapse behavior when clicking on nav section links
582 // (since we're navigating away from the page)
583 // This selector captures the first instance of <a>, but not those with "#" as the href.
584 $('.nav-section-header').find('a:eq(0)').not('a[href="#"]').click(function(evt) {
585 window.location.href = $(this).attr('href');
586 return false;
587 });
Scott Mainad08f072013-08-20 16:49:57 -0700588}
589
Scott Mainf6145542013-04-01 16:38:11 -0700590function highlightSidenav() {
591 // select current page in sidenav and header, and set up prev/next links if they exist
592 var $selNavLink = $('#nav').find('a[href="' + mPagePath + '"]');
593 var $selListItem;
594 if ($selNavLink.length) {
595
596 // Find this page's <li> in sidenav and set selected
597 $selListItem = $selNavLink.closest('li');
598 $selListItem.addClass('selected');
Scott Main3b90aff2013-08-01 18:09:35 -0700599
Scott Mainf6145542013-04-01 16:38:11 -0700600 // Traverse up the tree and expand all parent nav-sections
601 $selNavLink.parents('li.nav-section').each(function() {
602 $(this).addClass('expanded');
603 $(this).children('ul').show();
604 });
605 }
606}
607
Scott Maine4d8f1b2012-06-21 18:03:05 -0700608
609function toggleFullscreen(enable) {
610 var delay = 20;
611 var enabled = true;
612 var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
613 if (enable) {
614 // Currently NOT USING fullscreen; enable fullscreen
615 stylesheet.removeAttr('disabled');
616 $('#nav-swap .fullscreen').removeClass('disabled');
617 $('#devdoc-nav').css({left:''});
618 setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
619 enabled = true;
620 } else {
621 // Currently USING fullscreen; disable fullscreen
622 stylesheet.attr('disabled', 'disabled');
623 $('#nav-swap .fullscreen').addClass('disabled');
624 setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
625 enabled = false;
626 }
627 writeCookie("fullscreen", enabled, null, null);
628 setNavBarLeftPos();
629 resizeNav(delay);
630 updateSideNavPosition();
631 setTimeout(initSidenavHeightResize,delay);
632}
633
634
635function setNavBarLeftPos() {
636 navBarLeftPos = $('#body-content').offset().left;
637}
638
639
640function updateSideNavPosition() {
641 var newLeft = $(window).scrollLeft() - navBarLeftPos;
642 $('#devdoc-nav').css({left: -newLeft});
643 $('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
644}
Scott Main3b90aff2013-08-01 18:09:35 -0700645
Scott Maine4d8f1b2012-06-21 18:03:05 -0700646// TODO: use $(document).ready instead
647function addLoadEvent(newfun) {
648 var current = window.onload;
649 if (typeof window.onload != 'function') {
650 window.onload = newfun;
651 } else {
652 window.onload = function() {
653 current();
654 newfun();
655 }
656 }
657}
658
659var agent = navigator['userAgent'].toLowerCase();
660// If a mobile phone, set flag and do mobile setup
661if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
662 (agent.indexOf("blackberry") != -1) ||
663 (agent.indexOf("webos") != -1) ||
664 (agent.indexOf("mini") != -1)) { // opera mini browsers
665 isMobile = true;
666}
667
668
Scott Main498d7102013-08-21 15:47:38 -0700669$(document).ready(function() {
Scott Maine4d8f1b2012-06-21 18:03:05 -0700670 $("pre:not(.no-pretty-print)").addClass("prettyprint");
671 prettyPrint();
Scott Main498d7102013-08-21 15:47:38 -0700672});
Scott Maine4d8f1b2012-06-21 18:03:05 -0700673
Scott Maine4d8f1b2012-06-21 18:03:05 -0700674
675
676
677/* ######### RESIZE THE SIDENAV HEIGHT ########## */
678
679function resizeNav(delay) {
680 var $nav = $("#devdoc-nav");
681 var $window = $(window);
682 var navHeight;
Scott Main3b90aff2013-08-01 18:09:35 -0700683
Scott Maine4d8f1b2012-06-21 18:03:05 -0700684 // Get the height of entire window and the total header height.
685 // Then figure out based on scroll position whether the header is visible
686 var windowHeight = $window.height();
687 var scrollTop = $window.scrollTop();
688 var headerHeight = $('#header').outerHeight();
689 var subheaderHeight = $('#nav-x').outerHeight();
690 var headerVisible = (scrollTop < (headerHeight + subheaderHeight));
Scott Main3b90aff2013-08-01 18:09:35 -0700691
692 // get the height of space between nav and top of window.
Scott Maine4d8f1b2012-06-21 18:03:05 -0700693 // Could be either margin or top position, depending on whether the nav is fixed.
Scott Main3b90aff2013-08-01 18:09:35 -0700694 var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
Scott Maine4d8f1b2012-06-21 18:03:05 -0700695 // add 1 for the #side-nav bottom margin
Scott Main3b90aff2013-08-01 18:09:35 -0700696
Scott Maine4d8f1b2012-06-21 18:03:05 -0700697 // Depending on whether the header is visible, set the side nav's height.
698 if (headerVisible) {
699 // The sidenav height grows as the header goes off screen
700 navHeight = windowHeight - (headerHeight + subheaderHeight - scrollTop) - topMargin;
701 } else {
702 // Once header is off screen, the nav height is almost full window height
703 navHeight = windowHeight - topMargin;
704 }
Scott Main3b90aff2013-08-01 18:09:35 -0700705
706
707
Scott Maine4d8f1b2012-06-21 18:03:05 -0700708 $scrollPanes = $(".scroll-pane");
709 if ($scrollPanes.length > 1) {
710 // subtract the height of the api level widget and nav swapper from the available nav height
711 navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
Scott Main3b90aff2013-08-01 18:09:35 -0700712
Scott Maine4d8f1b2012-06-21 18:03:05 -0700713 $("#swapper").css({height:navHeight + "px"});
714 if ($("#nav-tree").is(":visible")) {
715 $("#nav-tree").css({height:navHeight});
716 }
Scott Main3b90aff2013-08-01 18:09:35 -0700717
718 var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
Scott Maine4d8f1b2012-06-21 18:03:05 -0700719 //subtract 10px to account for drag bar
Scott Main3b90aff2013-08-01 18:09:35 -0700720
721 // if the window becomes small enough to make the class panel height 0,
Scott Maine4d8f1b2012-06-21 18:03:05 -0700722 // then the package panel should begin to shrink
723 if (parseInt(classesHeight) <= 0) {
724 $("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
725 $("#packages-nav").css({height:navHeight - 10});
726 }
Scott Main3b90aff2013-08-01 18:09:35 -0700727
Scott Maine4d8f1b2012-06-21 18:03:05 -0700728 $("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
729 $("#classes-nav .jspContainer").css({height:classesHeight});
Scott Main3b90aff2013-08-01 18:09:35 -0700730
731
Scott Maine4d8f1b2012-06-21 18:03:05 -0700732 } else {
733 $nav.height(navHeight);
734 }
Scott Main3b90aff2013-08-01 18:09:35 -0700735
Scott Maine4d8f1b2012-06-21 18:03:05 -0700736 if (delay) {
737 updateFromResize = true;
738 delayedReInitScrollbars(delay);
739 } else {
740 reInitScrollbars();
741 }
Scott Main3b90aff2013-08-01 18:09:35 -0700742
Scott Maine4d8f1b2012-06-21 18:03:05 -0700743}
744
745var updateScrollbars = false;
746var updateFromResize = false;
747
748/* Re-initialize the scrollbars to account for changed nav size.
749 * This method postpones the actual update by a 1/4 second in order to optimize the
750 * scroll performance while the header is still visible, because re-initializing the
751 * scroll panes is an intensive process.
752 */
753function delayedReInitScrollbars(delay) {
754 // If we're scheduled for an update, but have received another resize request
755 // before the scheduled resize has occured, just ignore the new request
756 // (and wait for the scheduled one).
757 if (updateScrollbars && updateFromResize) {
758 updateFromResize = false;
759 return;
760 }
Scott Main3b90aff2013-08-01 18:09:35 -0700761
Scott Maine4d8f1b2012-06-21 18:03:05 -0700762 // We're scheduled for an update and the update request came from this method's setTimeout
763 if (updateScrollbars && !updateFromResize) {
764 reInitScrollbars();
765 updateScrollbars = false;
766 } else {
767 updateScrollbars = true;
768 updateFromResize = false;
769 setTimeout('delayedReInitScrollbars()',delay);
770 }
771}
772
773/* Re-initialize the scrollbars to account for changed nav size. */
774function reInitScrollbars() {
775 var pane = $(".scroll-pane").each(function(){
776 var api = $(this).data('jsp');
777 if (!api) { setTimeout(reInitScrollbars,300); return;}
778 api.reinitialise( {verticalGutter:0} );
Scott Main3b90aff2013-08-01 18:09:35 -0700779 });
Scott Maine4d8f1b2012-06-21 18:03:05 -0700780 $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
781}
782
783
784/* Resize the height of the nav panels in the reference,
785 * and save the new size to a cookie */
786function saveNavPanels() {
787 var basePath = getBaseUri(location.pathname);
788 var section = basePath.substring(1,basePath.indexOf("/",1));
789 writeCookie("height", resizePackagesNav.css("height"), section, null);
790}
791
792
793
794function restoreHeight(packageHeight) {
795 $("#resize-packages-nav").height(packageHeight);
796 $("#packages-nav").height(packageHeight);
797 // var classesHeight = navHeight - packageHeight;
798 // $("#classes-nav").css({height:classesHeight});
799 // $("#classes-nav .jspContainer").css({height:classesHeight});
800}
801
802
803
804/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
805
806
807
808
809
Scott Main3b90aff2013-08-01 18:09:35 -0700810/** Scroll the jScrollPane to make the currently selected item visible
Scott Maine4d8f1b2012-06-21 18:03:05 -0700811 This is called when the page finished loading. */
812function scrollIntoView(nav) {
813 var $nav = $("#"+nav);
814 var element = $nav.jScrollPane({/* ...settings... */});
815 var api = element.data('jsp');
816
817 if ($nav.is(':visible')) {
818 var $selected = $(".selected", $nav);
Scott Mainbc729572013-07-30 18:00:51 -0700819 if ($selected.length == 0) {
820 // If no selected item found, exit
821 return;
822 }
Scott Main52dd2062013-08-15 12:22:28 -0700823 // get the selected item's offset from its container nav by measuring the item's offset
824 // relative to the document then subtract the container nav's offset relative to the document
825 var selectedOffset = $selected.offset().top - $nav.offset().top;
826 if (selectedOffset > $nav.height() * .8) { // multiply nav height by .8 so we move up the item
827 // if it's more than 80% down the nav
828 // scroll the item up by an amount equal to 80% the container nav's height
829 api.scrollTo(0, selectedOffset - ($nav.height() * .8), false);
Scott Maine4d8f1b2012-06-21 18:03:05 -0700830 }
831 }
832}
833
834
835
836
837
838
839/* Show popup dialogs */
840function showDialog(id) {
841 $dialog = $("#"+id);
842 $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>');
843 $dialog.wrapInner('<div/>');
844 $dialog.removeClass("hide");
845}
846
847
848
849
850
851/* ######### COOKIES! ########## */
852
853function readCookie(cookie) {
854 var myCookie = cookie_namespace+"_"+cookie+"=";
855 if (document.cookie) {
856 var index = document.cookie.indexOf(myCookie);
857 if (index != -1) {
858 var valStart = index + myCookie.length;
859 var valEnd = document.cookie.indexOf(";", valStart);
860 if (valEnd == -1) {
861 valEnd = document.cookie.length;
862 }
863 var val = document.cookie.substring(valStart, valEnd);
864 return val;
865 }
866 }
867 return 0;
868}
869
870function writeCookie(cookie, val, section, expiration) {
871 if (val==undefined) return;
872 section = section == null ? "_" : "_"+section+"_";
873 if (expiration == null) {
874 var date = new Date();
875 date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
876 expiration = date.toGMTString();
877 }
Scott Main3b90aff2013-08-01 18:09:35 -0700878 var cookieValue = cookie_namespace + section + cookie + "=" + val
Scott Maine4d8f1b2012-06-21 18:03:05 -0700879 + "; expires=" + expiration+"; path=/";
880 document.cookie = cookieValue;
881}
882
883/* ######### END COOKIES! ########## */
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
Scott Maind7026f72013-06-17 15:08:49 -0700903/* MISC LIBRARY FUNCTIONS */
Scott Maine4d8f1b2012-06-21 18:03:05 -0700904
905
906
907
908
909function toggle(obj, slide) {
910 var ul = $("ul:first", obj);
911 var li = ul.parent();
912 if (li.hasClass("closed")) {
913 if (slide) {
914 ul.slideDown("fast");
915 } else {
916 ul.show();
917 }
918 li.removeClass("closed");
919 li.addClass("open");
920 $(".toggle-img", li).attr("title", "hide pages");
921 } else {
922 ul.slideUp("fast");
923 li.removeClass("open");
924 li.addClass("closed");
925 $(".toggle-img", li).attr("title", "show pages");
926 }
927}
928
929
Scott Maine4d8f1b2012-06-21 18:03:05 -0700930function buildToggleLists() {
931 $(".toggle-list").each(
932 function(i) {
933 $("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
934 $(this).addClass("closed");
935 });
936}
937
938
939
Scott Maind7026f72013-06-17 15:08:49 -0700940function hideNestedItems(list, toggle) {
941 $list = $(list);
942 // hide nested lists
943 if($list.hasClass('showing')) {
944 $("li ol", $list).hide('fast');
945 $list.removeClass('showing');
946 // show nested lists
947 } else {
948 $("li ol", $list).show('fast');
949 $list.addClass('showing');
950 }
951 $(".more,.less",$(toggle)).toggle();
952}
Scott Maine4d8f1b2012-06-21 18:03:05 -0700953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981/* REFERENCE NAV SWAP */
982
983
984function getNavPref() {
985 var v = readCookie('reference_nav');
986 if (v != NAV_PREF_TREE) {
987 v = NAV_PREF_PANELS;
988 }
989 return v;
990}
991
992function chooseDefaultNav() {
993 nav_pref = getNavPref();
994 if (nav_pref == NAV_PREF_TREE) {
995 $("#nav-panels").toggle();
996 $("#panel-link").toggle();
997 $("#nav-tree").toggle();
998 $("#tree-link").toggle();
999 }
1000}
1001
1002function swapNav() {
1003 if (nav_pref == NAV_PREF_TREE) {
1004 nav_pref = NAV_PREF_PANELS;
1005 } else {
1006 nav_pref = NAV_PREF_TREE;
1007 init_default_navtree(toRoot);
1008 }
1009 var date = new Date();
1010 date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
1011 writeCookie("nav", nav_pref, "reference", date.toGMTString());
1012
1013 $("#nav-panels").toggle();
1014 $("#panel-link").toggle();
1015 $("#nav-tree").toggle();
1016 $("#tree-link").toggle();
Scott Main3b90aff2013-08-01 18:09:35 -07001017
Scott Maine4d8f1b2012-06-21 18:03:05 -07001018 resizeNav();
1019
1020 // Gross nasty hack to make tree view show up upon first swap by setting height manually
1021 $("#nav-tree .jspContainer:visible")
1022 .css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
1023 // Another nasty hack to make the scrollbar appear now that we have height
1024 resizeNav();
Scott Main3b90aff2013-08-01 18:09:35 -07001025
Scott Maine4d8f1b2012-06-21 18:03:05 -07001026 if ($("#nav-tree").is(':visible')) {
1027 scrollIntoView("nav-tree");
1028 } else {
1029 scrollIntoView("packages-nav");
1030 scrollIntoView("classes-nav");
1031 }
1032}
1033
1034
1035
Scott Mainf5089842012-08-14 16:31:07 -07001036/* ############################################ */
Scott Maine4d8f1b2012-06-21 18:03:05 -07001037/* ########## LOCALIZATION ############ */
Scott Mainf5089842012-08-14 16:31:07 -07001038/* ############################################ */
Scott Maine4d8f1b2012-06-21 18:03:05 -07001039
1040function getBaseUri(uri) {
1041 var intlUrl = (uri.substring(0,6) == "/intl/");
1042 if (intlUrl) {
1043 base = uri.substring(uri.indexOf('intl/')+5,uri.length);
1044 base = base.substring(base.indexOf('/')+1, base.length);
1045 //alert("intl, returning base url: /" + base);
1046 return ("/" + base);
1047 } else {
1048 //alert("not intl, returning uri as found.");
1049 return uri;
1050 }
1051}
1052
1053function requestAppendHL(uri) {
1054//append "?hl=<lang> to an outgoing request (such as to blog)
1055 var lang = getLangPref();
1056 if (lang) {
1057 var q = 'hl=' + lang;
1058 uri += '?' + q;
1059 window.location = uri;
1060 return false;
1061 } else {
1062 return true;
1063 }
1064}
1065
1066
Scott Maine4d8f1b2012-06-21 18:03:05 -07001067function changeNavLang(lang) {
Scott Main6eb95f12012-10-02 17:12:23 -07001068 var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
1069 $links.each(function(i){ // for each link with a translation
1070 var $link = $(this);
1071 if (lang != "en") { // No need to worry about English, because a language change invokes new request
1072 // put the desired language from the attribute as the text
1073 $link.text($link.attr(lang+"-lang"))
Scott Maine4d8f1b2012-06-21 18:03:05 -07001074 }
Scott Main6eb95f12012-10-02 17:12:23 -07001075 });
Scott Maine4d8f1b2012-06-21 18:03:05 -07001076}
1077
Scott Main015d6162013-01-29 09:01:52 -08001078function changeLangPref(lang, submit) {
Scott Maine4d8f1b2012-06-21 18:03:05 -07001079 var date = new Date();
Scott Main3b90aff2013-08-01 18:09:35 -07001080 expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000)));
Scott Maine4d8f1b2012-06-21 18:03:05 -07001081 // keep this for 50 years
1082 //alert("expires: " + expires)
1083 writeCookie("pref_lang", lang, null, expires);
Scott Main015d6162013-01-29 09:01:52 -08001084
1085 // ####### TODO: Remove this condition once we're stable on devsite #######
1086 // This condition is only needed if we still need to support legacy GAE server
1087 if (devsite) {
1088 // Switch language when on Devsite server
1089 if (submit) {
1090 $("#setlang").submit();
1091 }
1092 } else {
1093 // Switch language when on legacy GAE server
Scott Main015d6162013-01-29 09:01:52 -08001094 if (submit) {
1095 window.location = getBaseUri(location.pathname);
1096 }
Scott Maine4d8f1b2012-06-21 18:03:05 -07001097 }
1098}
1099
1100function loadLangPref() {
1101 var lang = readCookie("pref_lang");
1102 if (lang != 0) {
1103 $("#language").find("option[value='"+lang+"']").attr("selected",true);
1104 }
1105}
1106
1107function getLangPref() {
1108 var lang = $("#language").find(":selected").attr("value");
1109 if (!lang) {
1110 lang = readCookie("pref_lang");
1111 }
1112 return (lang != 0) ? lang : 'en';
1113}
1114
1115/* ########## END LOCALIZATION ############ */
1116
1117
1118
1119
1120
1121
1122/* Used to hide and reveal supplemental content, such as long code samples.
1123 See the companion CSS in android-developer-docs.css */
1124function toggleContent(obj) {
Scott Maindc63dda2013-08-22 16:03:21 -07001125 var div = $(obj).closest(".toggle-content");
1126 var toggleMe = $(".toggle-content-toggleme:eq(0)",div);
Scott Maine4d8f1b2012-06-21 18:03:05 -07001127 if (div.hasClass("closed")) { // if it's closed, open it
1128 toggleMe.slideDown();
Scott Maindc63dda2013-08-22 16:03:21 -07001129 $(".toggle-content-text:eq(0)", obj).toggle();
Scott Maine4d8f1b2012-06-21 18:03:05 -07001130 div.removeClass("closed").addClass("open");
Scott Maindc63dda2013-08-22 16:03:21 -07001131 $(".toggle-content-img:eq(0)", div).attr("title", "hide").attr("src", toRoot
Scott Maine4d8f1b2012-06-21 18:03:05 -07001132 + "assets/images/triangle-opened.png");
1133 } else { // if it's open, close it
1134 toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
Scott Maindc63dda2013-08-22 16:03:21 -07001135 $(".toggle-content-text:eq(0)", obj).toggle();
Scott Maine4d8f1b2012-06-21 18:03:05 -07001136 div.removeClass("open").addClass("closed");
Scott Maindc63dda2013-08-22 16:03:21 -07001137 div.find(".toggle-content").removeClass("open").addClass("closed")
1138 .find(".toggle-content-toggleme").hide();
Scott Main3b90aff2013-08-01 18:09:35 -07001139 $(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
Scott Maine4d8f1b2012-06-21 18:03:05 -07001140 + "assets/images/triangle-closed.png");
1141 });
1142 }
1143 return false;
1144}
Scott Mainf5089842012-08-14 16:31:07 -07001145
1146
Scott Maindb3678b2012-10-23 14:13:41 -07001147/* New version of expandable content */
1148function toggleExpandable(link,id) {
1149 if($(id).is(':visible')) {
1150 $(id).slideUp();
1151 $(link).removeClass('expanded');
1152 } else {
1153 $(id).slideDown();
1154 $(link).addClass('expanded');
1155 }
1156}
1157
1158function hideExpandable(ids) {
1159 $(ids).slideUp();
Scott Main55d99832012-11-12 23:03:59 -08001160 $(ids).prev('h4').find('a.expandable').removeClass('expanded');
Scott Maindb3678b2012-10-23 14:13:41 -07001161}
1162
Scott Mainf5089842012-08-14 16:31:07 -07001163
1164
1165
1166
Scott Main3b90aff2013-08-01 18:09:35 -07001167/*
Scott Mainf5089842012-08-14 16:31:07 -07001168 * Slideshow 1.0
1169 * Used on /index.html and /develop/index.html for carousel
1170 *
1171 * Sample usage:
1172 * HTML -
1173 * <div class="slideshow-container">
1174 * <a href="" class="slideshow-prev">Prev</a>
1175 * <a href="" class="slideshow-next">Next</a>
1176 * <ul>
1177 * <li class="item"><img src="images/marquee1.jpg"></li>
1178 * <li class="item"><img src="images/marquee2.jpg"></li>
1179 * <li class="item"><img src="images/marquee3.jpg"></li>
1180 * <li class="item"><img src="images/marquee4.jpg"></li>
1181 * </ul>
1182 * </div>
1183 *
1184 * <script type="text/javascript">
1185 * $('.slideshow-container').dacSlideshow({
1186 * auto: true,
1187 * btnPrev: '.slideshow-prev',
1188 * btnNext: '.slideshow-next'
1189 * });
1190 * </script>
1191 *
1192 * Options:
1193 * btnPrev: optional identifier for previous button
1194 * btnNext: optional identifier for next button
Scott Maineb410352013-01-14 19:03:40 -08001195 * btnPause: optional identifier for pause button
Scott Mainf5089842012-08-14 16:31:07 -07001196 * auto: whether or not to auto-proceed
1197 * speed: animation speed
1198 * autoTime: time between auto-rotation
1199 * easing: easing function for transition
1200 * start: item to select by default
1201 * scroll: direction to scroll in
1202 * pagination: whether or not to include dotted pagination
1203 *
1204 */
1205
1206 (function($) {
1207 $.fn.dacSlideshow = function(o) {
Scott Main3b90aff2013-08-01 18:09:35 -07001208
Scott Mainf5089842012-08-14 16:31:07 -07001209 //Options - see above
1210 o = $.extend({
1211 btnPrev: null,
1212 btnNext: null,
Scott Maineb410352013-01-14 19:03:40 -08001213 btnPause: null,
Scott Mainf5089842012-08-14 16:31:07 -07001214 auto: true,
1215 speed: 500,
1216 autoTime: 12000,
1217 easing: null,
1218 start: 0,
1219 scroll: 1,
1220 pagination: true
1221
1222 }, o || {});
Scott Main3b90aff2013-08-01 18:09:35 -07001223
1224 //Set up a carousel for each
Scott Mainf5089842012-08-14 16:31:07 -07001225 return this.each(function() {
1226
1227 var running = false;
1228 var animCss = o.vertical ? "top" : "left";
1229 var sizeCss = o.vertical ? "height" : "width";
1230 var div = $(this);
1231 var ul = $("ul", div);
1232 var tLi = $("li", ul);
Scott Main3b90aff2013-08-01 18:09:35 -07001233 var tl = tLi.size();
Scott Mainf5089842012-08-14 16:31:07 -07001234 var timer = null;
1235
1236 var li = $("li", ul);
1237 var itemLength = li.size();
1238 var curr = o.start;
1239
1240 li.css({float: o.vertical ? "none" : "left"});
1241 ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
1242 div.css({position: "relative", "z-index": "2", left: "0px"});
1243
1244 var liSize = o.vertical ? height(li) : width(li);
1245 var ulSize = liSize * itemLength;
1246 var divSize = liSize;
1247
1248 li.css({width: li.width(), height: li.height()});
1249 ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
1250
1251 div.css(sizeCss, divSize+"px");
Scott Main3b90aff2013-08-01 18:09:35 -07001252
Scott Mainf5089842012-08-14 16:31:07 -07001253 //Pagination
1254 if (o.pagination) {
1255 var pagination = $("<div class='pagination'></div>");
1256 var pag_ul = $("<ul></ul>");
1257 if (tl > 1) {
1258 for (var i=0;i<tl;i++) {
1259 var li = $("<li>"+i+"</li>");
1260 pag_ul.append(li);
1261 if (i==o.start) li.addClass('active');
1262 li.click(function() {
1263 go(parseInt($(this).text()));
1264 })
1265 }
1266 pagination.append(pag_ul);
1267 div.append(pagination);
1268 }
1269 }
Scott Main3b90aff2013-08-01 18:09:35 -07001270
Scott Mainf5089842012-08-14 16:31:07 -07001271 //Previous button
1272 if(o.btnPrev)
1273 $(o.btnPrev).click(function(e) {
1274 e.preventDefault();
1275 return go(curr-o.scroll);
1276 });
1277
1278 //Next button
1279 if(o.btnNext)
1280 $(o.btnNext).click(function(e) {
1281 e.preventDefault();
1282 return go(curr+o.scroll);
1283 });
Scott Maineb410352013-01-14 19:03:40 -08001284
1285 //Pause button
1286 if(o.btnPause)
1287 $(o.btnPause).click(function(e) {
1288 e.preventDefault();
1289 if ($(this).hasClass('paused')) {
1290 startRotateTimer();
1291 } else {
1292 pauseRotateTimer();
1293 }
1294 });
Scott Main3b90aff2013-08-01 18:09:35 -07001295
Scott Mainf5089842012-08-14 16:31:07 -07001296 //Auto rotation
1297 if(o.auto) startRotateTimer();
Scott Main3b90aff2013-08-01 18:09:35 -07001298
Scott Mainf5089842012-08-14 16:31:07 -07001299 function startRotateTimer() {
1300 clearInterval(timer);
1301 timer = setInterval(function() {
1302 if (curr == tl-1) {
1303 go(0);
1304 } else {
Scott Main3b90aff2013-08-01 18:09:35 -07001305 go(curr+o.scroll);
1306 }
Scott Mainf5089842012-08-14 16:31:07 -07001307 }, o.autoTime);
Scott Maineb410352013-01-14 19:03:40 -08001308 $(o.btnPause).removeClass('paused');
1309 }
1310
1311 function pauseRotateTimer() {
1312 clearInterval(timer);
1313 $(o.btnPause).addClass('paused');
Scott Mainf5089842012-08-14 16:31:07 -07001314 }
1315
1316 //Go to an item
1317 function go(to) {
1318 if(!running) {
1319
1320 if(to<0) {
1321 to = itemLength-1;
1322 } else if (to>itemLength-1) {
1323 to = 0;
1324 }
1325 curr = to;
1326
1327 running = true;
1328
1329 ul.animate(
1330 animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
1331 function() {
1332 running = false;
1333 }
1334 );
1335
1336 $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
1337 $( (curr-o.scroll<0 && o.btnPrev)
1338 ||
1339 (curr+o.scroll > itemLength && o.btnNext)
1340 ||
1341 []
1342 ).addClass("disabled");
1343
Scott Main3b90aff2013-08-01 18:09:35 -07001344
Scott Mainf5089842012-08-14 16:31:07 -07001345 var nav_items = $('li', pagination);
1346 nav_items.removeClass('active');
1347 nav_items.eq(to).addClass('active');
Scott Main3b90aff2013-08-01 18:09:35 -07001348
Scott Mainf5089842012-08-14 16:31:07 -07001349
1350 }
1351 if(o.auto) startRotateTimer();
1352 return false;
1353 };
1354 });
1355 };
1356
1357 function css(el, prop) {
1358 return parseInt($.css(el[0], prop)) || 0;
1359 };
1360 function width(el) {
1361 return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
1362 };
1363 function height(el) {
1364 return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
1365 };
1366
1367 })(jQuery);
1368
1369
Scott Main3b90aff2013-08-01 18:09:35 -07001370/*
Scott Mainf5089842012-08-14 16:31:07 -07001371 * dacSlideshow 1.0
1372 * Used on develop/index.html for side-sliding tabs
1373 *
1374 * Sample usage:
1375 * HTML -
1376 * <div class="slideshow-container">
1377 * <a href="" class="slideshow-prev">Prev</a>
1378 * <a href="" class="slideshow-next">Next</a>
1379 * <ul>
1380 * <li class="item"><img src="images/marquee1.jpg"></li>
1381 * <li class="item"><img src="images/marquee2.jpg"></li>
1382 * <li class="item"><img src="images/marquee3.jpg"></li>
1383 * <li class="item"><img src="images/marquee4.jpg"></li>
1384 * </ul>
1385 * </div>
1386 *
1387 * <script type="text/javascript">
1388 * $('.slideshow-container').dacSlideshow({
1389 * auto: true,
1390 * btnPrev: '.slideshow-prev',
1391 * btnNext: '.slideshow-next'
1392 * });
1393 * </script>
1394 *
1395 * Options:
1396 * btnPrev: optional identifier for previous button
1397 * btnNext: optional identifier for next button
1398 * auto: whether or not to auto-proceed
1399 * speed: animation speed
1400 * autoTime: time between auto-rotation
1401 * easing: easing function for transition
1402 * start: item to select by default
1403 * scroll: direction to scroll in
1404 * pagination: whether or not to include dotted pagination
1405 *
1406 */
1407 (function($) {
1408 $.fn.dacTabbedList = function(o) {
Scott Main3b90aff2013-08-01 18:09:35 -07001409
Scott Mainf5089842012-08-14 16:31:07 -07001410 //Options - see above
1411 o = $.extend({
1412 speed : 250,
1413 easing: null,
1414 nav_id: null,
1415 frame_id: null
1416 }, o || {});
Scott Main3b90aff2013-08-01 18:09:35 -07001417
1418 //Set up a carousel for each
Scott Mainf5089842012-08-14 16:31:07 -07001419 return this.each(function() {
1420
1421 var curr = 0;
1422 var running = false;
1423 var animCss = "margin-left";
1424 var sizeCss = "width";
1425 var div = $(this);
Scott Main3b90aff2013-08-01 18:09:35 -07001426
Scott Mainf5089842012-08-14 16:31:07 -07001427 var nav = $(o.nav_id, div);
1428 var nav_li = $("li", nav);
Scott Main3b90aff2013-08-01 18:09:35 -07001429 var nav_size = nav_li.size();
Scott Mainf5089842012-08-14 16:31:07 -07001430 var frame = div.find(o.frame_id);
1431 var content_width = $(frame).find('ul').width();
1432 //Buttons
1433 $(nav_li).click(function(e) {
1434 go($(nav_li).index($(this)));
1435 })
Scott Main3b90aff2013-08-01 18:09:35 -07001436
Scott Mainf5089842012-08-14 16:31:07 -07001437 //Go to an item
1438 function go(to) {
1439 if(!running) {
1440 curr = to;
1441 running = true;
1442
1443 frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
1444 function() {
1445 running = false;
1446 }
1447 );
1448
Scott Main3b90aff2013-08-01 18:09:35 -07001449
Scott Mainf5089842012-08-14 16:31:07 -07001450 nav_li.removeClass('active');
1451 nav_li.eq(to).addClass('active');
Scott Main3b90aff2013-08-01 18:09:35 -07001452
Scott Mainf5089842012-08-14 16:31:07 -07001453
1454 }
1455 return false;
1456 };
1457 });
1458 };
1459
1460 function css(el, prop) {
1461 return parseInt($.css(el[0], prop)) || 0;
1462 };
1463 function width(el) {
1464 return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
1465 };
1466 function height(el) {
1467 return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
1468 };
1469
1470 })(jQuery);
1471
1472
1473
1474
1475
1476/* ######################################################## */
1477/* ################ SEARCH SUGGESTIONS ################## */
1478/* ######################################################## */
1479
1480
Scott Main7e447ed2013-02-19 17:22:37 -08001481
Scott Main0e76e7e2013-03-12 10:24:07 -07001482var gSelectedIndex = -1; // the index position of currently highlighted suggestion
1483var gSelectedColumn = -1; // which column of suggestion lists is currently focused
1484
Scott Mainf5089842012-08-14 16:31:07 -07001485var gMatches = new Array();
1486var gLastText = "";
Scott Mainf5089842012-08-14 16:31:07 -07001487var gInitialized = false;
Scott Main7e447ed2013-02-19 17:22:37 -08001488var ROW_COUNT_FRAMEWORK = 20; // max number of results in list
1489var gListLength = 0;
1490
1491
1492var gGoogleMatches = new Array();
1493var ROW_COUNT_GOOGLE = 15; // max number of results in list
1494var gGoogleListLength = 0;
Scott Mainf5089842012-08-14 16:31:07 -07001495
Scott Main0e76e7e2013-03-12 10:24:07 -07001496var gDocsMatches = new Array();
1497var ROW_COUNT_DOCS = 100; // max number of results in list
1498var gDocsListLength = 0;
1499
Scott Mainde295272013-03-25 15:48:35 -07001500function onSuggestionClick(link) {
1501 // When user clicks a suggested document, track it
1502 _gaq.push(['_trackEvent', 'Suggestion Click', 'clicked: ' + $(link).text(),
1503 'from: ' + $("#search_autocomplete").val()]);
1504}
1505
Scott Mainf5089842012-08-14 16:31:07 -07001506function set_item_selected($li, selected)
1507{
1508 if (selected) {
1509 $li.attr('class','jd-autocomplete jd-selected');
1510 } else {
1511 $li.attr('class','jd-autocomplete');
1512 }
1513}
1514
1515function set_item_values(toroot, $li, match)
1516{
1517 var $link = $('a',$li);
1518 $link.html(match.__hilabel || match.label);
1519 $link.attr('href',toroot + match.link);
1520}
1521
Scott Main0e76e7e2013-03-12 10:24:07 -07001522function new_suggestion($list) {
Scott Main7e447ed2013-02-19 17:22:37 -08001523 var $li = $("<li class='jd-autocomplete'></li>");
1524 $list.append($li);
1525
1526 $li.mousedown(function() {
1527 window.location = this.firstChild.getAttribute("href");
1528 });
1529 $li.mouseover(function() {
Scott Main0e76e7e2013-03-12 10:24:07 -07001530 $('.search_filtered_wrapper li').removeClass('jd-selected');
Scott Main7e447ed2013-02-19 17:22:37 -08001531 $(this).addClass('jd-selected');
Scott Main0e76e7e2013-03-12 10:24:07 -07001532 gSelectedColumn = $(".search_filtered:visible").index($(this).closest('.search_filtered'));
1533 gSelectedIndex = $("li", $(".search_filtered:visible")[gSelectedColumn]).index(this);
Scott Main7e447ed2013-02-19 17:22:37 -08001534 });
Scott Mainde295272013-03-25 15:48:35 -07001535 $li.append("<a onclick='onSuggestionClick(this)'></a>");
Scott Main7e447ed2013-02-19 17:22:37 -08001536 $li.attr('class','show-item');
1537 return $li;
1538}
1539
Scott Mainf5089842012-08-14 16:31:07 -07001540function sync_selection_table(toroot)
1541{
Scott Mainf5089842012-08-14 16:31:07 -07001542 var $li; //list item jquery object
1543 var i; //list item iterator
Scott Main7e447ed2013-02-19 17:22:37 -08001544
Scott Main0e76e7e2013-03-12 10:24:07 -07001545 // if there are NO results at all, hide all columns
1546 if (!(gMatches.length > 0) && !(gGoogleMatches.length > 0) && !(gDocsMatches.length > 0)) {
1547 $('.suggest-card').hide(300);
1548 return;
1549 }
1550
1551 // if there are api results
Scott Main7e447ed2013-02-19 17:22:37 -08001552 if ((gMatches.length > 0) || (gGoogleMatches.length > 0)) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001553 // reveal suggestion list
1554 $('.suggest-card.dummy').show();
1555 $('.suggest-card.reference').show();
1556 var listIndex = 0; // list index position
Scott Main7e447ed2013-02-19 17:22:37 -08001557
Scott Main0e76e7e2013-03-12 10:24:07 -07001558 // reset the lists
1559 $(".search_filtered_wrapper.reference li").remove();
Scott Main7e447ed2013-02-19 17:22:37 -08001560
Scott Main0e76e7e2013-03-12 10:24:07 -07001561 // ########### ANDROID RESULTS #############
1562 if (gMatches.length > 0) {
Scott Main7e447ed2013-02-19 17:22:37 -08001563
Scott Main0e76e7e2013-03-12 10:24:07 -07001564 // determine android results to show
1565 gListLength = gMatches.length < ROW_COUNT_FRAMEWORK ?
1566 gMatches.length : ROW_COUNT_FRAMEWORK;
1567 for (i=0; i<gListLength; i++) {
1568 var $li = new_suggestion($(".suggest-card.reference ul"));
1569 set_item_values(toroot, $li, gMatches[i]);
1570 set_item_selected($li, i == gSelectedIndex);
1571 }
1572 }
Scott Main7e447ed2013-02-19 17:22:37 -08001573
Scott Main0e76e7e2013-03-12 10:24:07 -07001574 // ########### GOOGLE RESULTS #############
1575 if (gGoogleMatches.length > 0) {
1576 // show header for list
1577 $(".suggest-card.reference ul").append("<li class='header'>in Google Services:</li>");
Scott Main7e447ed2013-02-19 17:22:37 -08001578
Scott Main0e76e7e2013-03-12 10:24:07 -07001579 // determine google results to show
1580 gGoogleListLength = gGoogleMatches.length < ROW_COUNT_GOOGLE ? gGoogleMatches.length : ROW_COUNT_GOOGLE;
1581 for (i=0; i<gGoogleListLength; i++) {
1582 var $li = new_suggestion($(".suggest-card.reference ul"));
1583 set_item_values(toroot, $li, gGoogleMatches[i]);
1584 set_item_selected($li, i == gSelectedIndex);
1585 }
1586 }
Scott Mainf5089842012-08-14 16:31:07 -07001587 } else {
Scott Main0e76e7e2013-03-12 10:24:07 -07001588 $('.suggest-card.reference').hide();
1589 $('.suggest-card.dummy').hide();
1590 }
1591
1592 // ########### JD DOC RESULTS #############
1593 if (gDocsMatches.length > 0) {
1594 // reset the lists
1595 $(".search_filtered_wrapper.docs li").remove();
1596
1597 // determine google results to show
1598 gDocsListLength = gDocsMatches.length < ROW_COUNT_DOCS ? gDocsMatches.length : ROW_COUNT_DOCS;
1599 for (i=0; i<gDocsListLength; i++) {
1600 var sugg = gDocsMatches[i];
1601 var $li;
1602 if (sugg.type == "design") {
1603 $li = new_suggestion($(".suggest-card.design ul"));
1604 } else
1605 if (sugg.type == "distribute") {
1606 $li = new_suggestion($(".suggest-card.distribute ul"));
1607 } else
1608 if (sugg.type == "training") {
1609 $li = new_suggestion($(".suggest-card.develop .child-card.training"));
1610 } else
1611 if (sugg.type == "guide"||"google") {
1612 $li = new_suggestion($(".suggest-card.develop .child-card.guides"));
1613 } else {
1614 continue;
1615 }
1616
1617 set_item_values(toroot, $li, sugg);
1618 set_item_selected($li, i == gSelectedIndex);
1619 }
1620
1621 // add heading and show or hide card
1622 if ($(".suggest-card.design li").length > 0) {
1623 $(".suggest-card.design ul").prepend("<li class='header'>Design:</li>");
1624 $(".suggest-card.design").show(300);
1625 } else {
1626 $('.suggest-card.design').hide(300);
1627 }
1628 if ($(".suggest-card.distribute li").length > 0) {
1629 $(".suggest-card.distribute ul").prepend("<li class='header'>Distribute:</li>");
1630 $(".suggest-card.distribute").show(300);
1631 } else {
1632 $('.suggest-card.distribute').hide(300);
1633 }
1634 if ($(".child-card.guides li").length > 0) {
1635 $(".child-card.guides").prepend("<li class='header'>Guides:</li>");
1636 $(".child-card.guides li").appendTo(".suggest-card.develop ul");
1637 }
1638 if ($(".child-card.training li").length > 0) {
1639 $(".child-card.training").prepend("<li class='header'>Training:</li>");
1640 $(".child-card.training li").appendTo(".suggest-card.develop ul");
1641 }
1642
1643 if ($(".suggest-card.develop li").length > 0) {
1644 $(".suggest-card.develop").show(300);
1645 } else {
1646 $('.suggest-card.develop').hide(300);
1647 }
1648
1649 } else {
1650 $('.search_filtered_wrapper.docs .suggest-card:not(.dummy)').hide(300);
Scott Mainf5089842012-08-14 16:31:07 -07001651 }
1652}
1653
Scott Main0e76e7e2013-03-12 10:24:07 -07001654/** Called by the search input's onkeydown and onkeyup events.
1655 * Handles navigation with keyboard arrows, Enter key to invoke search,
1656 * otherwise invokes search suggestions on key-up event.
1657 * @param e The JS event
1658 * @param kd True if the event is key-down
Scott Main3b90aff2013-08-01 18:09:35 -07001659 * @param toroot A string for the site's root path
Scott Main0e76e7e2013-03-12 10:24:07 -07001660 * @returns True if the event should bubble up
1661 */
Scott Mainf5089842012-08-14 16:31:07 -07001662function search_changed(e, kd, toroot)
1663{
1664 var search = document.getElementById("search_autocomplete");
1665 var text = search.value.replace(/(^ +)|( +$)/g, '');
Scott Main0e76e7e2013-03-12 10:24:07 -07001666 // get the ul hosting the currently selected item
1667 gSelectedColumn = gSelectedColumn >= 0 ? gSelectedColumn : 0;
1668 var $columns = $(".search_filtered_wrapper").find(".search_filtered:visible");
1669 var $selectedUl = $columns[gSelectedColumn];
1670
Scott Mainf5089842012-08-14 16:31:07 -07001671 // show/hide the close button
1672 if (text != '') {
1673 $(".search .close").removeClass("hide");
1674 } else {
1675 $(".search .close").addClass("hide");
1676 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001677 // 27 = esc
1678 if (e.keyCode == 27) {
1679 // close all search results
1680 if (kd) $('.search .close').trigger('click');
1681 return true;
1682 }
Scott Mainf5089842012-08-14 16:31:07 -07001683 // 13 = enter
Scott Main0e76e7e2013-03-12 10:24:07 -07001684 else if (e.keyCode == 13) {
1685 if (gSelectedIndex < 0) {
1686 $('.suggest-card').hide();
Scott Main7e447ed2013-02-19 17:22:37 -08001687 if ($("#searchResults").is(":hidden") && (search.value != "")) {
1688 // if results aren't showing (and text not empty), return true to allow search to execute
Scott Mainf5089842012-08-14 16:31:07 -07001689 return true;
1690 } else {
1691 // otherwise, results are already showing, so allow ajax to auto refresh the results
1692 // and ignore this Enter press to avoid the reload.
1693 return false;
1694 }
1695 } else if (kd && gSelectedIndex >= 0) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001696 // click the link corresponding to selected item
1697 $("a",$("li",$selectedUl)[gSelectedIndex]).get()[0].click();
Scott Mainf5089842012-08-14 16:31:07 -07001698 return false;
1699 }
1700 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001701 // Stop here if Google results are showing
1702 else if ($("#searchResults").is(":visible")) {
1703 return true;
1704 }
1705 // 38 UP ARROW
Scott Mainf5089842012-08-14 16:31:07 -07001706 else if (kd && (e.keyCode == 38)) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001707 // if the next item is a header, skip it
1708 if ($($("li", $selectedUl)[gSelectedIndex-1]).hasClass("header")) {
Scott Mainf5089842012-08-14 16:31:07 -07001709 gSelectedIndex--;
Scott Main7e447ed2013-02-19 17:22:37 -08001710 }
1711 if (gSelectedIndex >= 0) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001712 $('li', $selectedUl).removeClass('jd-selected');
Scott Main7e447ed2013-02-19 17:22:37 -08001713 gSelectedIndex--;
Scott Main0e76e7e2013-03-12 10:24:07 -07001714 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1715 // If user reaches top, reset selected column
1716 if (gSelectedIndex < 0) {
1717 gSelectedColumn = -1;
1718 }
Scott Mainf5089842012-08-14 16:31:07 -07001719 }
1720 return false;
1721 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001722 // 40 DOWN ARROW
Scott Mainf5089842012-08-14 16:31:07 -07001723 else if (kd && (e.keyCode == 40)) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001724 // if the next item is a header, skip it
1725 if ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header")) {
Scott Mainf5089842012-08-14 16:31:07 -07001726 gSelectedIndex++;
Scott Main7e447ed2013-02-19 17:22:37 -08001727 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001728 if ((gSelectedIndex < $("li", $selectedUl).length-1) ||
1729 ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header"))) {
1730 $('li', $selectedUl).removeClass('jd-selected');
Scott Main7e447ed2013-02-19 17:22:37 -08001731 gSelectedIndex++;
Scott Main0e76e7e2013-03-12 10:24:07 -07001732 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
Scott Mainf5089842012-08-14 16:31:07 -07001733 }
1734 return false;
1735 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001736 // Consider left/right arrow navigation
1737 // NOTE: Order of suggest columns are reverse order (index position 0 is on right)
1738 else if (kd && $columns.length > 1 && gSelectedColumn >= 0) {
1739 // 37 LEFT ARROW
1740 // go left only if current column is not left-most column (last column)
1741 if (e.keyCode == 37 && gSelectedColumn < $columns.length - 1) {
1742 $('li', $selectedUl).removeClass('jd-selected');
1743 gSelectedColumn++;
1744 $selectedUl = $columns[gSelectedColumn];
1745 // keep or reset the selected item to last item as appropriate
1746 gSelectedIndex = gSelectedIndex >
1747 $("li", $selectedUl).length-1 ?
1748 $("li", $selectedUl).length-1 : gSelectedIndex;
1749 // if the corresponding item is a header, move down
1750 if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
1751 gSelectedIndex++;
1752 }
Scott Main3b90aff2013-08-01 18:09:35 -07001753 // set item selected
Scott Main0e76e7e2013-03-12 10:24:07 -07001754 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1755 return false;
1756 }
1757 // 39 RIGHT ARROW
1758 // go right only if current column is not the right-most column (first column)
1759 else if (e.keyCode == 39 && gSelectedColumn > 0) {
1760 $('li', $selectedUl).removeClass('jd-selected');
1761 gSelectedColumn--;
1762 $selectedUl = $columns[gSelectedColumn];
1763 // keep or reset the selected item to last item as appropriate
1764 gSelectedIndex = gSelectedIndex >
1765 $("li", $selectedUl).length-1 ?
1766 $("li", $selectedUl).length-1 : gSelectedIndex;
1767 // if the corresponding item is a header, move down
1768 if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
1769 gSelectedIndex++;
1770 }
Scott Main3b90aff2013-08-01 18:09:35 -07001771 // set item selected
Scott Main0e76e7e2013-03-12 10:24:07 -07001772 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1773 return false;
1774 }
1775 }
1776
Scott Main7e447ed2013-02-19 17:22:37 -08001777 // if key-up event and not arrow down/up,
1778 // read the search query and add suggestsions to gMatches
Scott Main0e76e7e2013-03-12 10:24:07 -07001779 else if (!kd && (e.keyCode != 40)
1780 && (e.keyCode != 38)
1781 && (e.keyCode != 37)
1782 && (e.keyCode != 39)) {
1783 gSelectedIndex = -1;
Scott Mainf5089842012-08-14 16:31:07 -07001784 gMatches = new Array();
1785 matchedCount = 0;
Scott Main7e447ed2013-02-19 17:22:37 -08001786 gGoogleMatches = new Array();
1787 matchedCountGoogle = 0;
Scott Main0e76e7e2013-03-12 10:24:07 -07001788 gDocsMatches = new Array();
1789 matchedCountDocs = 0;
Scott Main7e447ed2013-02-19 17:22:37 -08001790
1791 // Search for Android matches
Scott Mainf5089842012-08-14 16:31:07 -07001792 for (var i=0; i<DATA.length; i++) {
1793 var s = DATA[i];
1794 if (text.length != 0 &&
1795 s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
1796 gMatches[matchedCount] = s;
1797 matchedCount++;
1798 }
1799 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001800 rank_autocomplete_api_results(text, gMatches);
Scott Mainf5089842012-08-14 16:31:07 -07001801 for (var i=0; i<gMatches.length; i++) {
1802 var s = gMatches[i];
Scott Main7e447ed2013-02-19 17:22:37 -08001803 }
1804
1805
1806 // Search for Google matches
1807 for (var i=0; i<GOOGLE_DATA.length; i++) {
1808 var s = GOOGLE_DATA[i];
1809 if (text.length != 0 &&
1810 s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
1811 gGoogleMatches[matchedCountGoogle] = s;
1812 matchedCountGoogle++;
Scott Mainf5089842012-08-14 16:31:07 -07001813 }
1814 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001815 rank_autocomplete_api_results(text, gGoogleMatches);
Scott Main7e447ed2013-02-19 17:22:37 -08001816 for (var i=0; i<gGoogleMatches.length; i++) {
1817 var s = gGoogleMatches[i];
1818 }
1819
Scott Mainf5089842012-08-14 16:31:07 -07001820 highlight_autocomplete_result_labels(text);
Scott Main0e76e7e2013-03-12 10:24:07 -07001821
1822
1823
1824 // Search for JD docs
1825 if (text.length >= 3) {
1826 for (var i=0; i<JD_DATA.length; i++) {
1827 // Regex to match only the beginning of a word
1828 var textRegex = new RegExp("\\b" + text.toLowerCase(), "g");
1829 // current search comparison, with counters for tag and title,
1830 // used later to improve ranking
1831 var s = JD_DATA[i];
1832 s.matched_tag = 0;
1833 s.matched_title = 0;
1834 var matched = false;
1835
1836 // Check if query matches any tags; work backwards toward 1 to assist ranking
1837 for (var j = s.tags.length - 1; j >= 0; j--) {
1838 // it matches a tag
1839 if (s.tags[j].toLowerCase().match(textRegex)) {
1840 matched = true;
1841 s.matched_tag = j + 1; // add 1 to index position
1842 }
1843 }
1844 // Don't consider doc title for lessons (only for class landing pages)
1845 // ...it is not a training lesson (or is but has matched a tag)
1846 if (!(s.type == "training" && s.link.indexOf("index.html") == -1) || matched) {
1847 // it matches the doc title
1848 if (s.label.toLowerCase().match(textRegex)) {
1849 matched = true;
1850 s.matched_title = 1;
1851 }
1852 }
1853 if (matched) {
1854 gDocsMatches[matchedCountDocs] = s;
1855 matchedCountDocs++;
1856 }
1857 }
1858 rank_autocomplete_doc_results(text, gDocsMatches);
1859 }
1860
1861 // draw the suggestions
Scott Mainf5089842012-08-14 16:31:07 -07001862 sync_selection_table(toroot);
1863 return true; // allow the event to bubble up to the search api
1864 }
1865}
1866
Scott Main0e76e7e2013-03-12 10:24:07 -07001867/* Order the jd doc result list based on match quality */
1868function rank_autocomplete_doc_results(query, matches) {
1869 query = query || '';
1870 if (!matches || !matches.length)
1871 return;
1872
1873 var _resultScoreFn = function(match) {
1874 var score = 1.0;
1875
1876 // if the query matched a tag
1877 if (match.matched_tag > 0) {
1878 // multiply score by factor relative to position in tags list (max of 3)
1879 score *= 3 / match.matched_tag;
1880
1881 // if it also matched the title
1882 if (match.matched_title > 0) {
1883 score *= 2;
1884 }
1885 } else if (match.matched_title > 0) {
1886 score *= 3;
1887 }
1888
1889 return score;
1890 };
1891
1892 for (var i=0; i<matches.length; i++) {
1893 matches[i].__resultScore = _resultScoreFn(matches[i]);
1894 }
1895
1896 matches.sort(function(a,b){
1897 var n = b.__resultScore - a.__resultScore;
1898 if (n == 0) // lexicographical sort if scores are the same
1899 n = (a.label < b.label) ? -1 : 1;
1900 return n;
1901 });
1902}
1903
Scott Main7e447ed2013-02-19 17:22:37 -08001904/* Order the result list based on match quality */
Scott Main0e76e7e2013-03-12 10:24:07 -07001905function rank_autocomplete_api_results(query, matches) {
Scott Mainf5089842012-08-14 16:31:07 -07001906 query = query || '';
Scott Main7e447ed2013-02-19 17:22:37 -08001907 if (!matches || !matches.length)
Scott Mainf5089842012-08-14 16:31:07 -07001908 return;
1909
1910 // helper function that gets the last occurence index of the given regex
1911 // in the given string, or -1 if not found
1912 var _lastSearch = function(s, re) {
1913 if (s == '')
1914 return -1;
1915 var l = -1;
1916 var tmp;
1917 while ((tmp = s.search(re)) >= 0) {
1918 if (l < 0) l = 0;
1919 l += tmp;
1920 s = s.substr(tmp + 1);
1921 }
1922 return l;
1923 };
1924
1925 // helper function that counts the occurrences of a given character in
1926 // a given string
1927 var _countChar = function(s, c) {
1928 var n = 0;
1929 for (var i=0; i<s.length; i++)
1930 if (s.charAt(i) == c) ++n;
1931 return n;
1932 };
1933
1934 var queryLower = query.toLowerCase();
1935 var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
1936 var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
1937 var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
1938
1939 var _resultScoreFn = function(result) {
1940 // scores are calculated based on exact and prefix matches,
1941 // and then number of path separators (dots) from the last
1942 // match (i.e. favoring classes and deep package names)
1943 var score = 1.0;
1944 var labelLower = result.label.toLowerCase();
1945 var t;
1946 t = _lastSearch(labelLower, partExactAlnumRE);
1947 if (t >= 0) {
1948 // exact part match
1949 var partsAfter = _countChar(labelLower.substr(t + 1), '.');
1950 score *= 200 / (partsAfter + 1);
1951 } else {
1952 t = _lastSearch(labelLower, partPrefixAlnumRE);
1953 if (t >= 0) {
1954 // part prefix match
1955 var partsAfter = _countChar(labelLower.substr(t + 1), '.');
1956 score *= 20 / (partsAfter + 1);
1957 }
1958 }
1959
1960 return score;
1961 };
1962
Scott Main7e447ed2013-02-19 17:22:37 -08001963 for (var i=0; i<matches.length; i++) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001964 // if the API is deprecated, default score is 0; otherwise, perform scoring
1965 if (matches[i].deprecated == "true") {
1966 matches[i].__resultScore = 0;
1967 } else {
1968 matches[i].__resultScore = _resultScoreFn(matches[i]);
1969 }
Scott Mainf5089842012-08-14 16:31:07 -07001970 }
1971
Scott Main7e447ed2013-02-19 17:22:37 -08001972 matches.sort(function(a,b){
Scott Mainf5089842012-08-14 16:31:07 -07001973 var n = b.__resultScore - a.__resultScore;
1974 if (n == 0) // lexicographical sort if scores are the same
1975 n = (a.label < b.label) ? -1 : 1;
1976 return n;
1977 });
1978}
1979
Scott Main7e447ed2013-02-19 17:22:37 -08001980/* Add emphasis to part of string that matches query */
Scott Mainf5089842012-08-14 16:31:07 -07001981function highlight_autocomplete_result_labels(query) {
1982 query = query || '';
Scott Main7e447ed2013-02-19 17:22:37 -08001983 if ((!gMatches || !gMatches.length) && (!gGoogleMatches || !gGoogleMatches.length))
Scott Mainf5089842012-08-14 16:31:07 -07001984 return;
1985
1986 var queryLower = query.toLowerCase();
1987 var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
1988 var queryRE = new RegExp(
1989 '(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
1990 for (var i=0; i<gMatches.length; i++) {
1991 gMatches[i].__hilabel = gMatches[i].label.replace(
1992 queryRE, '<b>$1</b>');
1993 }
Scott Main7e447ed2013-02-19 17:22:37 -08001994 for (var i=0; i<gGoogleMatches.length; i++) {
1995 gGoogleMatches[i].__hilabel = gGoogleMatches[i].label.replace(
1996 queryRE, '<b>$1</b>');
1997 }
Scott Mainf5089842012-08-14 16:31:07 -07001998}
1999
2000function search_focus_changed(obj, focused)
2001{
Scott Main3b90aff2013-08-01 18:09:35 -07002002 if (!focused) {
Scott Mainf5089842012-08-14 16:31:07 -07002003 if(obj.value == ""){
2004 $(".search .close").addClass("hide");
2005 }
Scott Main0e76e7e2013-03-12 10:24:07 -07002006 $(".suggest-card").hide();
Scott Mainf5089842012-08-14 16:31:07 -07002007 }
2008}
2009
2010function submit_search() {
2011 var query = document.getElementById('search_autocomplete').value;
2012 location.hash = 'q=' + query;
2013 loadSearchResults();
2014 $("#searchResults").slideDown('slow');
2015 return false;
2016}
2017
2018
2019function hideResults() {
2020 $("#searchResults").slideUp();
2021 $(".search .close").addClass("hide");
2022 location.hash = '';
Scott Main3b90aff2013-08-01 18:09:35 -07002023
Scott Mainf5089842012-08-14 16:31:07 -07002024 $("#search_autocomplete").val("").blur();
Scott Main3b90aff2013-08-01 18:09:35 -07002025
Scott Mainf5089842012-08-14 16:31:07 -07002026 // reset the ajax search callback to nothing, so results don't appear unless ENTER
2027 searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
Scott Main0e76e7e2013-03-12 10:24:07 -07002028
2029 // forcefully regain key-up event control (previously jacked by search api)
2030 $("#search_autocomplete").keyup(function(event) {
2031 return search_changed(event, false, toRoot);
2032 });
2033
Scott Mainf5089842012-08-14 16:31:07 -07002034 return false;
2035}
2036
2037
2038
2039/* ########################################################## */
2040/* ################ CUSTOM SEARCH ENGINE ################## */
2041/* ########################################################## */
2042
Scott Mainf5089842012-08-14 16:31:07 -07002043var searchControl;
Scott Main0e76e7e2013-03-12 10:24:07 -07002044google.load('search', '1', {"callback" : function() {
2045 searchControl = new google.search.SearchControl();
2046 } });
Scott Mainf5089842012-08-14 16:31:07 -07002047
2048function loadSearchResults() {
2049 document.getElementById("search_autocomplete").style.color = "#000";
2050
Scott Mainf5089842012-08-14 16:31:07 -07002051 searchControl = new google.search.SearchControl();
2052
2053 // use our existing search form and use tabs when multiple searchers are used
2054 drawOptions = new google.search.DrawOptions();
2055 drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
2056 drawOptions.setInput(document.getElementById("search_autocomplete"));
2057
2058 // configure search result options
2059 searchOptions = new google.search.SearcherOptions();
2060 searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
2061
2062 // configure each of the searchers, for each tab
2063 devSiteSearcher = new google.search.WebSearch();
2064 devSiteSearcher.setUserDefinedLabel("All");
2065 devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
2066
2067 designSearcher = new google.search.WebSearch();
2068 designSearcher.setUserDefinedLabel("Design");
2069 designSearcher.setSiteRestriction("http://developer.android.com/design/");
2070
2071 trainingSearcher = new google.search.WebSearch();
2072 trainingSearcher.setUserDefinedLabel("Training");
2073 trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
2074
2075 guidesSearcher = new google.search.WebSearch();
2076 guidesSearcher.setUserDefinedLabel("Guides");
2077 guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
2078
2079 referenceSearcher = new google.search.WebSearch();
2080 referenceSearcher.setUserDefinedLabel("Reference");
2081 referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
2082
Scott Maindf08ada2012-12-03 08:54:37 -08002083 googleSearcher = new google.search.WebSearch();
2084 googleSearcher.setUserDefinedLabel("Google Services");
2085 googleSearcher.setSiteRestriction("http://developer.android.com/google/");
2086
Scott Mainf5089842012-08-14 16:31:07 -07002087 blogSearcher = new google.search.WebSearch();
2088 blogSearcher.setUserDefinedLabel("Blog");
2089 blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
2090
2091 // add each searcher to the search control
2092 searchControl.addSearcher(devSiteSearcher, searchOptions);
2093 searchControl.addSearcher(designSearcher, searchOptions);
2094 searchControl.addSearcher(trainingSearcher, searchOptions);
2095 searchControl.addSearcher(guidesSearcher, searchOptions);
2096 searchControl.addSearcher(referenceSearcher, searchOptions);
Scott Maindf08ada2012-12-03 08:54:37 -08002097 searchControl.addSearcher(googleSearcher, searchOptions);
Scott Mainf5089842012-08-14 16:31:07 -07002098 searchControl.addSearcher(blogSearcher, searchOptions);
2099
2100 // configure result options
2101 searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
2102 searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
2103 searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
2104 searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
2105
2106 // upon ajax search, refresh the url and search title
2107 searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
2108 updateResultTitle(query);
2109 var query = document.getElementById('search_autocomplete').value;
2110 location.hash = 'q=' + query;
2111 });
2112
Scott Mainde295272013-03-25 15:48:35 -07002113 // once search results load, set up click listeners
2114 searchControl.setSearchCompleteCallback(this, function(control, searcher, query) {
2115 addResultClickListeners();
2116 });
2117
Scott Mainf5089842012-08-14 16:31:07 -07002118 // draw the search results box
2119 searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
2120
2121 // get query and execute the search
2122 searchControl.execute(decodeURI(getQuery(location.hash)));
2123
2124 document.getElementById("search_autocomplete").focus();
2125 addTabListeners();
2126}
2127// End of loadSearchResults
2128
2129
2130google.setOnLoadCallback(function(){
2131 if (location.hash.indexOf("q=") == -1) {
2132 // if there's no query in the url, don't search and make sure results are hidden
2133 $('#searchResults').hide();
2134 return;
2135 } else {
2136 // first time loading search results for this page
2137 $('#searchResults').slideDown('slow');
2138 $(".search .close").removeClass("hide");
2139 loadSearchResults();
2140 }
2141}, true);
2142
2143// when an event on the browser history occurs (back, forward, load) requery hash and do search
2144$(window).hashchange( function(){
2145 // Exit if the hash isn't a search query or there's an error in the query
2146 if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
2147 // If the results pane is open, close it.
2148 if (!$("#searchResults").is(":hidden")) {
2149 hideResults();
2150 }
2151 return;
2152 }
2153
2154 // Otherwise, we have a search to do
2155 var query = decodeURI(getQuery(location.hash));
2156 searchControl.execute(query);
2157 $('#searchResults').slideDown('slow');
2158 $("#search_autocomplete").focus();
2159 $(".search .close").removeClass("hide");
2160
2161 updateResultTitle(query);
2162});
2163
2164function updateResultTitle(query) {
2165 $("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
2166}
2167
2168// forcefully regain key-up event control (previously jacked by search api)
2169$("#search_autocomplete").keyup(function(event) {
2170 return search_changed(event, false, toRoot);
2171});
2172
2173// add event listeners to each tab so we can track the browser history
2174function addTabListeners() {
2175 var tabHeaders = $(".gsc-tabHeader");
2176 for (var i = 0; i < tabHeaders.length; i++) {
2177 $(tabHeaders[i]).attr("id",i).click(function() {
2178 /*
2179 // make a copy of the page numbers for the search left pane
2180 setTimeout(function() {
2181 // remove any residual page numbers
2182 $('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
Scott Main3b90aff2013-08-01 18:09:35 -07002183 // move the page numbers to the left position; make a clone,
Scott Mainf5089842012-08-14 16:31:07 -07002184 // because the element is drawn to the DOM only once
Scott Main3b90aff2013-08-01 18:09:35 -07002185 // and because we're going to remove it (previous line),
2186 // we need it to be available to move again as the user navigates
Scott Mainf5089842012-08-14 16:31:07 -07002187 $('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
2188 .clone().appendTo('#searchResults .gsc-tabsArea');
2189 }, 200);
2190 */
2191 });
2192 }
2193 setTimeout(function(){$(tabHeaders[0]).click()},200);
2194}
2195
Scott Mainde295272013-03-25 15:48:35 -07002196// add analytics tracking events to each result link
2197function addResultClickListeners() {
2198 $("#searchResults a.gs-title").each(function(index, link) {
2199 // When user clicks enter for Google search results, track it
2200 $(link).click(function() {
2201 _gaq.push(['_trackEvent', 'Google Click', 'clicked: ' + $(this).text(),
2202 'from: ' + $("#search_autocomplete").val()]);
2203 });
2204 });
2205}
2206
Scott Mainf5089842012-08-14 16:31:07 -07002207
2208function getQuery(hash) {
2209 var queryParts = hash.split('=');
2210 return queryParts[1];
2211}
2212
2213/* returns the given string with all HTML brackets converted to entities
2214 TODO: move this to the site's JS library */
2215function escapeHTML(string) {
2216 return string.replace(/</g,"&lt;")
2217 .replace(/>/g,"&gt;");
2218}
2219
2220
2221
2222
2223
2224
2225
2226/* ######################################################## */
2227/* ################# JAVADOC REFERENCE ################### */
2228/* ######################################################## */
2229
Scott Main65511c02012-09-07 15:51:32 -07002230/* Initialize some droiddoc stuff, but only if we're in the reference */
Scott Main52dd2062013-08-15 12:22:28 -07002231if (location.pathname.indexOf("/reference") == 0) {
2232 if(!(location.pathname.indexOf("/reference-gms/packages.html") == 0)
2233 && !(location.pathname.indexOf("/reference-gcm/packages.html") == 0)
2234 && !(location.pathname.indexOf("/reference/com/google") == 0)) {
Robert Ly67d75f12012-12-03 12:53:42 -08002235 $(document).ready(function() {
2236 // init available apis based on user pref
2237 changeApiLevel();
2238 initSidenavHeightResize()
2239 });
2240 }
Scott Main65511c02012-09-07 15:51:32 -07002241}
Scott Mainf5089842012-08-14 16:31:07 -07002242
2243var API_LEVEL_COOKIE = "api_level";
2244var minLevel = 1;
2245var maxLevel = 1;
2246
2247/******* SIDENAV DIMENSIONS ************/
Scott Main3b90aff2013-08-01 18:09:35 -07002248
Scott Mainf5089842012-08-14 16:31:07 -07002249 function initSidenavHeightResize() {
2250 // Change the drag bar size to nicely fit the scrollbar positions
2251 var $dragBar = $(".ui-resizable-s");
2252 $dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
Scott Main3b90aff2013-08-01 18:09:35 -07002253
2254 $( "#resize-packages-nav" ).resizable({
Scott Mainf5089842012-08-14 16:31:07 -07002255 containment: "#nav-panels",
2256 handles: "s",
2257 alsoResize: "#packages-nav",
2258 resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
2259 stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
2260 });
Scott Main3b90aff2013-08-01 18:09:35 -07002261
Scott Mainf5089842012-08-14 16:31:07 -07002262 }
Scott Main3b90aff2013-08-01 18:09:35 -07002263
Scott Mainf5089842012-08-14 16:31:07 -07002264function updateSidenavFixedWidth() {
2265 if (!navBarIsFixed) return;
2266 $('#devdoc-nav').css({
2267 'width' : $('#side-nav').css('width'),
2268 'margin' : $('#side-nav').css('margin')
2269 });
2270 $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
Scott Main3b90aff2013-08-01 18:09:35 -07002271
Scott Mainf5089842012-08-14 16:31:07 -07002272 initSidenavHeightResize();
2273}
2274
2275function updateSidenavFullscreenWidth() {
2276 if (!navBarIsFixed) return;
2277 $('#devdoc-nav').css({
2278 'width' : $('#side-nav').css('width'),
2279 'margin' : $('#side-nav').css('margin')
2280 });
2281 $('#devdoc-nav .totop').css({'left': 'inherit'});
Scott Main3b90aff2013-08-01 18:09:35 -07002282
Scott Mainf5089842012-08-14 16:31:07 -07002283 initSidenavHeightResize();
2284}
2285
2286function buildApiLevelSelector() {
2287 maxLevel = SINCE_DATA.length;
2288 var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
2289 userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
2290
2291 minLevel = parseInt($("#doc-api-level").attr("class"));
2292 // Handle provisional api levels; the provisional level will always be the highest possible level
2293 // Provisional api levels will also have a length; other stuff that's just missing a level won't,
2294 // so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
2295 if (isNaN(minLevel) && minLevel.length) {
2296 minLevel = maxLevel;
2297 }
2298 var select = $("#apiLevelSelector").html("").change(changeApiLevel);
2299 for (var i = maxLevel-1; i >= 0; i--) {
2300 var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
2301 // if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
2302 select.append(option);
2303 }
2304
2305 // get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
2306 var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
2307 selectedLevelItem.setAttribute('selected',true);
2308}
2309
2310function changeApiLevel() {
2311 maxLevel = SINCE_DATA.length;
2312 var selectedLevel = maxLevel;
2313
2314 selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
2315 toggleVisisbleApis(selectedLevel, "body");
2316
2317 var date = new Date();
2318 date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
2319 var expiration = date.toGMTString();
2320 writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
2321
2322 if (selectedLevel < minLevel) {
2323 var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
Scott Main8f24ca82012-11-16 10:34:22 -08002324 $("#naMessage").show().html("<div><p><strong>This " + thing
2325 + " requires API level " + minLevel + " or higher.</strong></p>"
2326 + "<p>This document is hidden because your selected API level for the documentation is "
2327 + selectedLevel + ". You can change the documentation API level with the selector "
2328 + "above the left navigation.</p>"
2329 + "<p>For more information about specifying the API level your app requires, "
2330 + "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
2331 + ">Supporting Different Platform Versions</a>.</p>"
2332 + "<input type='button' value='OK, make this page visible' "
2333 + "title='Change the API level to " + minLevel + "' "
2334 + "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
2335 + "</div>");
Scott Mainf5089842012-08-14 16:31:07 -07002336 } else {
2337 $("#naMessage").hide();
2338 }
2339}
2340
2341function toggleVisisbleApis(selectedLevel, context) {
2342 var apis = $(".api",context);
2343 apis.each(function(i) {
2344 var obj = $(this);
2345 var className = obj.attr("class");
2346 var apiLevelIndex = className.lastIndexOf("-")+1;
2347 var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
2348 apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
2349 var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
2350 if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
2351 return;
2352 }
2353 apiLevel = parseInt(apiLevel);
2354
2355 // Handle provisional api levels; if this item's level is the provisional one, set it to the max
2356 var selectedLevelNum = parseInt(selectedLevel)
2357 var apiLevelNum = parseInt(apiLevel);
2358 if (isNaN(apiLevelNum)) {
2359 apiLevelNum = maxLevel;
2360 }
2361
2362 // Grey things out that aren't available and give a tooltip title
2363 if (apiLevelNum > selectedLevelNum) {
2364 obj.addClass("absent").attr("title","Requires API Level \""
2365 + apiLevel + "\" or higher");
Scott Main3b90aff2013-08-01 18:09:35 -07002366 }
Scott Mainf5089842012-08-14 16:31:07 -07002367 else obj.removeClass("absent").removeAttr("title");
2368 });
2369}
2370
2371
2372
2373
2374/* ################# SIDENAV TREE VIEW ################### */
2375
2376function new_node(me, mom, text, link, children_data, api_level)
2377{
2378 var node = new Object();
2379 node.children = Array();
2380 node.children_data = children_data;
2381 node.depth = mom.depth + 1;
2382
2383 node.li = document.createElement("li");
2384 mom.get_children_ul().appendChild(node.li);
2385
2386 node.label_div = document.createElement("div");
2387 node.label_div.className = "label";
2388 if (api_level != null) {
2389 $(node.label_div).addClass("api");
2390 $(node.label_div).addClass("api-level-"+api_level);
2391 }
2392 node.li.appendChild(node.label_div);
2393
2394 if (children_data != null) {
2395 node.expand_toggle = document.createElement("a");
2396 node.expand_toggle.href = "javascript:void(0)";
2397 node.expand_toggle.onclick = function() {
2398 if (node.expanded) {
2399 $(node.get_children_ul()).slideUp("fast");
2400 node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
2401 node.expanded = false;
2402 } else {
2403 expand_node(me, node);
2404 }
2405 };
2406 node.label_div.appendChild(node.expand_toggle);
2407
2408 node.plus_img = document.createElement("img");
2409 node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
2410 node.plus_img.className = "plus";
2411 node.plus_img.width = "8";
2412 node.plus_img.border = "0";
2413 node.expand_toggle.appendChild(node.plus_img);
2414
2415 node.expanded = false;
2416 }
2417
2418 var a = document.createElement("a");
2419 node.label_div.appendChild(a);
2420 node.label = document.createTextNode(text);
2421 a.appendChild(node.label);
2422 if (link) {
2423 a.href = me.toroot + link;
2424 } else {
2425 if (children_data != null) {
2426 a.className = "nolink";
2427 a.href = "javascript:void(0)";
2428 a.onclick = node.expand_toggle.onclick;
2429 // This next line shouldn't be necessary. I'll buy a beer for the first
2430 // person who figures out how to remove this line and have the link
2431 // toggle shut on the first try. --joeo@android.com
2432 node.expanded = false;
2433 }
2434 }
Scott Main3b90aff2013-08-01 18:09:35 -07002435
Scott Mainf5089842012-08-14 16:31:07 -07002436
2437 node.children_ul = null;
2438 node.get_children_ul = function() {
2439 if (!node.children_ul) {
2440 node.children_ul = document.createElement("ul");
2441 node.children_ul.className = "children_ul";
2442 node.children_ul.style.display = "none";
2443 node.li.appendChild(node.children_ul);
2444 }
2445 return node.children_ul;
2446 };
2447
2448 return node;
2449}
2450
Robert Lyd2dd6e52012-11-29 21:28:48 -08002451
2452
2453
Scott Mainf5089842012-08-14 16:31:07 -07002454function expand_node(me, node)
2455{
2456 if (node.children_data && !node.expanded) {
2457 if (node.children_visited) {
2458 $(node.get_children_ul()).slideDown("fast");
2459 } else {
2460 get_node(me, node);
2461 if ($(node.label_div).hasClass("absent")) {
2462 $(node.get_children_ul()).addClass("absent");
Scott Main3b90aff2013-08-01 18:09:35 -07002463 }
Scott Mainf5089842012-08-14 16:31:07 -07002464 $(node.get_children_ul()).slideDown("fast");
2465 }
2466 node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
2467 node.expanded = true;
2468
2469 // perform api level toggling because new nodes are new to the DOM
2470 var selectedLevel = $("#apiLevelSelector option:selected").val();
2471 toggleVisisbleApis(selectedLevel, "#side-nav");
2472 }
2473}
2474
2475function get_node(me, mom)
2476{
2477 mom.children_visited = true;
2478 for (var i in mom.children_data) {
2479 var node_data = mom.children_data[i];
2480 mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
2481 node_data[2], node_data[3]);
2482 }
2483}
2484
2485function this_page_relative(toroot)
2486{
2487 var full = document.location.pathname;
2488 var file = "";
2489 if (toroot.substr(0, 1) == "/") {
2490 if (full.substr(0, toroot.length) == toroot) {
2491 return full.substr(toroot.length);
2492 } else {
2493 // the file isn't under toroot. Fail.
2494 return null;
2495 }
2496 } else {
2497 if (toroot != "./") {
2498 toroot = "./" + toroot;
2499 }
2500 do {
2501 if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
2502 var pos = full.lastIndexOf("/");
2503 file = full.substr(pos) + file;
2504 full = full.substr(0, pos);
2505 toroot = toroot.substr(0, toroot.length-3);
2506 }
2507 } while (toroot != "" && toroot != "/");
2508 return file.substr(1);
2509 }
2510}
2511
2512function find_page(url, data)
2513{
2514 var nodes = data;
2515 var result = null;
2516 for (var i in nodes) {
2517 var d = nodes[i];
2518 if (d[1] == url) {
2519 return new Array(i);
2520 }
2521 else if (d[2] != null) {
2522 result = find_page(url, d[2]);
2523 if (result != null) {
2524 return (new Array(i).concat(result));
2525 }
2526 }
2527 }
2528 return null;
2529}
2530
Scott Mainf5089842012-08-14 16:31:07 -07002531function init_default_navtree(toroot) {
Scott Main25e73002013-03-27 15:24:06 -07002532 // load json file for navtree data
2533 $.getScript(toRoot + 'navtree_data.js', function(data, textStatus, jqxhr) {
2534 // when the file is loaded, initialize the tree
2535 if(jqxhr.status === 200) {
2536 init_navtree("tree-list", toroot, NAVTREE_DATA);
2537 }
2538 });
Scott Main3b90aff2013-08-01 18:09:35 -07002539
Scott Mainf5089842012-08-14 16:31:07 -07002540 // perform api level toggling because because the whole tree is new to the DOM
2541 var selectedLevel = $("#apiLevelSelector option:selected").val();
2542 toggleVisisbleApis(selectedLevel, "#side-nav");
2543}
2544
2545function init_navtree(navtree_id, toroot, root_nodes)
2546{
2547 var me = new Object();
2548 me.toroot = toroot;
2549 me.node = new Object();
2550
2551 me.node.li = document.getElementById(navtree_id);
2552 me.node.children_data = root_nodes;
2553 me.node.children = new Array();
2554 me.node.children_ul = document.createElement("ul");
2555 me.node.get_children_ul = function() { return me.node.children_ul; };
2556 //me.node.children_ul.className = "children_ul";
2557 me.node.li.appendChild(me.node.children_ul);
2558 me.node.depth = 0;
2559
2560 get_node(me, me.node);
2561
2562 me.this_page = this_page_relative(toroot);
2563 me.breadcrumbs = find_page(me.this_page, root_nodes);
2564 if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
2565 var mom = me.node;
2566 for (var i in me.breadcrumbs) {
2567 var j = me.breadcrumbs[i];
2568 mom = mom.children[j];
2569 expand_node(me, mom);
2570 }
2571 mom.label_div.className = mom.label_div.className + " selected";
2572 addLoadEvent(function() {
2573 scrollIntoView("nav-tree");
2574 });
2575 }
2576}
2577
Dirk Dougherty4f7e5152010-09-16 10:43:40 -07002578
2579
2580
2581
2582
2583
2584
Robert Lyd2dd6e52012-11-29 21:28:48 -08002585/* TODO: eliminate redundancy with non-google functions */
2586function init_google_navtree(navtree_id, toroot, root_nodes)
2587{
2588 var me = new Object();
2589 me.toroot = toroot;
2590 me.node = new Object();
2591
2592 me.node.li = document.getElementById(navtree_id);
2593 me.node.children_data = root_nodes;
2594 me.node.children = new Array();
2595 me.node.children_ul = document.createElement("ul");
2596 me.node.get_children_ul = function() { return me.node.children_ul; };
2597 //me.node.children_ul.className = "children_ul";
2598 me.node.li.appendChild(me.node.children_ul);
2599 me.node.depth = 0;
2600
2601 get_google_node(me, me.node);
Robert Lyd2dd6e52012-11-29 21:28:48 -08002602}
2603
2604function new_google_node(me, mom, text, link, children_data, api_level)
2605{
2606 var node = new Object();
2607 var child;
2608 node.children = Array();
2609 node.children_data = children_data;
2610 node.depth = mom.depth + 1;
2611 node.get_children_ul = function() {
2612 if (!node.children_ul) {
Scott Main3b90aff2013-08-01 18:09:35 -07002613 node.children_ul = document.createElement("ul");
2614 node.children_ul.className = "tree-list-children";
Robert Lyd2dd6e52012-11-29 21:28:48 -08002615 node.li.appendChild(node.children_ul);
2616 }
2617 return node.children_ul;
2618 };
2619 node.li = document.createElement("li");
2620
2621 mom.get_children_ul().appendChild(node.li);
Scott Main3b90aff2013-08-01 18:09:35 -07002622
2623
Robert Lyd2dd6e52012-11-29 21:28:48 -08002624 if(link) {
2625 child = document.createElement("a");
2626
2627 }
2628 else {
2629 child = document.createElement("span");
Scott Mainac71b2b2012-11-30 14:40:58 -08002630 child.className = "tree-list-subtitle";
Robert Lyd2dd6e52012-11-29 21:28:48 -08002631
2632 }
2633 if (children_data != null) {
2634 node.li.className="nav-section";
2635 node.label_div = document.createElement("div");
Scott Main3b90aff2013-08-01 18:09:35 -07002636 node.label_div.className = "nav-section-header-ref";
Robert Lyd2dd6e52012-11-29 21:28:48 -08002637 node.li.appendChild(node.label_div);
2638 get_google_node(me, node);
2639 node.label_div.appendChild(child);
2640 }
2641 else {
2642 node.li.appendChild(child);
2643 }
2644 if(link) {
2645 child.href = me.toroot + link;
2646 }
2647 node.label = document.createTextNode(text);
2648 child.appendChild(node.label);
2649
2650 node.children_ul = null;
2651
2652 return node;
2653}
2654
2655function get_google_node(me, mom)
2656{
2657 mom.children_visited = true;
2658 var linkText;
2659 for (var i in mom.children_data) {
2660 var node_data = mom.children_data[i];
2661 linkText = node_data[0];
2662
2663 if(linkText.match("^"+"com.google.android")=="com.google.android"){
2664 linkText = linkText.substr(19, linkText.length);
2665 }
2666 mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
2667 node_data[2], node_data[3]);
2668 }
2669}
Scott Mainad08f072013-08-20 16:49:57 -07002670
2671
2672
2673
2674
2675
2676/****** NEW version of script to build google and sample navs dynamically ******/
2677// TODO: update Google reference docs to tolerate this new implementation
2678
2679function init_google_navtree2(navtree_id, data)
2680{
2681 var $containerUl = $("#"+navtree_id);
2682 var linkText;
2683 for (var i in data) {
2684 var node_data = data[i];
2685 $containerUl.append(new_google_node2(node_data));
2686 }
2687
2688 initExpandableNavItems("#"+navtree_id);
2689}
2690
2691function new_google_node2(node_data)
2692{
2693 var linkText = node_data[0];
2694 if(linkText.match("^"+"com.google.android")=="com.google.android"){
2695 linkText = linkText.substr(19, linkText.length);
2696 }
2697 var $li = $('<li>');
2698 var $a;
2699 if (node_data[1] != null) {
2700 $a = $('<a href="' + toRoot + node_data[1] + '">' + linkText + '</a>');
2701 } else {
2702 $a = $('<a href="#" onclick="return false;">' + linkText + '/</a>');
2703 }
2704 var $childUl = $('<ul>');
2705 if (node_data[2] != null) {
2706 $li.addClass("nav-section");
2707 $a = $('<div class="nav-section-header">').append($a);
2708 if (node_data[1] == null) $a.addClass('empty');
2709
2710 for (var i in node_data[2]) {
2711 var child_node_data = node_data[2][i];
2712 $childUl.append(new_google_node2(child_node_data));
2713 }
2714 $li.append($childUl);
2715 }
2716 $li.prepend($a);
2717
2718 return $li;
2719}
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
Robert Lyd2dd6e52012-11-29 21:28:48 -08002731function showGoogleRefTree() {
2732 init_default_google_navtree(toRoot);
2733 init_default_gcm_navtree(toRoot);
Robert Lyd2dd6e52012-11-29 21:28:48 -08002734}
2735
2736function init_default_google_navtree(toroot) {
Scott Mainf6145542013-04-01 16:38:11 -07002737 // load json file for navtree data
2738 $.getScript(toRoot + 'gms_navtree_data.js', function(data, textStatus, jqxhr) {
2739 // when the file is loaded, initialize the tree
2740 if(jqxhr.status === 200) {
2741 init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
2742 highlightSidenav();
2743 resizeNav();
2744 }
2745 });
Robert Lyd2dd6e52012-11-29 21:28:48 -08002746}
2747
2748function init_default_gcm_navtree(toroot) {
Scott Mainf6145542013-04-01 16:38:11 -07002749 // load json file for navtree data
2750 $.getScript(toRoot + 'gcm_navtree_data.js', function(data, textStatus, jqxhr) {
2751 // when the file is loaded, initialize the tree
2752 if(jqxhr.status === 200) {
2753 init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
2754 highlightSidenav();
2755 resizeNav();
2756 }
2757 });
Robert Lyd2dd6e52012-11-29 21:28:48 -08002758}
2759
Dirk Dougherty4f7e5152010-09-16 10:43:40 -07002760function showSamplesRefTree() {
2761 init_default_samples_navtree(toRoot);
2762}
2763
2764function init_default_samples_navtree(toroot) {
2765 // load json file for navtree data
2766 $.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
2767 // when the file is loaded, initialize the tree
2768 if(jqxhr.status === 200) {
Scott Mainad08f072013-08-20 16:49:57 -07002769 init_google_navtree2("nav.samples-nav", SAMPLES_NAVTREE_DATA);
Dirk Dougherty4f7e5152010-09-16 10:43:40 -07002770 highlightSidenav();
2771 resizeNav();
2772 }
2773 });
2774}
2775
Scott Mainf5089842012-08-14 16:31:07 -07002776/* TOGGLE INHERITED MEMBERS */
2777
2778/* Toggle an inherited class (arrow toggle)
2779 * @param linkObj The link that was clicked.
2780 * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
2781 * 'null' to simply toggle.
2782 */
2783function toggleInherited(linkObj, expand) {
2784 var base = linkObj.getAttribute("id");
2785 var list = document.getElementById(base + "-list");
2786 var summary = document.getElementById(base + "-summary");
2787 var trigger = document.getElementById(base + "-trigger");
2788 var a = $(linkObj);
2789 if ( (expand == null && a.hasClass("closed")) || expand ) {
2790 list.style.display = "none";
2791 summary.style.display = "block";
2792 trigger.src = toRoot + "assets/images/triangle-opened.png";
2793 a.removeClass("closed");
2794 a.addClass("opened");
2795 } else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
2796 list.style.display = "block";
2797 summary.style.display = "none";
2798 trigger.src = toRoot + "assets/images/triangle-closed.png";
2799 a.removeClass("opened");
2800 a.addClass("closed");
2801 }
2802 return false;
2803}
2804
2805/* Toggle all inherited classes in a single table (e.g. all inherited methods)
2806 * @param linkObj The link that was clicked.
2807 * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
2808 * 'null' to simply toggle.
2809 */
2810function toggleAllInherited(linkObj, expand) {
2811 var a = $(linkObj);
2812 var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
2813 var expandos = $(".jd-expando-trigger", table);
2814 if ( (expand == null && a.text() == "[Expand]") || expand ) {
2815 expandos.each(function(i) {
2816 toggleInherited(this, true);
2817 });
2818 a.text("[Collapse]");
2819 } else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
2820 expandos.each(function(i) {
2821 toggleInherited(this, false);
2822 });
2823 a.text("[Expand]");
2824 }
2825 return false;
2826}
2827
2828/* Toggle all inherited members in the class (link in the class title)
2829 */
2830function toggleAllClassInherited() {
2831 var a = $("#toggleAllClassInherited"); // get toggle link from class title
2832 var toggles = $(".toggle-all", $("#body-content"));
2833 if (a.text() == "[Expand All]") {
2834 toggles.each(function(i) {
2835 toggleAllInherited(this, true);
2836 });
2837 a.text("[Collapse All]");
2838 } else {
2839 toggles.each(function(i) {
2840 toggleAllInherited(this, false);
2841 });
2842 a.text("[Expand All]");
2843 }
2844 return false;
2845}
2846
2847/* Expand all inherited members in the class. Used when initiating page search */
2848function ensureAllInheritedExpanded() {
2849 var toggles = $(".toggle-all", $("#body-content"));
2850 toggles.each(function(i) {
2851 toggleAllInherited(this, true);
2852 });
2853 $("#toggleAllClassInherited").text("[Collapse All]");
2854}
2855
2856
2857/* HANDLE KEY EVENTS
2858 * - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
2859 */
2860var agent = navigator['userAgent'].toLowerCase();
2861var mac = agent.indexOf("macintosh") != -1;
2862
2863$(document).keydown( function(e) {
2864var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
2865 if (control && e.which == 70) { // 70 is "F"
2866 ensureAllInheritedExpanded();
2867 }
2868});
Scott Main498d7102013-08-21 15:47:38 -07002869
2870
2871
2872
2873
2874
2875/* On-demand functions */
2876
2877/** Move sample code line numbers out of PRE block and into non-copyable column */
2878function initCodeLineNumbers() {
2879 var numbers = $("#codesample-block a.number");
2880 if (numbers.length) {
2881 $("#codesample-line-numbers").removeClass("hidden").append(numbers);
2882 }
2883
2884 $(document).ready(function() {
2885 // select entire line when clicked
2886 $("span.code-line").click(function() {
2887 if (!shifted) {
2888 selectText(this);
2889 }
2890 });
2891 // invoke line link on double click
2892 $(".code-line").dblclick(function() {
2893 document.location.hash = $(this).attr('id');
2894 });
2895 // highlight the line when hovering on the number
2896 $("#codesample-line-numbers a.number").mouseover(function() {
2897 var id = $(this).attr('href');
2898 $(id).css('background','#e7e7e7');
2899 });
2900 $("#codesample-line-numbers a.number").mouseout(function() {
2901 var id = $(this).attr('href');
2902 $(id).css('background','none');
2903 });
2904 });
2905}
2906
2907// create SHIFT key binder to avoid the selectText method when selecting multiple lines
2908var shifted = false;
2909$(document).bind('keyup keydown', function(e){shifted = e.shiftKey; return true;} );
2910
2911// courtesy of jasonedelman.com
2912function selectText(element) {
2913 var doc = document
2914 , range, selection
2915 ;
2916 if (doc.body.createTextRange) { //ms
2917 range = doc.body.createTextRange();
2918 range.moveToElementText(element);
2919 range.select();
2920 } else if (window.getSelection) { //all others
2921 selection = window.getSelection();
2922 range = doc.createRange();
2923 range.selectNodeContents(element);
2924 selection.removeAllRanges();
2925 selection.addRange(range);
2926 }
Scott Main285f0772013-08-22 23:22:09 +00002927}