blob: 25588f30fc45cac83358408e8f04fa0ce1c3a948 [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) {
1125 var div = $(obj.parentNode.parentNode);
1126 var toggleMe = $(".toggle-content-toggleme",div);
1127 if (div.hasClass("closed")) { // if it's closed, open it
1128 toggleMe.slideDown();
1129 $(".toggle-content-text", obj).toggle();
1130 div.removeClass("closed").addClass("open");
Scott Main3b90aff2013-08-01 18:09:35 -07001131 $(".toggle-content-img", 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
1135 $(".toggle-content-text", obj).toggle();
1136 div.removeClass("open").addClass("closed");
Scott Main3b90aff2013-08-01 18:09:35 -07001137 $(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
Scott Maine4d8f1b2012-06-21 18:03:05 -07001138 + "assets/images/triangle-closed.png");
1139 });
1140 }
1141 return false;
1142}
Scott Mainf5089842012-08-14 16:31:07 -07001143
1144
Scott Maindb3678b2012-10-23 14:13:41 -07001145/* New version of expandable content */
1146function toggleExpandable(link,id) {
1147 if($(id).is(':visible')) {
1148 $(id).slideUp();
1149 $(link).removeClass('expanded');
1150 } else {
1151 $(id).slideDown();
1152 $(link).addClass('expanded');
1153 }
1154}
1155
1156function hideExpandable(ids) {
1157 $(ids).slideUp();
Scott Main55d99832012-11-12 23:03:59 -08001158 $(ids).prev('h4').find('a.expandable').removeClass('expanded');
Scott Maindb3678b2012-10-23 14:13:41 -07001159}
1160
Scott Mainf5089842012-08-14 16:31:07 -07001161
1162
1163
1164
Scott Main3b90aff2013-08-01 18:09:35 -07001165/*
Scott Mainf5089842012-08-14 16:31:07 -07001166 * Slideshow 1.0
1167 * Used on /index.html and /develop/index.html for carousel
1168 *
1169 * Sample usage:
1170 * HTML -
1171 * <div class="slideshow-container">
1172 * <a href="" class="slideshow-prev">Prev</a>
1173 * <a href="" class="slideshow-next">Next</a>
1174 * <ul>
1175 * <li class="item"><img src="images/marquee1.jpg"></li>
1176 * <li class="item"><img src="images/marquee2.jpg"></li>
1177 * <li class="item"><img src="images/marquee3.jpg"></li>
1178 * <li class="item"><img src="images/marquee4.jpg"></li>
1179 * </ul>
1180 * </div>
1181 *
1182 * <script type="text/javascript">
1183 * $('.slideshow-container').dacSlideshow({
1184 * auto: true,
1185 * btnPrev: '.slideshow-prev',
1186 * btnNext: '.slideshow-next'
1187 * });
1188 * </script>
1189 *
1190 * Options:
1191 * btnPrev: optional identifier for previous button
1192 * btnNext: optional identifier for next button
Scott Maineb410352013-01-14 19:03:40 -08001193 * btnPause: optional identifier for pause button
Scott Mainf5089842012-08-14 16:31:07 -07001194 * auto: whether or not to auto-proceed
1195 * speed: animation speed
1196 * autoTime: time between auto-rotation
1197 * easing: easing function for transition
1198 * start: item to select by default
1199 * scroll: direction to scroll in
1200 * pagination: whether or not to include dotted pagination
1201 *
1202 */
1203
1204 (function($) {
1205 $.fn.dacSlideshow = function(o) {
Scott Main3b90aff2013-08-01 18:09:35 -07001206
Scott Mainf5089842012-08-14 16:31:07 -07001207 //Options - see above
1208 o = $.extend({
1209 btnPrev: null,
1210 btnNext: null,
Scott Maineb410352013-01-14 19:03:40 -08001211 btnPause: null,
Scott Mainf5089842012-08-14 16:31:07 -07001212 auto: true,
1213 speed: 500,
1214 autoTime: 12000,
1215 easing: null,
1216 start: 0,
1217 scroll: 1,
1218 pagination: true
1219
1220 }, o || {});
Scott Main3b90aff2013-08-01 18:09:35 -07001221
1222 //Set up a carousel for each
Scott Mainf5089842012-08-14 16:31:07 -07001223 return this.each(function() {
1224
1225 var running = false;
1226 var animCss = o.vertical ? "top" : "left";
1227 var sizeCss = o.vertical ? "height" : "width";
1228 var div = $(this);
1229 var ul = $("ul", div);
1230 var tLi = $("li", ul);
Scott Main3b90aff2013-08-01 18:09:35 -07001231 var tl = tLi.size();
Scott Mainf5089842012-08-14 16:31:07 -07001232 var timer = null;
1233
1234 var li = $("li", ul);
1235 var itemLength = li.size();
1236 var curr = o.start;
1237
1238 li.css({float: o.vertical ? "none" : "left"});
1239 ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
1240 div.css({position: "relative", "z-index": "2", left: "0px"});
1241
1242 var liSize = o.vertical ? height(li) : width(li);
1243 var ulSize = liSize * itemLength;
1244 var divSize = liSize;
1245
1246 li.css({width: li.width(), height: li.height()});
1247 ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
1248
1249 div.css(sizeCss, divSize+"px");
Scott Main3b90aff2013-08-01 18:09:35 -07001250
Scott Mainf5089842012-08-14 16:31:07 -07001251 //Pagination
1252 if (o.pagination) {
1253 var pagination = $("<div class='pagination'></div>");
1254 var pag_ul = $("<ul></ul>");
1255 if (tl > 1) {
1256 for (var i=0;i<tl;i++) {
1257 var li = $("<li>"+i+"</li>");
1258 pag_ul.append(li);
1259 if (i==o.start) li.addClass('active');
1260 li.click(function() {
1261 go(parseInt($(this).text()));
1262 })
1263 }
1264 pagination.append(pag_ul);
1265 div.append(pagination);
1266 }
1267 }
Scott Main3b90aff2013-08-01 18:09:35 -07001268
Scott Mainf5089842012-08-14 16:31:07 -07001269 //Previous button
1270 if(o.btnPrev)
1271 $(o.btnPrev).click(function(e) {
1272 e.preventDefault();
1273 return go(curr-o.scroll);
1274 });
1275
1276 //Next button
1277 if(o.btnNext)
1278 $(o.btnNext).click(function(e) {
1279 e.preventDefault();
1280 return go(curr+o.scroll);
1281 });
Scott Maineb410352013-01-14 19:03:40 -08001282
1283 //Pause button
1284 if(o.btnPause)
1285 $(o.btnPause).click(function(e) {
1286 e.preventDefault();
1287 if ($(this).hasClass('paused')) {
1288 startRotateTimer();
1289 } else {
1290 pauseRotateTimer();
1291 }
1292 });
Scott Main3b90aff2013-08-01 18:09:35 -07001293
Scott Mainf5089842012-08-14 16:31:07 -07001294 //Auto rotation
1295 if(o.auto) startRotateTimer();
Scott Main3b90aff2013-08-01 18:09:35 -07001296
Scott Mainf5089842012-08-14 16:31:07 -07001297 function startRotateTimer() {
1298 clearInterval(timer);
1299 timer = setInterval(function() {
1300 if (curr == tl-1) {
1301 go(0);
1302 } else {
Scott Main3b90aff2013-08-01 18:09:35 -07001303 go(curr+o.scroll);
1304 }
Scott Mainf5089842012-08-14 16:31:07 -07001305 }, o.autoTime);
Scott Maineb410352013-01-14 19:03:40 -08001306 $(o.btnPause).removeClass('paused');
1307 }
1308
1309 function pauseRotateTimer() {
1310 clearInterval(timer);
1311 $(o.btnPause).addClass('paused');
Scott Mainf5089842012-08-14 16:31:07 -07001312 }
1313
1314 //Go to an item
1315 function go(to) {
1316 if(!running) {
1317
1318 if(to<0) {
1319 to = itemLength-1;
1320 } else if (to>itemLength-1) {
1321 to = 0;
1322 }
1323 curr = to;
1324
1325 running = true;
1326
1327 ul.animate(
1328 animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
1329 function() {
1330 running = false;
1331 }
1332 );
1333
1334 $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
1335 $( (curr-o.scroll<0 && o.btnPrev)
1336 ||
1337 (curr+o.scroll > itemLength && o.btnNext)
1338 ||
1339 []
1340 ).addClass("disabled");
1341
Scott Main3b90aff2013-08-01 18:09:35 -07001342
Scott Mainf5089842012-08-14 16:31:07 -07001343 var nav_items = $('li', pagination);
1344 nav_items.removeClass('active');
1345 nav_items.eq(to).addClass('active');
Scott Main3b90aff2013-08-01 18:09:35 -07001346
Scott Mainf5089842012-08-14 16:31:07 -07001347
1348 }
1349 if(o.auto) startRotateTimer();
1350 return false;
1351 };
1352 });
1353 };
1354
1355 function css(el, prop) {
1356 return parseInt($.css(el[0], prop)) || 0;
1357 };
1358 function width(el) {
1359 return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
1360 };
1361 function height(el) {
1362 return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
1363 };
1364
1365 })(jQuery);
1366
1367
Scott Main3b90aff2013-08-01 18:09:35 -07001368/*
Scott Mainf5089842012-08-14 16:31:07 -07001369 * dacSlideshow 1.0
1370 * Used on develop/index.html for side-sliding tabs
1371 *
1372 * Sample usage:
1373 * HTML -
1374 * <div class="slideshow-container">
1375 * <a href="" class="slideshow-prev">Prev</a>
1376 * <a href="" class="slideshow-next">Next</a>
1377 * <ul>
1378 * <li class="item"><img src="images/marquee1.jpg"></li>
1379 * <li class="item"><img src="images/marquee2.jpg"></li>
1380 * <li class="item"><img src="images/marquee3.jpg"></li>
1381 * <li class="item"><img src="images/marquee4.jpg"></li>
1382 * </ul>
1383 * </div>
1384 *
1385 * <script type="text/javascript">
1386 * $('.slideshow-container').dacSlideshow({
1387 * auto: true,
1388 * btnPrev: '.slideshow-prev',
1389 * btnNext: '.slideshow-next'
1390 * });
1391 * </script>
1392 *
1393 * Options:
1394 * btnPrev: optional identifier for previous button
1395 * btnNext: optional identifier for next button
1396 * auto: whether or not to auto-proceed
1397 * speed: animation speed
1398 * autoTime: time between auto-rotation
1399 * easing: easing function for transition
1400 * start: item to select by default
1401 * scroll: direction to scroll in
1402 * pagination: whether or not to include dotted pagination
1403 *
1404 */
1405 (function($) {
1406 $.fn.dacTabbedList = function(o) {
Scott Main3b90aff2013-08-01 18:09:35 -07001407
Scott Mainf5089842012-08-14 16:31:07 -07001408 //Options - see above
1409 o = $.extend({
1410 speed : 250,
1411 easing: null,
1412 nav_id: null,
1413 frame_id: null
1414 }, o || {});
Scott Main3b90aff2013-08-01 18:09:35 -07001415
1416 //Set up a carousel for each
Scott Mainf5089842012-08-14 16:31:07 -07001417 return this.each(function() {
1418
1419 var curr = 0;
1420 var running = false;
1421 var animCss = "margin-left";
1422 var sizeCss = "width";
1423 var div = $(this);
Scott Main3b90aff2013-08-01 18:09:35 -07001424
Scott Mainf5089842012-08-14 16:31:07 -07001425 var nav = $(o.nav_id, div);
1426 var nav_li = $("li", nav);
Scott Main3b90aff2013-08-01 18:09:35 -07001427 var nav_size = nav_li.size();
Scott Mainf5089842012-08-14 16:31:07 -07001428 var frame = div.find(o.frame_id);
1429 var content_width = $(frame).find('ul').width();
1430 //Buttons
1431 $(nav_li).click(function(e) {
1432 go($(nav_li).index($(this)));
1433 })
Scott Main3b90aff2013-08-01 18:09:35 -07001434
Scott Mainf5089842012-08-14 16:31:07 -07001435 //Go to an item
1436 function go(to) {
1437 if(!running) {
1438 curr = to;
1439 running = true;
1440
1441 frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
1442 function() {
1443 running = false;
1444 }
1445 );
1446
Scott Main3b90aff2013-08-01 18:09:35 -07001447
Scott Mainf5089842012-08-14 16:31:07 -07001448 nav_li.removeClass('active');
1449 nav_li.eq(to).addClass('active');
Scott Main3b90aff2013-08-01 18:09:35 -07001450
Scott Mainf5089842012-08-14 16:31:07 -07001451
1452 }
1453 return false;
1454 };
1455 });
1456 };
1457
1458 function css(el, prop) {
1459 return parseInt($.css(el[0], prop)) || 0;
1460 };
1461 function width(el) {
1462 return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
1463 };
1464 function height(el) {
1465 return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
1466 };
1467
1468 })(jQuery);
1469
1470
1471
1472
1473
1474/* ######################################################## */
1475/* ################ SEARCH SUGGESTIONS ################## */
1476/* ######################################################## */
1477
1478
Scott Main7e447ed2013-02-19 17:22:37 -08001479
Scott Main0e76e7e2013-03-12 10:24:07 -07001480var gSelectedIndex = -1; // the index position of currently highlighted suggestion
1481var gSelectedColumn = -1; // which column of suggestion lists is currently focused
1482
Scott Mainf5089842012-08-14 16:31:07 -07001483var gMatches = new Array();
1484var gLastText = "";
Scott Mainf5089842012-08-14 16:31:07 -07001485var gInitialized = false;
Scott Main7e447ed2013-02-19 17:22:37 -08001486var ROW_COUNT_FRAMEWORK = 20; // max number of results in list
1487var gListLength = 0;
1488
1489
1490var gGoogleMatches = new Array();
1491var ROW_COUNT_GOOGLE = 15; // max number of results in list
1492var gGoogleListLength = 0;
Scott Mainf5089842012-08-14 16:31:07 -07001493
Scott Main0e76e7e2013-03-12 10:24:07 -07001494var gDocsMatches = new Array();
1495var ROW_COUNT_DOCS = 100; // max number of results in list
1496var gDocsListLength = 0;
1497
Scott Mainde295272013-03-25 15:48:35 -07001498function onSuggestionClick(link) {
1499 // When user clicks a suggested document, track it
1500 _gaq.push(['_trackEvent', 'Suggestion Click', 'clicked: ' + $(link).text(),
1501 'from: ' + $("#search_autocomplete").val()]);
1502}
1503
Scott Mainf5089842012-08-14 16:31:07 -07001504function set_item_selected($li, selected)
1505{
1506 if (selected) {
1507 $li.attr('class','jd-autocomplete jd-selected');
1508 } else {
1509 $li.attr('class','jd-autocomplete');
1510 }
1511}
1512
1513function set_item_values(toroot, $li, match)
1514{
1515 var $link = $('a',$li);
1516 $link.html(match.__hilabel || match.label);
1517 $link.attr('href',toroot + match.link);
1518}
1519
Scott Main0e76e7e2013-03-12 10:24:07 -07001520function new_suggestion($list) {
Scott Main7e447ed2013-02-19 17:22:37 -08001521 var $li = $("<li class='jd-autocomplete'></li>");
1522 $list.append($li);
1523
1524 $li.mousedown(function() {
1525 window.location = this.firstChild.getAttribute("href");
1526 });
1527 $li.mouseover(function() {
Scott Main0e76e7e2013-03-12 10:24:07 -07001528 $('.search_filtered_wrapper li').removeClass('jd-selected');
Scott Main7e447ed2013-02-19 17:22:37 -08001529 $(this).addClass('jd-selected');
Scott Main0e76e7e2013-03-12 10:24:07 -07001530 gSelectedColumn = $(".search_filtered:visible").index($(this).closest('.search_filtered'));
1531 gSelectedIndex = $("li", $(".search_filtered:visible")[gSelectedColumn]).index(this);
Scott Main7e447ed2013-02-19 17:22:37 -08001532 });
Scott Mainde295272013-03-25 15:48:35 -07001533 $li.append("<a onclick='onSuggestionClick(this)'></a>");
Scott Main7e447ed2013-02-19 17:22:37 -08001534 $li.attr('class','show-item');
1535 return $li;
1536}
1537
Scott Mainf5089842012-08-14 16:31:07 -07001538function sync_selection_table(toroot)
1539{
Scott Mainf5089842012-08-14 16:31:07 -07001540 var $li; //list item jquery object
1541 var i; //list item iterator
Scott Main7e447ed2013-02-19 17:22:37 -08001542
Scott Main0e76e7e2013-03-12 10:24:07 -07001543 // if there are NO results at all, hide all columns
1544 if (!(gMatches.length > 0) && !(gGoogleMatches.length > 0) && !(gDocsMatches.length > 0)) {
1545 $('.suggest-card').hide(300);
1546 return;
1547 }
1548
1549 // if there are api results
Scott Main7e447ed2013-02-19 17:22:37 -08001550 if ((gMatches.length > 0) || (gGoogleMatches.length > 0)) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001551 // reveal suggestion list
1552 $('.suggest-card.dummy').show();
1553 $('.suggest-card.reference').show();
1554 var listIndex = 0; // list index position
Scott Main7e447ed2013-02-19 17:22:37 -08001555
Scott Main0e76e7e2013-03-12 10:24:07 -07001556 // reset the lists
1557 $(".search_filtered_wrapper.reference li").remove();
Scott Main7e447ed2013-02-19 17:22:37 -08001558
Scott Main0e76e7e2013-03-12 10:24:07 -07001559 // ########### ANDROID RESULTS #############
1560 if (gMatches.length > 0) {
Scott Main7e447ed2013-02-19 17:22:37 -08001561
Scott Main0e76e7e2013-03-12 10:24:07 -07001562 // determine android results to show
1563 gListLength = gMatches.length < ROW_COUNT_FRAMEWORK ?
1564 gMatches.length : ROW_COUNT_FRAMEWORK;
1565 for (i=0; i<gListLength; i++) {
1566 var $li = new_suggestion($(".suggest-card.reference ul"));
1567 set_item_values(toroot, $li, gMatches[i]);
1568 set_item_selected($li, i == gSelectedIndex);
1569 }
1570 }
Scott Main7e447ed2013-02-19 17:22:37 -08001571
Scott Main0e76e7e2013-03-12 10:24:07 -07001572 // ########### GOOGLE RESULTS #############
1573 if (gGoogleMatches.length > 0) {
1574 // show header for list
1575 $(".suggest-card.reference ul").append("<li class='header'>in Google Services:</li>");
Scott Main7e447ed2013-02-19 17:22:37 -08001576
Scott Main0e76e7e2013-03-12 10:24:07 -07001577 // determine google results to show
1578 gGoogleListLength = gGoogleMatches.length < ROW_COUNT_GOOGLE ? gGoogleMatches.length : ROW_COUNT_GOOGLE;
1579 for (i=0; i<gGoogleListLength; i++) {
1580 var $li = new_suggestion($(".suggest-card.reference ul"));
1581 set_item_values(toroot, $li, gGoogleMatches[i]);
1582 set_item_selected($li, i == gSelectedIndex);
1583 }
1584 }
Scott Mainf5089842012-08-14 16:31:07 -07001585 } else {
Scott Main0e76e7e2013-03-12 10:24:07 -07001586 $('.suggest-card.reference').hide();
1587 $('.suggest-card.dummy').hide();
1588 }
1589
1590 // ########### JD DOC RESULTS #############
1591 if (gDocsMatches.length > 0) {
1592 // reset the lists
1593 $(".search_filtered_wrapper.docs li").remove();
1594
1595 // determine google results to show
1596 gDocsListLength = gDocsMatches.length < ROW_COUNT_DOCS ? gDocsMatches.length : ROW_COUNT_DOCS;
1597 for (i=0; i<gDocsListLength; i++) {
1598 var sugg = gDocsMatches[i];
1599 var $li;
1600 if (sugg.type == "design") {
1601 $li = new_suggestion($(".suggest-card.design ul"));
1602 } else
1603 if (sugg.type == "distribute") {
1604 $li = new_suggestion($(".suggest-card.distribute ul"));
1605 } else
1606 if (sugg.type == "training") {
1607 $li = new_suggestion($(".suggest-card.develop .child-card.training"));
1608 } else
1609 if (sugg.type == "guide"||"google") {
1610 $li = new_suggestion($(".suggest-card.develop .child-card.guides"));
1611 } else {
1612 continue;
1613 }
1614
1615 set_item_values(toroot, $li, sugg);
1616 set_item_selected($li, i == gSelectedIndex);
1617 }
1618
1619 // add heading and show or hide card
1620 if ($(".suggest-card.design li").length > 0) {
1621 $(".suggest-card.design ul").prepend("<li class='header'>Design:</li>");
1622 $(".suggest-card.design").show(300);
1623 } else {
1624 $('.suggest-card.design').hide(300);
1625 }
1626 if ($(".suggest-card.distribute li").length > 0) {
1627 $(".suggest-card.distribute ul").prepend("<li class='header'>Distribute:</li>");
1628 $(".suggest-card.distribute").show(300);
1629 } else {
1630 $('.suggest-card.distribute').hide(300);
1631 }
1632 if ($(".child-card.guides li").length > 0) {
1633 $(".child-card.guides").prepend("<li class='header'>Guides:</li>");
1634 $(".child-card.guides li").appendTo(".suggest-card.develop ul");
1635 }
1636 if ($(".child-card.training li").length > 0) {
1637 $(".child-card.training").prepend("<li class='header'>Training:</li>");
1638 $(".child-card.training li").appendTo(".suggest-card.develop ul");
1639 }
1640
1641 if ($(".suggest-card.develop li").length > 0) {
1642 $(".suggest-card.develop").show(300);
1643 } else {
1644 $('.suggest-card.develop').hide(300);
1645 }
1646
1647 } else {
1648 $('.search_filtered_wrapper.docs .suggest-card:not(.dummy)').hide(300);
Scott Mainf5089842012-08-14 16:31:07 -07001649 }
1650}
1651
Scott Main0e76e7e2013-03-12 10:24:07 -07001652/** Called by the search input's onkeydown and onkeyup events.
1653 * Handles navigation with keyboard arrows, Enter key to invoke search,
1654 * otherwise invokes search suggestions on key-up event.
1655 * @param e The JS event
1656 * @param kd True if the event is key-down
Scott Main3b90aff2013-08-01 18:09:35 -07001657 * @param toroot A string for the site's root path
Scott Main0e76e7e2013-03-12 10:24:07 -07001658 * @returns True if the event should bubble up
1659 */
Scott Mainf5089842012-08-14 16:31:07 -07001660function search_changed(e, kd, toroot)
1661{
1662 var search = document.getElementById("search_autocomplete");
1663 var text = search.value.replace(/(^ +)|( +$)/g, '');
Scott Main0e76e7e2013-03-12 10:24:07 -07001664 // get the ul hosting the currently selected item
1665 gSelectedColumn = gSelectedColumn >= 0 ? gSelectedColumn : 0;
1666 var $columns = $(".search_filtered_wrapper").find(".search_filtered:visible");
1667 var $selectedUl = $columns[gSelectedColumn];
1668
Scott Mainf5089842012-08-14 16:31:07 -07001669 // show/hide the close button
1670 if (text != '') {
1671 $(".search .close").removeClass("hide");
1672 } else {
1673 $(".search .close").addClass("hide");
1674 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001675 // 27 = esc
1676 if (e.keyCode == 27) {
1677 // close all search results
1678 if (kd) $('.search .close').trigger('click');
1679 return true;
1680 }
Scott Mainf5089842012-08-14 16:31:07 -07001681 // 13 = enter
Scott Main0e76e7e2013-03-12 10:24:07 -07001682 else if (e.keyCode == 13) {
1683 if (gSelectedIndex < 0) {
1684 $('.suggest-card').hide();
Scott Main7e447ed2013-02-19 17:22:37 -08001685 if ($("#searchResults").is(":hidden") && (search.value != "")) {
1686 // if results aren't showing (and text not empty), return true to allow search to execute
Scott Mainf5089842012-08-14 16:31:07 -07001687 return true;
1688 } else {
1689 // otherwise, results are already showing, so allow ajax to auto refresh the results
1690 // and ignore this Enter press to avoid the reload.
1691 return false;
1692 }
1693 } else if (kd && gSelectedIndex >= 0) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001694 // click the link corresponding to selected item
1695 $("a",$("li",$selectedUl)[gSelectedIndex]).get()[0].click();
Scott Mainf5089842012-08-14 16:31:07 -07001696 return false;
1697 }
1698 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001699 // Stop here if Google results are showing
1700 else if ($("#searchResults").is(":visible")) {
1701 return true;
1702 }
1703 // 38 UP ARROW
Scott Mainf5089842012-08-14 16:31:07 -07001704 else if (kd && (e.keyCode == 38)) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001705 // if the next item is a header, skip it
1706 if ($($("li", $selectedUl)[gSelectedIndex-1]).hasClass("header")) {
Scott Mainf5089842012-08-14 16:31:07 -07001707 gSelectedIndex--;
Scott Main7e447ed2013-02-19 17:22:37 -08001708 }
1709 if (gSelectedIndex >= 0) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001710 $('li', $selectedUl).removeClass('jd-selected');
Scott Main7e447ed2013-02-19 17:22:37 -08001711 gSelectedIndex--;
Scott Main0e76e7e2013-03-12 10:24:07 -07001712 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1713 // If user reaches top, reset selected column
1714 if (gSelectedIndex < 0) {
1715 gSelectedColumn = -1;
1716 }
Scott Mainf5089842012-08-14 16:31:07 -07001717 }
1718 return false;
1719 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001720 // 40 DOWN ARROW
Scott Mainf5089842012-08-14 16:31:07 -07001721 else if (kd && (e.keyCode == 40)) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001722 // if the next item is a header, skip it
1723 if ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header")) {
Scott Mainf5089842012-08-14 16:31:07 -07001724 gSelectedIndex++;
Scott Main7e447ed2013-02-19 17:22:37 -08001725 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001726 if ((gSelectedIndex < $("li", $selectedUl).length-1) ||
1727 ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header"))) {
1728 $('li', $selectedUl).removeClass('jd-selected');
Scott Main7e447ed2013-02-19 17:22:37 -08001729 gSelectedIndex++;
Scott Main0e76e7e2013-03-12 10:24:07 -07001730 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
Scott Mainf5089842012-08-14 16:31:07 -07001731 }
1732 return false;
1733 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001734 // Consider left/right arrow navigation
1735 // NOTE: Order of suggest columns are reverse order (index position 0 is on right)
1736 else if (kd && $columns.length > 1 && gSelectedColumn >= 0) {
1737 // 37 LEFT ARROW
1738 // go left only if current column is not left-most column (last column)
1739 if (e.keyCode == 37 && gSelectedColumn < $columns.length - 1) {
1740 $('li', $selectedUl).removeClass('jd-selected');
1741 gSelectedColumn++;
1742 $selectedUl = $columns[gSelectedColumn];
1743 // keep or reset the selected item to last item as appropriate
1744 gSelectedIndex = gSelectedIndex >
1745 $("li", $selectedUl).length-1 ?
1746 $("li", $selectedUl).length-1 : gSelectedIndex;
1747 // if the corresponding item is a header, move down
1748 if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
1749 gSelectedIndex++;
1750 }
Scott Main3b90aff2013-08-01 18:09:35 -07001751 // set item selected
Scott Main0e76e7e2013-03-12 10:24:07 -07001752 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1753 return false;
1754 }
1755 // 39 RIGHT ARROW
1756 // go right only if current column is not the right-most column (first column)
1757 else if (e.keyCode == 39 && gSelectedColumn > 0) {
1758 $('li', $selectedUl).removeClass('jd-selected');
1759 gSelectedColumn--;
1760 $selectedUl = $columns[gSelectedColumn];
1761 // keep or reset the selected item to last item as appropriate
1762 gSelectedIndex = gSelectedIndex >
1763 $("li", $selectedUl).length-1 ?
1764 $("li", $selectedUl).length-1 : gSelectedIndex;
1765 // if the corresponding item is a header, move down
1766 if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
1767 gSelectedIndex++;
1768 }
Scott Main3b90aff2013-08-01 18:09:35 -07001769 // set item selected
Scott Main0e76e7e2013-03-12 10:24:07 -07001770 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1771 return false;
1772 }
1773 }
1774
Scott Main7e447ed2013-02-19 17:22:37 -08001775 // if key-up event and not arrow down/up,
1776 // read the search query and add suggestsions to gMatches
Scott Main0e76e7e2013-03-12 10:24:07 -07001777 else if (!kd && (e.keyCode != 40)
1778 && (e.keyCode != 38)
1779 && (e.keyCode != 37)
1780 && (e.keyCode != 39)) {
1781 gSelectedIndex = -1;
Scott Mainf5089842012-08-14 16:31:07 -07001782 gMatches = new Array();
1783 matchedCount = 0;
Scott Main7e447ed2013-02-19 17:22:37 -08001784 gGoogleMatches = new Array();
1785 matchedCountGoogle = 0;
Scott Main0e76e7e2013-03-12 10:24:07 -07001786 gDocsMatches = new Array();
1787 matchedCountDocs = 0;
Scott Main7e447ed2013-02-19 17:22:37 -08001788
1789 // Search for Android matches
Scott Mainf5089842012-08-14 16:31:07 -07001790 for (var i=0; i<DATA.length; i++) {
1791 var s = DATA[i];
1792 if (text.length != 0 &&
1793 s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
1794 gMatches[matchedCount] = s;
1795 matchedCount++;
1796 }
1797 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001798 rank_autocomplete_api_results(text, gMatches);
Scott Mainf5089842012-08-14 16:31:07 -07001799 for (var i=0; i<gMatches.length; i++) {
1800 var s = gMatches[i];
Scott Main7e447ed2013-02-19 17:22:37 -08001801 }
1802
1803
1804 // Search for Google matches
1805 for (var i=0; i<GOOGLE_DATA.length; i++) {
1806 var s = GOOGLE_DATA[i];
1807 if (text.length != 0 &&
1808 s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
1809 gGoogleMatches[matchedCountGoogle] = s;
1810 matchedCountGoogle++;
Scott Mainf5089842012-08-14 16:31:07 -07001811 }
1812 }
Scott Main0e76e7e2013-03-12 10:24:07 -07001813 rank_autocomplete_api_results(text, gGoogleMatches);
Scott Main7e447ed2013-02-19 17:22:37 -08001814 for (var i=0; i<gGoogleMatches.length; i++) {
1815 var s = gGoogleMatches[i];
1816 }
1817
Scott Mainf5089842012-08-14 16:31:07 -07001818 highlight_autocomplete_result_labels(text);
Scott Main0e76e7e2013-03-12 10:24:07 -07001819
1820
1821
1822 // Search for JD docs
1823 if (text.length >= 3) {
1824 for (var i=0; i<JD_DATA.length; i++) {
1825 // Regex to match only the beginning of a word
1826 var textRegex = new RegExp("\\b" + text.toLowerCase(), "g");
1827 // current search comparison, with counters for tag and title,
1828 // used later to improve ranking
1829 var s = JD_DATA[i];
1830 s.matched_tag = 0;
1831 s.matched_title = 0;
1832 var matched = false;
1833
1834 // Check if query matches any tags; work backwards toward 1 to assist ranking
1835 for (var j = s.tags.length - 1; j >= 0; j--) {
1836 // it matches a tag
1837 if (s.tags[j].toLowerCase().match(textRegex)) {
1838 matched = true;
1839 s.matched_tag = j + 1; // add 1 to index position
1840 }
1841 }
1842 // Don't consider doc title for lessons (only for class landing pages)
1843 // ...it is not a training lesson (or is but has matched a tag)
1844 if (!(s.type == "training" && s.link.indexOf("index.html") == -1) || matched) {
1845 // it matches the doc title
1846 if (s.label.toLowerCase().match(textRegex)) {
1847 matched = true;
1848 s.matched_title = 1;
1849 }
1850 }
1851 if (matched) {
1852 gDocsMatches[matchedCountDocs] = s;
1853 matchedCountDocs++;
1854 }
1855 }
1856 rank_autocomplete_doc_results(text, gDocsMatches);
1857 }
1858
1859 // draw the suggestions
Scott Mainf5089842012-08-14 16:31:07 -07001860 sync_selection_table(toroot);
1861 return true; // allow the event to bubble up to the search api
1862 }
1863}
1864
Scott Main0e76e7e2013-03-12 10:24:07 -07001865/* Order the jd doc result list based on match quality */
1866function rank_autocomplete_doc_results(query, matches) {
1867 query = query || '';
1868 if (!matches || !matches.length)
1869 return;
1870
1871 var _resultScoreFn = function(match) {
1872 var score = 1.0;
1873
1874 // if the query matched a tag
1875 if (match.matched_tag > 0) {
1876 // multiply score by factor relative to position in tags list (max of 3)
1877 score *= 3 / match.matched_tag;
1878
1879 // if it also matched the title
1880 if (match.matched_title > 0) {
1881 score *= 2;
1882 }
1883 } else if (match.matched_title > 0) {
1884 score *= 3;
1885 }
1886
1887 return score;
1888 };
1889
1890 for (var i=0; i<matches.length; i++) {
1891 matches[i].__resultScore = _resultScoreFn(matches[i]);
1892 }
1893
1894 matches.sort(function(a,b){
1895 var n = b.__resultScore - a.__resultScore;
1896 if (n == 0) // lexicographical sort if scores are the same
1897 n = (a.label < b.label) ? -1 : 1;
1898 return n;
1899 });
1900}
1901
Scott Main7e447ed2013-02-19 17:22:37 -08001902/* Order the result list based on match quality */
Scott Main0e76e7e2013-03-12 10:24:07 -07001903function rank_autocomplete_api_results(query, matches) {
Scott Mainf5089842012-08-14 16:31:07 -07001904 query = query || '';
Scott Main7e447ed2013-02-19 17:22:37 -08001905 if (!matches || !matches.length)
Scott Mainf5089842012-08-14 16:31:07 -07001906 return;
1907
1908 // helper function that gets the last occurence index of the given regex
1909 // in the given string, or -1 if not found
1910 var _lastSearch = function(s, re) {
1911 if (s == '')
1912 return -1;
1913 var l = -1;
1914 var tmp;
1915 while ((tmp = s.search(re)) >= 0) {
1916 if (l < 0) l = 0;
1917 l += tmp;
1918 s = s.substr(tmp + 1);
1919 }
1920 return l;
1921 };
1922
1923 // helper function that counts the occurrences of a given character in
1924 // a given string
1925 var _countChar = function(s, c) {
1926 var n = 0;
1927 for (var i=0; i<s.length; i++)
1928 if (s.charAt(i) == c) ++n;
1929 return n;
1930 };
1931
1932 var queryLower = query.toLowerCase();
1933 var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
1934 var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
1935 var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
1936
1937 var _resultScoreFn = function(result) {
1938 // scores are calculated based on exact and prefix matches,
1939 // and then number of path separators (dots) from the last
1940 // match (i.e. favoring classes and deep package names)
1941 var score = 1.0;
1942 var labelLower = result.label.toLowerCase();
1943 var t;
1944 t = _lastSearch(labelLower, partExactAlnumRE);
1945 if (t >= 0) {
1946 // exact part match
1947 var partsAfter = _countChar(labelLower.substr(t + 1), '.');
1948 score *= 200 / (partsAfter + 1);
1949 } else {
1950 t = _lastSearch(labelLower, partPrefixAlnumRE);
1951 if (t >= 0) {
1952 // part prefix match
1953 var partsAfter = _countChar(labelLower.substr(t + 1), '.');
1954 score *= 20 / (partsAfter + 1);
1955 }
1956 }
1957
1958 return score;
1959 };
1960
Scott Main7e447ed2013-02-19 17:22:37 -08001961 for (var i=0; i<matches.length; i++) {
Scott Main0e76e7e2013-03-12 10:24:07 -07001962 // if the API is deprecated, default score is 0; otherwise, perform scoring
1963 if (matches[i].deprecated == "true") {
1964 matches[i].__resultScore = 0;
1965 } else {
1966 matches[i].__resultScore = _resultScoreFn(matches[i]);
1967 }
Scott Mainf5089842012-08-14 16:31:07 -07001968 }
1969
Scott Main7e447ed2013-02-19 17:22:37 -08001970 matches.sort(function(a,b){
Scott Mainf5089842012-08-14 16:31:07 -07001971 var n = b.__resultScore - a.__resultScore;
1972 if (n == 0) // lexicographical sort if scores are the same
1973 n = (a.label < b.label) ? -1 : 1;
1974 return n;
1975 });
1976}
1977
Scott Main7e447ed2013-02-19 17:22:37 -08001978/* Add emphasis to part of string that matches query */
Scott Mainf5089842012-08-14 16:31:07 -07001979function highlight_autocomplete_result_labels(query) {
1980 query = query || '';
Scott Main7e447ed2013-02-19 17:22:37 -08001981 if ((!gMatches || !gMatches.length) && (!gGoogleMatches || !gGoogleMatches.length))
Scott Mainf5089842012-08-14 16:31:07 -07001982 return;
1983
1984 var queryLower = query.toLowerCase();
1985 var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
1986 var queryRE = new RegExp(
1987 '(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
1988 for (var i=0; i<gMatches.length; i++) {
1989 gMatches[i].__hilabel = gMatches[i].label.replace(
1990 queryRE, '<b>$1</b>');
1991 }
Scott Main7e447ed2013-02-19 17:22:37 -08001992 for (var i=0; i<gGoogleMatches.length; i++) {
1993 gGoogleMatches[i].__hilabel = gGoogleMatches[i].label.replace(
1994 queryRE, '<b>$1</b>');
1995 }
Scott Mainf5089842012-08-14 16:31:07 -07001996}
1997
1998function search_focus_changed(obj, focused)
1999{
Scott Main3b90aff2013-08-01 18:09:35 -07002000 if (!focused) {
Scott Mainf5089842012-08-14 16:31:07 -07002001 if(obj.value == ""){
2002 $(".search .close").addClass("hide");
2003 }
Scott Main0e76e7e2013-03-12 10:24:07 -07002004 $(".suggest-card").hide();
Scott Mainf5089842012-08-14 16:31:07 -07002005 }
2006}
2007
2008function submit_search() {
2009 var query = document.getElementById('search_autocomplete').value;
2010 location.hash = 'q=' + query;
2011 loadSearchResults();
2012 $("#searchResults").slideDown('slow');
2013 return false;
2014}
2015
2016
2017function hideResults() {
2018 $("#searchResults").slideUp();
2019 $(".search .close").addClass("hide");
2020 location.hash = '';
Scott Main3b90aff2013-08-01 18:09:35 -07002021
Scott Mainf5089842012-08-14 16:31:07 -07002022 $("#search_autocomplete").val("").blur();
Scott Main3b90aff2013-08-01 18:09:35 -07002023
Scott Mainf5089842012-08-14 16:31:07 -07002024 // reset the ajax search callback to nothing, so results don't appear unless ENTER
2025 searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
Scott Main0e76e7e2013-03-12 10:24:07 -07002026
2027 // forcefully regain key-up event control (previously jacked by search api)
2028 $("#search_autocomplete").keyup(function(event) {
2029 return search_changed(event, false, toRoot);
2030 });
2031
Scott Mainf5089842012-08-14 16:31:07 -07002032 return false;
2033}
2034
2035
2036
2037/* ########################################################## */
2038/* ################ CUSTOM SEARCH ENGINE ################## */
2039/* ########################################################## */
2040
Scott Mainf5089842012-08-14 16:31:07 -07002041var searchControl;
Scott Main0e76e7e2013-03-12 10:24:07 -07002042google.load('search', '1', {"callback" : function() {
2043 searchControl = new google.search.SearchControl();
2044 } });
Scott Mainf5089842012-08-14 16:31:07 -07002045
2046function loadSearchResults() {
2047 document.getElementById("search_autocomplete").style.color = "#000";
2048
Scott Mainf5089842012-08-14 16:31:07 -07002049 searchControl = new google.search.SearchControl();
2050
2051 // use our existing search form and use tabs when multiple searchers are used
2052 drawOptions = new google.search.DrawOptions();
2053 drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
2054 drawOptions.setInput(document.getElementById("search_autocomplete"));
2055
2056 // configure search result options
2057 searchOptions = new google.search.SearcherOptions();
2058 searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
2059
2060 // configure each of the searchers, for each tab
2061 devSiteSearcher = new google.search.WebSearch();
2062 devSiteSearcher.setUserDefinedLabel("All");
2063 devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
2064
2065 designSearcher = new google.search.WebSearch();
2066 designSearcher.setUserDefinedLabel("Design");
2067 designSearcher.setSiteRestriction("http://developer.android.com/design/");
2068
2069 trainingSearcher = new google.search.WebSearch();
2070 trainingSearcher.setUserDefinedLabel("Training");
2071 trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
2072
2073 guidesSearcher = new google.search.WebSearch();
2074 guidesSearcher.setUserDefinedLabel("Guides");
2075 guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
2076
2077 referenceSearcher = new google.search.WebSearch();
2078 referenceSearcher.setUserDefinedLabel("Reference");
2079 referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
2080
Scott Maindf08ada2012-12-03 08:54:37 -08002081 googleSearcher = new google.search.WebSearch();
2082 googleSearcher.setUserDefinedLabel("Google Services");
2083 googleSearcher.setSiteRestriction("http://developer.android.com/google/");
2084
Scott Mainf5089842012-08-14 16:31:07 -07002085 blogSearcher = new google.search.WebSearch();
2086 blogSearcher.setUserDefinedLabel("Blog");
2087 blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
2088
2089 // add each searcher to the search control
2090 searchControl.addSearcher(devSiteSearcher, searchOptions);
2091 searchControl.addSearcher(designSearcher, searchOptions);
2092 searchControl.addSearcher(trainingSearcher, searchOptions);
2093 searchControl.addSearcher(guidesSearcher, searchOptions);
2094 searchControl.addSearcher(referenceSearcher, searchOptions);
Scott Maindf08ada2012-12-03 08:54:37 -08002095 searchControl.addSearcher(googleSearcher, searchOptions);
Scott Mainf5089842012-08-14 16:31:07 -07002096 searchControl.addSearcher(blogSearcher, searchOptions);
2097
2098 // configure result options
2099 searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
2100 searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
2101 searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
2102 searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
2103
2104 // upon ajax search, refresh the url and search title
2105 searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
2106 updateResultTitle(query);
2107 var query = document.getElementById('search_autocomplete').value;
2108 location.hash = 'q=' + query;
2109 });
2110
Scott Mainde295272013-03-25 15:48:35 -07002111 // once search results load, set up click listeners
2112 searchControl.setSearchCompleteCallback(this, function(control, searcher, query) {
2113 addResultClickListeners();
2114 });
2115
Scott Mainf5089842012-08-14 16:31:07 -07002116 // draw the search results box
2117 searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
2118
2119 // get query and execute the search
2120 searchControl.execute(decodeURI(getQuery(location.hash)));
2121
2122 document.getElementById("search_autocomplete").focus();
2123 addTabListeners();
2124}
2125// End of loadSearchResults
2126
2127
2128google.setOnLoadCallback(function(){
2129 if (location.hash.indexOf("q=") == -1) {
2130 // if there's no query in the url, don't search and make sure results are hidden
2131 $('#searchResults').hide();
2132 return;
2133 } else {
2134 // first time loading search results for this page
2135 $('#searchResults').slideDown('slow');
2136 $(".search .close").removeClass("hide");
2137 loadSearchResults();
2138 }
2139}, true);
2140
2141// when an event on the browser history occurs (back, forward, load) requery hash and do search
2142$(window).hashchange( function(){
2143 // Exit if the hash isn't a search query or there's an error in the query
2144 if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
2145 // If the results pane is open, close it.
2146 if (!$("#searchResults").is(":hidden")) {
2147 hideResults();
2148 }
2149 return;
2150 }
2151
2152 // Otherwise, we have a search to do
2153 var query = decodeURI(getQuery(location.hash));
2154 searchControl.execute(query);
2155 $('#searchResults').slideDown('slow');
2156 $("#search_autocomplete").focus();
2157 $(".search .close").removeClass("hide");
2158
2159 updateResultTitle(query);
2160});
2161
2162function updateResultTitle(query) {
2163 $("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
2164}
2165
2166// forcefully regain key-up event control (previously jacked by search api)
2167$("#search_autocomplete").keyup(function(event) {
2168 return search_changed(event, false, toRoot);
2169});
2170
2171// add event listeners to each tab so we can track the browser history
2172function addTabListeners() {
2173 var tabHeaders = $(".gsc-tabHeader");
2174 for (var i = 0; i < tabHeaders.length; i++) {
2175 $(tabHeaders[i]).attr("id",i).click(function() {
2176 /*
2177 // make a copy of the page numbers for the search left pane
2178 setTimeout(function() {
2179 // remove any residual page numbers
2180 $('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
Scott Main3b90aff2013-08-01 18:09:35 -07002181 // move the page numbers to the left position; make a clone,
Scott Mainf5089842012-08-14 16:31:07 -07002182 // because the element is drawn to the DOM only once
Scott Main3b90aff2013-08-01 18:09:35 -07002183 // and because we're going to remove it (previous line),
2184 // we need it to be available to move again as the user navigates
Scott Mainf5089842012-08-14 16:31:07 -07002185 $('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
2186 .clone().appendTo('#searchResults .gsc-tabsArea');
2187 }, 200);
2188 */
2189 });
2190 }
2191 setTimeout(function(){$(tabHeaders[0]).click()},200);
2192}
2193
Scott Mainde295272013-03-25 15:48:35 -07002194// add analytics tracking events to each result link
2195function addResultClickListeners() {
2196 $("#searchResults a.gs-title").each(function(index, link) {
2197 // When user clicks enter for Google search results, track it
2198 $(link).click(function() {
2199 _gaq.push(['_trackEvent', 'Google Click', 'clicked: ' + $(this).text(),
2200 'from: ' + $("#search_autocomplete").val()]);
2201 });
2202 });
2203}
2204
Scott Mainf5089842012-08-14 16:31:07 -07002205
2206function getQuery(hash) {
2207 var queryParts = hash.split('=');
2208 return queryParts[1];
2209}
2210
2211/* returns the given string with all HTML brackets converted to entities
2212 TODO: move this to the site's JS library */
2213function escapeHTML(string) {
2214 return string.replace(/</g,"&lt;")
2215 .replace(/>/g,"&gt;");
2216}
2217
2218
2219
2220
2221
2222
2223
2224/* ######################################################## */
2225/* ################# JAVADOC REFERENCE ################### */
2226/* ######################################################## */
2227
Scott Main65511c02012-09-07 15:51:32 -07002228/* Initialize some droiddoc stuff, but only if we're in the reference */
Scott Main52dd2062013-08-15 12:22:28 -07002229if (location.pathname.indexOf("/reference") == 0) {
2230 if(!(location.pathname.indexOf("/reference-gms/packages.html") == 0)
2231 && !(location.pathname.indexOf("/reference-gcm/packages.html") == 0)
2232 && !(location.pathname.indexOf("/reference/com/google") == 0)) {
Robert Ly67d75f12012-12-03 12:53:42 -08002233 $(document).ready(function() {
2234 // init available apis based on user pref
2235 changeApiLevel();
2236 initSidenavHeightResize()
2237 });
2238 }
Scott Main65511c02012-09-07 15:51:32 -07002239}
Scott Mainf5089842012-08-14 16:31:07 -07002240
2241var API_LEVEL_COOKIE = "api_level";
2242var minLevel = 1;
2243var maxLevel = 1;
2244
2245/******* SIDENAV DIMENSIONS ************/
Scott Main3b90aff2013-08-01 18:09:35 -07002246
Scott Mainf5089842012-08-14 16:31:07 -07002247 function initSidenavHeightResize() {
2248 // Change the drag bar size to nicely fit the scrollbar positions
2249 var $dragBar = $(".ui-resizable-s");
2250 $dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
Scott Main3b90aff2013-08-01 18:09:35 -07002251
2252 $( "#resize-packages-nav" ).resizable({
Scott Mainf5089842012-08-14 16:31:07 -07002253 containment: "#nav-panels",
2254 handles: "s",
2255 alsoResize: "#packages-nav",
2256 resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
2257 stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
2258 });
Scott Main3b90aff2013-08-01 18:09:35 -07002259
Scott Mainf5089842012-08-14 16:31:07 -07002260 }
Scott Main3b90aff2013-08-01 18:09:35 -07002261
Scott Mainf5089842012-08-14 16:31:07 -07002262function updateSidenavFixedWidth() {
2263 if (!navBarIsFixed) return;
2264 $('#devdoc-nav').css({
2265 'width' : $('#side-nav').css('width'),
2266 'margin' : $('#side-nav').css('margin')
2267 });
2268 $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
Scott Main3b90aff2013-08-01 18:09:35 -07002269
Scott Mainf5089842012-08-14 16:31:07 -07002270 initSidenavHeightResize();
2271}
2272
2273function updateSidenavFullscreenWidth() {
2274 if (!navBarIsFixed) return;
2275 $('#devdoc-nav').css({
2276 'width' : $('#side-nav').css('width'),
2277 'margin' : $('#side-nav').css('margin')
2278 });
2279 $('#devdoc-nav .totop').css({'left': 'inherit'});
Scott Main3b90aff2013-08-01 18:09:35 -07002280
Scott Mainf5089842012-08-14 16:31:07 -07002281 initSidenavHeightResize();
2282}
2283
2284function buildApiLevelSelector() {
2285 maxLevel = SINCE_DATA.length;
2286 var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
2287 userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
2288
2289 minLevel = parseInt($("#doc-api-level").attr("class"));
2290 // Handle provisional api levels; the provisional level will always be the highest possible level
2291 // Provisional api levels will also have a length; other stuff that's just missing a level won't,
2292 // so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
2293 if (isNaN(minLevel) && minLevel.length) {
2294 minLevel = maxLevel;
2295 }
2296 var select = $("#apiLevelSelector").html("").change(changeApiLevel);
2297 for (var i = maxLevel-1; i >= 0; i--) {
2298 var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
2299 // if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
2300 select.append(option);
2301 }
2302
2303 // get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
2304 var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
2305 selectedLevelItem.setAttribute('selected',true);
2306}
2307
2308function changeApiLevel() {
2309 maxLevel = SINCE_DATA.length;
2310 var selectedLevel = maxLevel;
2311
2312 selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
2313 toggleVisisbleApis(selectedLevel, "body");
2314
2315 var date = new Date();
2316 date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
2317 var expiration = date.toGMTString();
2318 writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
2319
2320 if (selectedLevel < minLevel) {
2321 var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
Scott Main8f24ca82012-11-16 10:34:22 -08002322 $("#naMessage").show().html("<div><p><strong>This " + thing
2323 + " requires API level " + minLevel + " or higher.</strong></p>"
2324 + "<p>This document is hidden because your selected API level for the documentation is "
2325 + selectedLevel + ". You can change the documentation API level with the selector "
2326 + "above the left navigation.</p>"
2327 + "<p>For more information about specifying the API level your app requires, "
2328 + "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
2329 + ">Supporting Different Platform Versions</a>.</p>"
2330 + "<input type='button' value='OK, make this page visible' "
2331 + "title='Change the API level to " + minLevel + "' "
2332 + "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
2333 + "</div>");
Scott Mainf5089842012-08-14 16:31:07 -07002334 } else {
2335 $("#naMessage").hide();
2336 }
2337}
2338
2339function toggleVisisbleApis(selectedLevel, context) {
2340 var apis = $(".api",context);
2341 apis.each(function(i) {
2342 var obj = $(this);
2343 var className = obj.attr("class");
2344 var apiLevelIndex = className.lastIndexOf("-")+1;
2345 var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
2346 apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
2347 var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
2348 if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
2349 return;
2350 }
2351 apiLevel = parseInt(apiLevel);
2352
2353 // Handle provisional api levels; if this item's level is the provisional one, set it to the max
2354 var selectedLevelNum = parseInt(selectedLevel)
2355 var apiLevelNum = parseInt(apiLevel);
2356 if (isNaN(apiLevelNum)) {
2357 apiLevelNum = maxLevel;
2358 }
2359
2360 // Grey things out that aren't available and give a tooltip title
2361 if (apiLevelNum > selectedLevelNum) {
2362 obj.addClass("absent").attr("title","Requires API Level \""
2363 + apiLevel + "\" or higher");
Scott Main3b90aff2013-08-01 18:09:35 -07002364 }
Scott Mainf5089842012-08-14 16:31:07 -07002365 else obj.removeClass("absent").removeAttr("title");
2366 });
2367}
2368
2369
2370
2371
2372/* ################# SIDENAV TREE VIEW ################### */
2373
2374function new_node(me, mom, text, link, children_data, api_level)
2375{
2376 var node = new Object();
2377 node.children = Array();
2378 node.children_data = children_data;
2379 node.depth = mom.depth + 1;
2380
2381 node.li = document.createElement("li");
2382 mom.get_children_ul().appendChild(node.li);
2383
2384 node.label_div = document.createElement("div");
2385 node.label_div.className = "label";
2386 if (api_level != null) {
2387 $(node.label_div).addClass("api");
2388 $(node.label_div).addClass("api-level-"+api_level);
2389 }
2390 node.li.appendChild(node.label_div);
2391
2392 if (children_data != null) {
2393 node.expand_toggle = document.createElement("a");
2394 node.expand_toggle.href = "javascript:void(0)";
2395 node.expand_toggle.onclick = function() {
2396 if (node.expanded) {
2397 $(node.get_children_ul()).slideUp("fast");
2398 node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
2399 node.expanded = false;
2400 } else {
2401 expand_node(me, node);
2402 }
2403 };
2404 node.label_div.appendChild(node.expand_toggle);
2405
2406 node.plus_img = document.createElement("img");
2407 node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
2408 node.plus_img.className = "plus";
2409 node.plus_img.width = "8";
2410 node.plus_img.border = "0";
2411 node.expand_toggle.appendChild(node.plus_img);
2412
2413 node.expanded = false;
2414 }
2415
2416 var a = document.createElement("a");
2417 node.label_div.appendChild(a);
2418 node.label = document.createTextNode(text);
2419 a.appendChild(node.label);
2420 if (link) {
2421 a.href = me.toroot + link;
2422 } else {
2423 if (children_data != null) {
2424 a.className = "nolink";
2425 a.href = "javascript:void(0)";
2426 a.onclick = node.expand_toggle.onclick;
2427 // This next line shouldn't be necessary. I'll buy a beer for the first
2428 // person who figures out how to remove this line and have the link
2429 // toggle shut on the first try. --joeo@android.com
2430 node.expanded = false;
2431 }
2432 }
Scott Main3b90aff2013-08-01 18:09:35 -07002433
Scott Mainf5089842012-08-14 16:31:07 -07002434
2435 node.children_ul = null;
2436 node.get_children_ul = function() {
2437 if (!node.children_ul) {
2438 node.children_ul = document.createElement("ul");
2439 node.children_ul.className = "children_ul";
2440 node.children_ul.style.display = "none";
2441 node.li.appendChild(node.children_ul);
2442 }
2443 return node.children_ul;
2444 };
2445
2446 return node;
2447}
2448
Robert Lyd2dd6e52012-11-29 21:28:48 -08002449
2450
2451
Scott Mainf5089842012-08-14 16:31:07 -07002452function expand_node(me, node)
2453{
2454 if (node.children_data && !node.expanded) {
2455 if (node.children_visited) {
2456 $(node.get_children_ul()).slideDown("fast");
2457 } else {
2458 get_node(me, node);
2459 if ($(node.label_div).hasClass("absent")) {
2460 $(node.get_children_ul()).addClass("absent");
Scott Main3b90aff2013-08-01 18:09:35 -07002461 }
Scott Mainf5089842012-08-14 16:31:07 -07002462 $(node.get_children_ul()).slideDown("fast");
2463 }
2464 node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
2465 node.expanded = true;
2466
2467 // perform api level toggling because new nodes are new to the DOM
2468 var selectedLevel = $("#apiLevelSelector option:selected").val();
2469 toggleVisisbleApis(selectedLevel, "#side-nav");
2470 }
2471}
2472
2473function get_node(me, mom)
2474{
2475 mom.children_visited = true;
2476 for (var i in mom.children_data) {
2477 var node_data = mom.children_data[i];
2478 mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
2479 node_data[2], node_data[3]);
2480 }
2481}
2482
2483function this_page_relative(toroot)
2484{
2485 var full = document.location.pathname;
2486 var file = "";
2487 if (toroot.substr(0, 1) == "/") {
2488 if (full.substr(0, toroot.length) == toroot) {
2489 return full.substr(toroot.length);
2490 } else {
2491 // the file isn't under toroot. Fail.
2492 return null;
2493 }
2494 } else {
2495 if (toroot != "./") {
2496 toroot = "./" + toroot;
2497 }
2498 do {
2499 if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
2500 var pos = full.lastIndexOf("/");
2501 file = full.substr(pos) + file;
2502 full = full.substr(0, pos);
2503 toroot = toroot.substr(0, toroot.length-3);
2504 }
2505 } while (toroot != "" && toroot != "/");
2506 return file.substr(1);
2507 }
2508}
2509
2510function find_page(url, data)
2511{
2512 var nodes = data;
2513 var result = null;
2514 for (var i in nodes) {
2515 var d = nodes[i];
2516 if (d[1] == url) {
2517 return new Array(i);
2518 }
2519 else if (d[2] != null) {
2520 result = find_page(url, d[2]);
2521 if (result != null) {
2522 return (new Array(i).concat(result));
2523 }
2524 }
2525 }
2526 return null;
2527}
2528
Scott Mainf5089842012-08-14 16:31:07 -07002529function init_default_navtree(toroot) {
Scott Main25e73002013-03-27 15:24:06 -07002530 // load json file for navtree data
2531 $.getScript(toRoot + 'navtree_data.js', function(data, textStatus, jqxhr) {
2532 // when the file is loaded, initialize the tree
2533 if(jqxhr.status === 200) {
2534 init_navtree("tree-list", toroot, NAVTREE_DATA);
2535 }
2536 });
Scott Main3b90aff2013-08-01 18:09:35 -07002537
Scott Mainf5089842012-08-14 16:31:07 -07002538 // perform api level toggling because because the whole tree is new to the DOM
2539 var selectedLevel = $("#apiLevelSelector option:selected").val();
2540 toggleVisisbleApis(selectedLevel, "#side-nav");
2541}
2542
2543function init_navtree(navtree_id, toroot, root_nodes)
2544{
2545 var me = new Object();
2546 me.toroot = toroot;
2547 me.node = new Object();
2548
2549 me.node.li = document.getElementById(navtree_id);
2550 me.node.children_data = root_nodes;
2551 me.node.children = new Array();
2552 me.node.children_ul = document.createElement("ul");
2553 me.node.get_children_ul = function() { return me.node.children_ul; };
2554 //me.node.children_ul.className = "children_ul";
2555 me.node.li.appendChild(me.node.children_ul);
2556 me.node.depth = 0;
2557
2558 get_node(me, me.node);
2559
2560 me.this_page = this_page_relative(toroot);
2561 me.breadcrumbs = find_page(me.this_page, root_nodes);
2562 if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
2563 var mom = me.node;
2564 for (var i in me.breadcrumbs) {
2565 var j = me.breadcrumbs[i];
2566 mom = mom.children[j];
2567 expand_node(me, mom);
2568 }
2569 mom.label_div.className = mom.label_div.className + " selected";
2570 addLoadEvent(function() {
2571 scrollIntoView("nav-tree");
2572 });
2573 }
2574}
2575
Dirk Dougherty4f7e5152010-09-16 10:43:40 -07002576
2577
2578
2579
2580
2581
2582
Robert Lyd2dd6e52012-11-29 21:28:48 -08002583/* TODO: eliminate redundancy with non-google functions */
2584function init_google_navtree(navtree_id, toroot, root_nodes)
2585{
2586 var me = new Object();
2587 me.toroot = toroot;
2588 me.node = new Object();
2589
2590 me.node.li = document.getElementById(navtree_id);
2591 me.node.children_data = root_nodes;
2592 me.node.children = new Array();
2593 me.node.children_ul = document.createElement("ul");
2594 me.node.get_children_ul = function() { return me.node.children_ul; };
2595 //me.node.children_ul.className = "children_ul";
2596 me.node.li.appendChild(me.node.children_ul);
2597 me.node.depth = 0;
2598
2599 get_google_node(me, me.node);
Robert Lyd2dd6e52012-11-29 21:28:48 -08002600}
2601
2602function new_google_node(me, mom, text, link, children_data, api_level)
2603{
2604 var node = new Object();
2605 var child;
2606 node.children = Array();
2607 node.children_data = children_data;
2608 node.depth = mom.depth + 1;
2609 node.get_children_ul = function() {
2610 if (!node.children_ul) {
Scott Main3b90aff2013-08-01 18:09:35 -07002611 node.children_ul = document.createElement("ul");
2612 node.children_ul.className = "tree-list-children";
Robert Lyd2dd6e52012-11-29 21:28:48 -08002613 node.li.appendChild(node.children_ul);
2614 }
2615 return node.children_ul;
2616 };
2617 node.li = document.createElement("li");
2618
2619 mom.get_children_ul().appendChild(node.li);
Scott Main3b90aff2013-08-01 18:09:35 -07002620
2621
Robert Lyd2dd6e52012-11-29 21:28:48 -08002622 if(link) {
2623 child = document.createElement("a");
2624
2625 }
2626 else {
2627 child = document.createElement("span");
Scott Mainac71b2b2012-11-30 14:40:58 -08002628 child.className = "tree-list-subtitle";
Robert Lyd2dd6e52012-11-29 21:28:48 -08002629
2630 }
2631 if (children_data != null) {
2632 node.li.className="nav-section";
2633 node.label_div = document.createElement("div");
Scott Main3b90aff2013-08-01 18:09:35 -07002634 node.label_div.className = "nav-section-header-ref";
Robert Lyd2dd6e52012-11-29 21:28:48 -08002635 node.li.appendChild(node.label_div);
2636 get_google_node(me, node);
2637 node.label_div.appendChild(child);
2638 }
2639 else {
2640 node.li.appendChild(child);
2641 }
2642 if(link) {
2643 child.href = me.toroot + link;
2644 }
2645 node.label = document.createTextNode(text);
2646 child.appendChild(node.label);
2647
2648 node.children_ul = null;
2649
2650 return node;
2651}
2652
2653function get_google_node(me, mom)
2654{
2655 mom.children_visited = true;
2656 var linkText;
2657 for (var i in mom.children_data) {
2658 var node_data = mom.children_data[i];
2659 linkText = node_data[0];
2660
2661 if(linkText.match("^"+"com.google.android")=="com.google.android"){
2662 linkText = linkText.substr(19, linkText.length);
2663 }
2664 mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
2665 node_data[2], node_data[3]);
2666 }
2667}
Scott Mainad08f072013-08-20 16:49:57 -07002668
2669
2670
2671
2672
2673
2674/****** NEW version of script to build google and sample navs dynamically ******/
2675// TODO: update Google reference docs to tolerate this new implementation
2676
2677function init_google_navtree2(navtree_id, data)
2678{
2679 var $containerUl = $("#"+navtree_id);
2680 var linkText;
2681 for (var i in data) {
2682 var node_data = data[i];
2683 $containerUl.append(new_google_node2(node_data));
2684 }
2685
2686 initExpandableNavItems("#"+navtree_id);
2687}
2688
2689function new_google_node2(node_data)
2690{
2691 var linkText = node_data[0];
2692 if(linkText.match("^"+"com.google.android")=="com.google.android"){
2693 linkText = linkText.substr(19, linkText.length);
2694 }
2695 var $li = $('<li>');
2696 var $a;
2697 if (node_data[1] != null) {
2698 $a = $('<a href="' + toRoot + node_data[1] + '">' + linkText + '</a>');
2699 } else {
2700 $a = $('<a href="#" onclick="return false;">' + linkText + '/</a>');
2701 }
2702 var $childUl = $('<ul>');
2703 if (node_data[2] != null) {
2704 $li.addClass("nav-section");
2705 $a = $('<div class="nav-section-header">').append($a);
2706 if (node_data[1] == null) $a.addClass('empty');
2707
2708 for (var i in node_data[2]) {
2709 var child_node_data = node_data[2][i];
2710 $childUl.append(new_google_node2(child_node_data));
2711 }
2712 $li.append($childUl);
2713 }
2714 $li.prepend($a);
2715
2716 return $li;
2717}
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
Robert Lyd2dd6e52012-11-29 21:28:48 -08002729function showGoogleRefTree() {
2730 init_default_google_navtree(toRoot);
2731 init_default_gcm_navtree(toRoot);
Robert Lyd2dd6e52012-11-29 21:28:48 -08002732}
2733
2734function init_default_google_navtree(toroot) {
Scott Mainf6145542013-04-01 16:38:11 -07002735 // load json file for navtree data
2736 $.getScript(toRoot + 'gms_navtree_data.js', function(data, textStatus, jqxhr) {
2737 // when the file is loaded, initialize the tree
2738 if(jqxhr.status === 200) {
2739 init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
2740 highlightSidenav();
2741 resizeNav();
2742 }
2743 });
Robert Lyd2dd6e52012-11-29 21:28:48 -08002744}
2745
2746function init_default_gcm_navtree(toroot) {
Scott Mainf6145542013-04-01 16:38:11 -07002747 // load json file for navtree data
2748 $.getScript(toRoot + 'gcm_navtree_data.js', function(data, textStatus, jqxhr) {
2749 // when the file is loaded, initialize the tree
2750 if(jqxhr.status === 200) {
2751 init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
2752 highlightSidenav();
2753 resizeNav();
2754 }
2755 });
Robert Lyd2dd6e52012-11-29 21:28:48 -08002756}
2757
Dirk Dougherty4f7e5152010-09-16 10:43:40 -07002758function showSamplesRefTree() {
2759 init_default_samples_navtree(toRoot);
2760}
2761
2762function init_default_samples_navtree(toroot) {
2763 // load json file for navtree data
2764 $.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
2765 // when the file is loaded, initialize the tree
2766 if(jqxhr.status === 200) {
Scott Mainad08f072013-08-20 16:49:57 -07002767 init_google_navtree2("nav.samples-nav", SAMPLES_NAVTREE_DATA);
Dirk Dougherty4f7e5152010-09-16 10:43:40 -07002768 highlightSidenav();
2769 resizeNav();
2770 }
2771 });
2772}
2773
Scott Mainf5089842012-08-14 16:31:07 -07002774/* TOGGLE INHERITED MEMBERS */
2775
2776/* Toggle an inherited class (arrow toggle)
2777 * @param linkObj The link that was clicked.
2778 * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
2779 * 'null' to simply toggle.
2780 */
2781function toggleInherited(linkObj, expand) {
2782 var base = linkObj.getAttribute("id");
2783 var list = document.getElementById(base + "-list");
2784 var summary = document.getElementById(base + "-summary");
2785 var trigger = document.getElementById(base + "-trigger");
2786 var a = $(linkObj);
2787 if ( (expand == null && a.hasClass("closed")) || expand ) {
2788 list.style.display = "none";
2789 summary.style.display = "block";
2790 trigger.src = toRoot + "assets/images/triangle-opened.png";
2791 a.removeClass("closed");
2792 a.addClass("opened");
2793 } else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
2794 list.style.display = "block";
2795 summary.style.display = "none";
2796 trigger.src = toRoot + "assets/images/triangle-closed.png";
2797 a.removeClass("opened");
2798 a.addClass("closed");
2799 }
2800 return false;
2801}
2802
2803/* Toggle all inherited classes in a single table (e.g. all inherited methods)
2804 * @param linkObj The link that was clicked.
2805 * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
2806 * 'null' to simply toggle.
2807 */
2808function toggleAllInherited(linkObj, expand) {
2809 var a = $(linkObj);
2810 var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
2811 var expandos = $(".jd-expando-trigger", table);
2812 if ( (expand == null && a.text() == "[Expand]") || expand ) {
2813 expandos.each(function(i) {
2814 toggleInherited(this, true);
2815 });
2816 a.text("[Collapse]");
2817 } else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
2818 expandos.each(function(i) {
2819 toggleInherited(this, false);
2820 });
2821 a.text("[Expand]");
2822 }
2823 return false;
2824}
2825
2826/* Toggle all inherited members in the class (link in the class title)
2827 */
2828function toggleAllClassInherited() {
2829 var a = $("#toggleAllClassInherited"); // get toggle link from class title
2830 var toggles = $(".toggle-all", $("#body-content"));
2831 if (a.text() == "[Expand All]") {
2832 toggles.each(function(i) {
2833 toggleAllInherited(this, true);
2834 });
2835 a.text("[Collapse All]");
2836 } else {
2837 toggles.each(function(i) {
2838 toggleAllInherited(this, false);
2839 });
2840 a.text("[Expand All]");
2841 }
2842 return false;
2843}
2844
2845/* Expand all inherited members in the class. Used when initiating page search */
2846function ensureAllInheritedExpanded() {
2847 var toggles = $(".toggle-all", $("#body-content"));
2848 toggles.each(function(i) {
2849 toggleAllInherited(this, true);
2850 });
2851 $("#toggleAllClassInherited").text("[Collapse All]");
2852}
2853
2854
2855/* HANDLE KEY EVENTS
2856 * - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
2857 */
2858var agent = navigator['userAgent'].toLowerCase();
2859var mac = agent.indexOf("macintosh") != -1;
2860
2861$(document).keydown( function(e) {
2862var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
2863 if (control && e.which == 70) { // 70 is "F"
2864 ensureAllInheritedExpanded();
2865 }
2866});
Scott Main498d7102013-08-21 15:47:38 -07002867
2868
2869
2870
2871
2872
2873/* On-demand functions */
2874
2875/** Move sample code line numbers out of PRE block and into non-copyable column */
2876function initCodeLineNumbers() {
2877 var numbers = $("#codesample-block a.number");
2878 if (numbers.length) {
2879 $("#codesample-line-numbers").removeClass("hidden").append(numbers);
2880 }
2881
2882 $(document).ready(function() {
2883 // select entire line when clicked
2884 $("span.code-line").click(function() {
2885 if (!shifted) {
2886 selectText(this);
2887 }
2888 });
2889 // invoke line link on double click
2890 $(".code-line").dblclick(function() {
2891 document.location.hash = $(this).attr('id');
2892 });
2893 // highlight the line when hovering on the number
2894 $("#codesample-line-numbers a.number").mouseover(function() {
2895 var id = $(this).attr('href');
2896 $(id).css('background','#e7e7e7');
2897 });
2898 $("#codesample-line-numbers a.number").mouseout(function() {
2899 var id = $(this).attr('href');
2900 $(id).css('background','none');
2901 });
2902 });
2903}
2904
2905// create SHIFT key binder to avoid the selectText method when selecting multiple lines
2906var shifted = false;
2907$(document).bind('keyup keydown', function(e){shifted = e.shiftKey; return true;} );
2908
2909// courtesy of jasonedelman.com
2910function selectText(element) {
2911 var doc = document
2912 , range, selection
2913 ;
2914 if (doc.body.createTextRange) { //ms
2915 range = doc.body.createTextRange();
2916 range.moveToElementText(element);
2917 range.select();
2918 } else if (window.getSelection) { //all others
2919 selection = window.getSelection();
2920 range = doc.createRange();
2921 range.selectNodeContents(element);
2922 selection.removeAllRanges();
2923 selection.addRange(range);
2924 }
2925}