blob: cfecf30bbbb51cafcebe5d45efe756bbc34c1f8f [file] [log] [blame]
Dirk Dougherty541b4942014-02-14 18:31:53 -08001var classesNav;
2var devdocNav;
3var sidenav;
4var cookie_namespace = 'android_developer';
5var NAV_PREF_TREE = "tree";
6var NAV_PREF_PANELS = "panels";
7var nav_pref;
8var isMobile = false; // true if mobile, so we can adjust some layout
9var mPagePath; // initialized in ready() function
10
11var basePath = getBaseUri(location.pathname);
12var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
13var GOOGLE_DATA; // combined data for google service apis, used for search suggest
14
15// Ensure that all ajax getScript() requests allow caching
16$.ajaxSetup({
17 cache: true
18});
19
20/****** ON LOAD SET UP STUFF *********/
21
22var navBarIsFixed = false;
23$(document).ready(function() {
24
25 // load json file for JD doc search suggestions
26 $.getScript(toRoot + 'jd_lists_unified.js');
27 // load json file for Android API search suggestions
28 $.getScript(toRoot + 'reference/lists.js');
29 // load json files for Google services API suggestions
30 $.getScript(toRoot + 'reference/gcm_lists.js', function(data, textStatus, jqxhr) {
31 // once the GCM json (GCM_DATA) is loaded, load the GMS json (GMS_DATA) and merge the data
32 if(jqxhr.status === 200) {
33 $.getScript(toRoot + 'reference/gms_lists.js', function(data, textStatus, jqxhr) {
34 if(jqxhr.status === 200) {
35 // combine GCM and GMS data
36 GOOGLE_DATA = GMS_DATA;
37 var start = GOOGLE_DATA.length;
38 for (var i=0; i<GCM_DATA.length; i++) {
39 GOOGLE_DATA.push({id:start+i, label:GCM_DATA[i].label,
40 link:GCM_DATA[i].link, type:GCM_DATA[i].type});
41 }
42 }
43 });
44 }
45 });
46
47 // setup keyboard listener for search shortcut
48 $('body').keyup(function(event) {
49 if (event.which == 191) {
50 $('#search_autocomplete').focus();
51 }
52 });
53
54 // init the fullscreen toggle click event
55 $('#nav-swap .fullscreen').click(function(){
56 if ($(this).hasClass('disabled')) {
57 toggleFullscreen(true);
58 } else {
59 toggleFullscreen(false);
60 }
61 });
62
63 // initialize the divs with custom scrollbars
64 $('.scroll-pane').jScrollPane( {verticalGutter:0} );
65
66 // add HRs below all H2s (except for a few other h2 variants)
67 $('h2').not('#qv h2').not('#tb h2').not('.sidebox h2').not('#devdoc-nav h2').not('h2.norule').css({marginBottom:0}).after('<hr/>');
68
69 // set up the search close button
70 $('.search .close').click(function() {
71 $searchInput = $('#search_autocomplete');
72 $searchInput.attr('value', '');
73 $(this).addClass("hide");
74 $("#search-container").removeClass('active');
75 $("#search_autocomplete").blur();
76 search_focus_changed($searchInput.get(), false);
77 hideResults();
78 });
79
80 // Set up quicknav
81 var quicknav_open = false;
82 $("#btn-quicknav").click(function() {
83 if (quicknav_open) {
84 $(this).removeClass('active');
85 quicknav_open = false;
86 collapse();
87 } else {
88 $(this).addClass('active');
89 quicknav_open = true;
90 expand();
91 }
92 })
93
94 var expand = function() {
95 $('#header-wrap').addClass('quicknav');
96 $('#quicknav').stop().show().animate({opacity:'1'});
97 }
98
99 var collapse = function() {
100 $('#quicknav').stop().animate({opacity:'0'}, 100, function() {
101 $(this).hide();
102 $('#header-wrap').removeClass('quicknav');
103 });
104 }
105
106
107 //Set up search
108 $("#search_autocomplete").focus(function() {
109 $("#search-container").addClass('active');
110 })
111 $("#search-container").mouseover(function() {
112 $("#search-container").addClass('active');
113 $("#search_autocomplete").focus();
114 })
115 $("#search-container").mouseout(function() {
116 if ($("#search_autocomplete").is(":focus")) return;
117 if ($("#search_autocomplete").val() == '') {
118 setTimeout(function(){
119 $("#search-container").removeClass('active');
120 $("#search_autocomplete").blur();
121 },250);
122 }
123 })
124 $("#search_autocomplete").blur(function() {
125 if ($("#search_autocomplete").val() == '') {
126 $("#search-container").removeClass('active');
127 }
128 })
129
130
131 // prep nav expandos
132 var pagePath = document.location.pathname;
133 // account for intl docs by removing the intl/*/ path
134 if (pagePath.indexOf("/intl/") == 0) {
135 pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last /
136 }
137
138 if (pagePath.indexOf(SITE_ROOT) == 0) {
139 if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
140 pagePath += 'index.html';
141 }
142 }
143
144 // Need a copy of the pagePath before it gets changed in the next block;
145 // it's needed to perform proper tab highlighting in offline docs (see rootDir below)
146 var pagePathOriginal = pagePath;
147 if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
148 // If running locally, SITE_ROOT will be a relative path, so account for that by
149 // finding the relative URL to this page. This will allow us to find links on the page
150 // leading back to this page.
151 var pathParts = pagePath.split('/');
152 var relativePagePathParts = [];
153 var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
154 for (var i = 0; i < upDirs; i++) {
155 relativePagePathParts.push('..');
156 }
157 for (var i = 0; i < upDirs; i++) {
158 relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
159 }
160 relativePagePathParts.push(pathParts[pathParts.length - 1]);
161 pagePath = relativePagePathParts.join('/');
162 } else {
163 // Otherwise the page path is already an absolute URL
164 }
165
166 // Highlight the header tabs...
167 // highlight Design tab
168 if ($("body").hasClass("design")) {
169 $("#header li.design a").addClass("selected");
Dirk Dougherty08032402014-02-15 10:14:35 -0800170 $("#sticky-header").addClass("design");
Dirk Dougherty541b4942014-02-14 18:31:53 -0800171
172 // highlight Develop tab
173 } else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
174 $("#header li.develop a").addClass("selected");
Dirk Dougherty08032402014-02-15 10:14:35 -0800175 $("#sticky-header").addClass("develop");
Dirk Dougherty541b4942014-02-14 18:31:53 -0800176 // In Develop docs, also highlight appropriate sub-tab
177 var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
178 if (rootDir == "training") {
179 $("#nav-x li.training a").addClass("selected");
180 } else if (rootDir == "guide") {
181 $("#nav-x li.guide a").addClass("selected");
182 } else if (rootDir == "reference") {
183 // If the root is reference, but page is also part of Google Services, select Google
184 if ($("body").hasClass("google")) {
185 $("#nav-x li.google a").addClass("selected");
186 } else {
187 $("#nav-x li.reference a").addClass("selected");
188 }
189 } else if ((rootDir == "tools") || (rootDir == "sdk")) {
190 $("#nav-x li.tools a").addClass("selected");
191 } else if ($("body").hasClass("google")) {
192 $("#nav-x li.google a").addClass("selected");
193 } else if ($("body").hasClass("samples")) {
194 $("#nav-x li.samples a").addClass("selected");
195 }
196
197 // highlight Distribute tab
198 } else if ($("body").hasClass("distribute")) {
199 $("#header li.distribute a").addClass("selected");
Dirk Dougherty08032402014-02-15 10:14:35 -0800200 $("#sticky-header").addClass("distribute");
Dirk Dougherty541b4942014-02-14 18:31:53 -0800201
Dirk Dougherty08032402014-02-15 10:14:35 -0800202 var baseFrag = pagePathOriginal.indexOf('/', 1) + 1;
203 var secondFrag = pagePathOriginal.substring(baseFrag, pagePathOriginal.indexOf('/', baseFrag));
204 if (secondFrag == "users") {
205 $("#nav-x li.users a").addClass("selected");
206 } else if (secondFrag == "engage") {
207 $("#nav-x li.engage a").addClass("selected");
208 } else if (secondFrag == "monetize") {
209 $("#nav-x li.monetize a").addClass("selected");
210 } else if (secondFrag == "tools") {
211 $("#nav-x li.disttools a").addClass("selected");
212 } else if (secondFrag == "stories") {
213 $("#nav-x li.stories a").addClass("selected");
214 } else if (secondFrag == "essentials") {
215 $("#nav-x li.essentials a").addClass("selected");
216 } else if (secondFrag == "googleplay") {
217 $("#nav-x li.googleplay a").addClass("selected");
218 }
219 }
Dirk Dougherty541b4942014-02-14 18:31:53 -0800220 // set global variable so we can highlight the sidenav a bit later (such as for google reference)
221 // and highlight the sidenav
222 mPagePath = pagePath;
223 highlightSidenav();
Scott Main20cf2a92014-04-02 21:57:20 -0700224 buildBreadcrumbs();
Dirk Dougherty541b4942014-02-14 18:31:53 -0800225
226 // set up prev/next links if they exist
227 var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
228 var $selListItem;
229 if ($selNavLink.length) {
230 $selListItem = $selNavLink.closest('li');
231
232 // set up prev links
233 var $prevLink = [];
234 var $prevListItem = $selListItem.prev('li');
235
236 var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
237false; // navigate across topic boundaries only in design docs
238 if ($prevListItem.length) {
239 if ($prevListItem.hasClass('nav-section')) {
240 // jump to last topic of previous section
241 $prevLink = $prevListItem.find('a:last');
242 } else if (!$selListItem.hasClass('nav-section')) {
243 // jump to previous topic in this section
244 $prevLink = $prevListItem.find('a:eq(0)');
245 }
246 } else {
247 // jump to this section's index page (if it exists)
248 var $parentListItem = $selListItem.parents('li');
249 $prevLink = $selListItem.parents('li').find('a');
250
251 // except if cross boundaries aren't allowed, and we're at the top of a section already
252 // (and there's another parent)
253 if (!crossBoundaries && $parentListItem.hasClass('nav-section')
254 && $selListItem.hasClass('nav-section')) {
255 $prevLink = [];
256 }
257 }
258
259 // set up next links
260 var $nextLink = [];
261 var startClass = false;
262 var training = $(".next-class-link").length; // decides whether to provide "next class" link
263 var isCrossingBoundary = false;
264
265 if ($selListItem.hasClass('nav-section') && $selListItem.children('div.empty').length == 0) {
266 // we're on an index page, jump to the first topic
267 $nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
268
269 // if there aren't any children, go to the next section (required for About pages)
270 if($nextLink.length == 0) {
271 $nextLink = $selListItem.next('li').find('a');
272 } else if ($('.topic-start-link').length) {
273 // as long as there's a child link and there is a "topic start link" (we're on a landing)
274 // then set the landing page "start link" text to be the first doc title
275 $('.topic-start-link').text($nextLink.text().toUpperCase());
276 }
277
278 // If the selected page has a description, then it's a class or article homepage
279 if ($selListItem.find('a[description]').length) {
280 // this means we're on a class landing page
281 startClass = true;
282 }
283 } else {
284 // jump to the next topic in this section (if it exists)
285 $nextLink = $selListItem.next('li').find('a:eq(0)');
286 if ($nextLink.length == 0) {
287 isCrossingBoundary = true;
288 // no more topics in this section, jump to the first topic in the next section
289 $nextLink = $selListItem.parents('li:eq(0)').next('li.nav-section').find('a:eq(0)');
290 if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course)
291 $nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
292 if ($nextLink.length == 0) {
293 // if that doesn't work, we're at the end of the list, so disable NEXT link
294 $('.next-page-link').attr('href','').addClass("disabled")
295 .click(function() { return false; });
296 }
297 }
298 }
299 }
300
301 if (startClass) {
302 $('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
303
304 // if there's no training bar (below the start button),
305 // then we need to add a bottom border to button
306 if (!$("#tb").length) {
307 $('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
308 }
309 } else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries
310 $('.content-footer.next-class').show();
311 $('.next-page-link').attr('href','')
312 .removeClass("hide").addClass("disabled")
313 .click(function() { return false; });
314 if ($nextLink.length) {
315 $('.next-class-link').attr('href',$nextLink.attr('href'))
316 .removeClass("hide").append($nextLink.html());
317 $('.next-class-link').find('.new').empty();
318 }
319 } else {
320 $('.next-page-link').attr('href', $nextLink.attr('href')).removeClass("hide");
321 }
322
323 if (!startClass && $prevLink.length) {
324 var prevHref = $prevLink.attr('href');
325 if (prevHref == SITE_ROOT + 'index.html') {
326 // Don't show Previous when it leads to the homepage
327 } else {
328 $('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide");
329 }
330 }
331
332 // If this is a training 'article', there should be no prev/next nav
333 // ... if the grandparent is the "nav" ... and it has no child list items...
334 if (training && $selListItem.parents('ul').eq(1).is('[id="nav"]') &&
335 !$selListItem.find('li').length) {
336 $('.next-page-link,.prev-page-link').attr('href','').addClass("disabled")
337 .click(function() { return false; });
338 }
339
340 }
341
342
343
344 // Set up the course landing pages for Training with class names and descriptions
345 if ($('body.trainingcourse').length) {
346 var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
347 var $classDescriptions = $classLinks.attr('description');
348
349 var $olClasses = $('<ol class="class-list"></ol>');
350 var $liClass;
351 var $imgIcon;
352 var $h2Title;
353 var $pSummary;
354 var $olLessons;
355 var $liLesson;
356 $classLinks.each(function(index) {
357 $liClass = $('<li></li>');
358 $h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
359 $pSummary = $('<p class="description">' + $(this).attr('description') + '</p>');
360
361 $olLessons = $('<ol class="lesson-list"></ol>');
362
363 $lessons = $(this).closest('li').find('ul li a');
364
365 if ($lessons.length) {
366 $imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" '
367 + ' width="64" height="64" alt=""/>');
368 $lessons.each(function(index) {
369 $olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
370 });
371 } else {
372 $imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" '
373 + ' width="64" height="64" alt=""/>');
374 $pSummary.addClass('article');
375 }
376
377 $liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons);
378 $olClasses.append($liClass);
379 });
380 $('.jd-descr').append($olClasses);
381 }
382
383 // Set up expand/collapse behavior
384 initExpandableNavItems("#nav");
385
386
387 $(".scroll-pane").scroll(function(event) {
388 event.preventDefault();
389 return false;
390 });
391
392 /* Resize nav height when window height changes */
393 $(window).resize(function() {
394 if ($('#side-nav').length == 0) return;
395 var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
396 setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
397 // make sidenav behave when resizing the window and side-scolling is a concern
398 if (navBarIsFixed) {
399 if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
400 updateSideNavPosition();
401 } else {
402 updateSidenavFullscreenWidth();
403 }
404 }
405 resizeNav();
406 });
407
408
Dirk Dougherty541b4942014-02-14 18:31:53 -0800409 var navBarLeftPos;
410 if ($('#devdoc-nav').length) {
411 setNavBarLeftPos();
412 }
413
414
415 // Set up play-on-hover <video> tags.
416 $('video.play-on-hover').bind('click', function(){
417 $(this).get(0).load(); // in case the video isn't seekable
418 $(this).get(0).play();
419 });
420
421 // Set up tooltips
422 var TOOLTIP_MARGIN = 10;
423 $('acronym,.tooltip-link').each(function() {
424 var $target = $(this);
425 var $tooltip = $('<div>')
426 .addClass('tooltip-box')
427 .append($target.attr('title'))
428 .hide()
429 .appendTo('body');
430 $target.removeAttr('title');
431
432 $target.hover(function() {
433 // in
434 var targetRect = $target.offset();
435 targetRect.width = $target.width();
436 targetRect.height = $target.height();
437
438 $tooltip.css({
439 left: targetRect.left,
440 top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
441 });
442 $tooltip.addClass('below');
443 $tooltip.show();
444 }, function() {
445 // out
446 $tooltip.hide();
447 });
448 });
449
450 // Set up <h2> deeplinks
451 $('h2').click(function() {
452 var id = $(this).attr('id');
453 if (id) {
454 document.location.hash = id;
455 }
456 });
457
458 //Loads the +1 button
459 var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
460 po.src = 'https://apis.google.com/js/plusone.js';
461 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
462
463
464 // Revise the sidenav widths to make room for the scrollbar
465 // which avoids the visible width from changing each time the bar appears
466 var $sidenav = $("#side-nav");
467 var sidenav_width = parseInt($sidenav.innerWidth());
468
469 $("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
470
471
472 $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
473
474 if ($(".scroll-pane").length > 1) {
475 // Check if there's a user preference for the panel heights
476 var cookieHeight = readCookie("reference_height");
477 if (cookieHeight) {
478 restoreHeight(cookieHeight);
479 }
480 }
481
482 resizeNav();
483
484 /* init the language selector based on user cookie for lang */
485 loadLangPref();
486 changeNavLang(getLangPref());
487
488 /* setup event handlers to ensure the overflow menu is visible while picking lang */
489 $("#language select")
490 .mousedown(function() {
491 $("div.morehover").addClass("hover"); })
492 .blur(function() {
493 $("div.morehover").removeClass("hover"); });
494
495 /* some global variable setup */
496 resizePackagesNav = $("#resize-packages-nav");
497 classesNav = $("#classes-nav");
498 devdocNav = $("#devdoc-nav");
499
500 var cookiePath = "";
501 if (location.href.indexOf("/reference/") != -1) {
502 cookiePath = "reference_";
503 } else if (location.href.indexOf("/guide/") != -1) {
504 cookiePath = "guide_";
505 } else if (location.href.indexOf("/tools/") != -1) {
506 cookiePath = "tools_";
507 } else if (location.href.indexOf("/training/") != -1) {
508 cookiePath = "training_";
509 } else if (location.href.indexOf("/design/") != -1) {
510 cookiePath = "design_";
511 } else if (location.href.indexOf("/distribute/") != -1) {
512 cookiePath = "distribute_";
513 }
514
515});
516// END of the onload event
517
518
519function initExpandableNavItems(rootTag) {
520 $(rootTag + ' li.nav-section .nav-section-header').click(function() {
521 var section = $(this).closest('li.nav-section');
522 if (section.hasClass('expanded')) {
523 /* hide me and descendants */
524 section.find('ul').slideUp(250, function() {
525 // remove 'expanded' class from my section and any children
526 section.closest('li').removeClass('expanded');
527 $('li.nav-section', section).removeClass('expanded');
528 resizeNav();
529 });
530 } else {
531 /* show me */
532 // first hide all other siblings
533 var $others = $('li.nav-section.expanded', $(this).closest('ul')).not('.sticky');
534 $others.removeClass('expanded').children('ul').slideUp(250);
535
536 // now expand me
537 section.closest('li').addClass('expanded');
538 section.children('ul').slideDown(250, function() {
539 resizeNav();
540 });
541 }
542 });
543
544 // Stop expand/collapse behavior when clicking on nav section links
545 // (since we're navigating away from the page)
546 // This selector captures the first instance of <a>, but not those with "#" as the href.
547 $('.nav-section-header').find('a:eq(0)').not('a[href="#"]').click(function(evt) {
548 window.location.href = $(this).attr('href');
549 return false;
550 });
551}
552
Scott Main20cf2a92014-04-02 21:57:20 -0700553
554/** Create the list of breadcrumb links in the sticky header */
555function buildBreadcrumbs() {
556 var $breadcrumbUl = $("#sticky-header ul.breadcrumb");
557 // Add the secondary horizontal nav item, if provided
558 var $selectedSecondNav = $("div#nav-x ul.nav-x a.selected").clone().removeClass("selected");
559 if ($selectedSecondNav.length) {
560 $breadcrumbUl.prepend($("<li>").append($selectedSecondNav))
561 }
562 // Add the primary horizontal nav
563 var $selectedFirstNav = $("div#header-wrap ul.nav-x a.selected").clone().removeClass("selected");
564 $breadcrumbUl.prepend($("<li>").append($selectedFirstNav));
565}
566
567
568
Dirk Dougherty541b4942014-02-14 18:31:53 -0800569/** Highlight the current page in sidenav, expanding children as appropriate */
570function highlightSidenav() {
571 // if something is already highlighted, undo it. This is for dynamic navigation (Samples index)
572 if ($("ul#nav li.selected").length) {
573 unHighlightSidenav();
574 }
575 // look for URL in sidenav, including the hash
576 var $selNavLink = $('#nav').find('a[href="' + mPagePath + location.hash + '"]');
577
578 // If the selNavLink is still empty, look for it without the hash
579 if ($selNavLink.length == 0) {
580 $selNavLink = $('#nav').find('a[href="' + mPagePath + '"]');
581 }
582
583 var $selListItem;
584 if ($selNavLink.length) {
585 // Find this page's <li> in sidenav and set selected
586 $selListItem = $selNavLink.closest('li');
587 $selListItem.addClass('selected');
588
589 // Traverse up the tree and expand all parent nav-sections
590 $selNavLink.parents('li.nav-section').each(function() {
591 $(this).addClass('expanded');
592 $(this).children('ul').show();
593 });
594 }
595}
596
597function unHighlightSidenav() {
598 $("ul#nav li.selected").removeClass("selected");
599 $('ul#nav li.nav-section.expanded').removeClass('expanded').children('ul').hide();
600}
601
602function toggleFullscreen(enable) {
603 var delay = 20;
604 var enabled = true;
605 var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
606 if (enable) {
607 // Currently NOT USING fullscreen; enable fullscreen
608 stylesheet.removeAttr('disabled');
609 $('#nav-swap .fullscreen').removeClass('disabled');
610 $('#devdoc-nav').css({left:''});
611 setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
612 enabled = true;
613 } else {
614 // Currently USING fullscreen; disable fullscreen
615 stylesheet.attr('disabled', 'disabled');
616 $('#nav-swap .fullscreen').addClass('disabled');
617 setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
618 enabled = false;
619 }
620 writeCookie("fullscreen", enabled, null, null);
621 setNavBarLeftPos();
622 resizeNav(delay);
623 updateSideNavPosition();
624 setTimeout(initSidenavHeightResize,delay);
625}
626
627
628function setNavBarLeftPos() {
629 navBarLeftPos = $('#body-content').offset().left;
630}
631
632
633function updateSideNavPosition() {
634 var newLeft = $(window).scrollLeft() - navBarLeftPos;
635 $('#devdoc-nav').css({left: -newLeft});
636 $('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
637}
638
639// TODO: use $(document).ready instead
640function addLoadEvent(newfun) {
641 var current = window.onload;
642 if (typeof window.onload != 'function') {
643 window.onload = newfun;
644 } else {
645 window.onload = function() {
646 current();
647 newfun();
648 }
649 }
650}
651
652var agent = navigator['userAgent'].toLowerCase();
653// If a mobile phone, set flag and do mobile setup
654if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
655 (agent.indexOf("blackberry") != -1) ||
656 (agent.indexOf("webos") != -1) ||
657 (agent.indexOf("mini") != -1)) { // opera mini browsers
658 isMobile = true;
659}
660
661
662$(document).ready(function() {
663 $("pre:not(.no-pretty-print)").addClass("prettyprint");
664 prettyPrint();
665});
666
667
668
669
670/* ######### RESIZE THE SIDENAV HEIGHT ########## */
671
672function resizeNav(delay) {
673 var $nav = $("#devdoc-nav");
674 var $window = $(window);
675 var navHeight;
676
677 // Get the height of entire window and the total header height.
678 // Then figure out based on scroll position whether the header is visible
679 var windowHeight = $window.height();
680 var scrollTop = $window.scrollTop();
Scott Main20cf2a92014-04-02 21:57:20 -0700681 var headerHeight = $('#header-wrapper').outerHeight();
682 var headerVisible = scrollTop < stickyTop;
Dirk Dougherty541b4942014-02-14 18:31:53 -0800683
684 // get the height of space between nav and top of window.
685 // Could be either margin or top position, depending on whether the nav is fixed.
686 var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
687 // add 1 for the #side-nav bottom margin
688
689 // Depending on whether the header is visible, set the side nav's height.
690 if (headerVisible) {
691 // The sidenav height grows as the header goes off screen
Scott Main20cf2a92014-04-02 21:57:20 -0700692 navHeight = windowHeight - (headerHeight - scrollTop) - topMargin;
Dirk Dougherty541b4942014-02-14 18:31:53 -0800693 } else {
694 // Once header is off screen, the nav height is almost full window height
695 navHeight = windowHeight - topMargin;
696 }
697
698
699
700 $scrollPanes = $(".scroll-pane");
701 if ($scrollPanes.length > 1) {
702 // subtract the height of the api level widget and nav swapper from the available nav height
703 navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
704
705 $("#swapper").css({height:navHeight + "px"});
706 if ($("#nav-tree").is(":visible")) {
707 $("#nav-tree").css({height:navHeight});
708 }
709
710 var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
711 //subtract 10px to account for drag bar
712
713 // if the window becomes small enough to make the class panel height 0,
714 // then the package panel should begin to shrink
715 if (parseInt(classesHeight) <= 0) {
716 $("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
717 $("#packages-nav").css({height:navHeight - 10});
718 }
719
720 $("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
721 $("#classes-nav .jspContainer").css({height:classesHeight});
722
723
724 } else {
725 $nav.height(navHeight);
726 }
727
728 if (delay) {
729 updateFromResize = true;
730 delayedReInitScrollbars(delay);
731 } else {
732 reInitScrollbars();
733 }
734
735}
736
737var updateScrollbars = false;
738var updateFromResize = false;
739
740/* Re-initialize the scrollbars to account for changed nav size.
741 * This method postpones the actual update by a 1/4 second in order to optimize the
742 * scroll performance while the header is still visible, because re-initializing the
743 * scroll panes is an intensive process.
744 */
745function delayedReInitScrollbars(delay) {
746 // If we're scheduled for an update, but have received another resize request
747 // before the scheduled resize has occured, just ignore the new request
748 // (and wait for the scheduled one).
749 if (updateScrollbars && updateFromResize) {
750 updateFromResize = false;
751 return;
752 }
753
754 // We're scheduled for an update and the update request came from this method's setTimeout
755 if (updateScrollbars && !updateFromResize) {
756 reInitScrollbars();
757 updateScrollbars = false;
758 } else {
759 updateScrollbars = true;
760 updateFromResize = false;
761 setTimeout('delayedReInitScrollbars()',delay);
762 }
763}
764
765/* Re-initialize the scrollbars to account for changed nav size. */
766function reInitScrollbars() {
767 var pane = $(".scroll-pane").each(function(){
768 var api = $(this).data('jsp');
769 if (!api) { setTimeout(reInitScrollbars,300); return;}
770 api.reinitialise( {verticalGutter:0} );
771 });
772 $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
773}
774
775
776/* Resize the height of the nav panels in the reference,
777 * and save the new size to a cookie */
778function saveNavPanels() {
779 var basePath = getBaseUri(location.pathname);
780 var section = basePath.substring(1,basePath.indexOf("/",1));
781 writeCookie("height", resizePackagesNav.css("height"), section, null);
782}
783
784
785
786function restoreHeight(packageHeight) {
787 $("#resize-packages-nav").height(packageHeight);
788 $("#packages-nav").height(packageHeight);
789 // var classesHeight = navHeight - packageHeight;
790 // $("#classes-nav").css({height:classesHeight});
791 // $("#classes-nav .jspContainer").css({height:classesHeight});
792}
793
794
795
796/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
797
798
799
800
801
802/** Scroll the jScrollPane to make the currently selected item visible
803 This is called when the page finished loading. */
804function scrollIntoView(nav) {
805 var $nav = $("#"+nav);
806 var element = $nav.jScrollPane({/* ...settings... */});
807 var api = element.data('jsp');
808
809 if ($nav.is(':visible')) {
810 var $selected = $(".selected", $nav);
811 if ($selected.length == 0) {
812 // If no selected item found, exit
813 return;
814 }
815 // get the selected item's offset from its container nav by measuring the item's offset
816 // relative to the document then subtract the container nav's offset relative to the document
817 var selectedOffset = $selected.offset().top - $nav.offset().top;
818 if (selectedOffset > $nav.height() * .8) { // multiply nav height by .8 so we move up the item
819 // if it's more than 80% down the nav
820 // scroll the item up by an amount equal to 80% the container nav's height
821 api.scrollTo(0, selectedOffset - ($nav.height() * .8), false);
822 }
823 }
824}
825
826
827
828
829
830
831/* Show popup dialogs */
832function showDialog(id) {
833 $dialog = $("#"+id);
834 $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>');
835 $dialog.wrapInner('<div/>');
836 $dialog.removeClass("hide");
837}
838
839
840
841
842
843/* ######### COOKIES! ########## */
844
845function readCookie(cookie) {
846 var myCookie = cookie_namespace+"_"+cookie+"=";
847 if (document.cookie) {
848 var index = document.cookie.indexOf(myCookie);
849 if (index != -1) {
850 var valStart = index + myCookie.length;
851 var valEnd = document.cookie.indexOf(";", valStart);
852 if (valEnd == -1) {
853 valEnd = document.cookie.length;
854 }
855 var val = document.cookie.substring(valStart, valEnd);
856 return val;
857 }
858 }
859 return 0;
860}
861
862function writeCookie(cookie, val, section, expiration) {
863 if (val==undefined) return;
864 section = section == null ? "_" : "_"+section+"_";
865 if (expiration == null) {
866 var date = new Date();
867 date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
868 expiration = date.toGMTString();
869 }
870 var cookieValue = cookie_namespace + section + cookie + "=" + val
871 + "; expires=" + expiration+"; path=/";
872 document.cookie = cookieValue;
873}
874
875/* ######### END COOKIES! ########## */
876
877
878
879
880
Dirk Dougherty08032402014-02-15 10:14:35 -0800881/*
882 * Displays sticky nav bar on pages when dac header scrolls out of view
883 */
Scott Main20cf2a92014-04-02 21:57:20 -0700884var stickyTop;
Dirk Dougherty08032402014-02-15 10:14:35 -0800885(function() {
886 $(document).ready(function() {
887
888 // Sticky nav position
Scott Main20cf2a92014-04-02 21:57:20 -0700889 stickyTop = $('#header-wrapper').outerHeight() - $('#sticky-header').outerHeight();
Dirk Dougherty08032402014-02-15 10:14:35 -0800890 var sticky = false;
891 var hiding = false;
892 var $stickyEl = $('#sticky-header');
893 var $menuEl = $('.menu-container');
Dirk Dougherty08032402014-02-15 10:14:35 -0800894
Scott Main20cf2a92014-04-02 21:57:20 -0700895 var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
Dirk Dougherty08032402014-02-15 10:14:35 -0800896
Scott Main20cf2a92014-04-02 21:57:20 -0700897 $(window).scroll(function() {
898 // Exit if there's no sidenav
899 if ($('#side-nav').length == 0) return;
900 // Exit if the mouse target is a DIV, because that means the event is coming
901 // from a scrollable div and so there's no need to make adjustments to our layout
902 if (event.target.nodeName == "DIV") {
903 return;
904 }
905
906
907 var top = $(window).scrollTop();
908 // we set the navbar fixed when the scroll position is beyond the height of the site header...
909 var shouldBeSticky = top >= stickyTop;
910 // ... except if the document content is shorter than the sidenav height.
911 // (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
912 if ($("#doc-col").height() < $("#side-nav").height()) {
913 shouldBeSticky = false;
914 }
915
916 // Don't continue if the header is sufficently far away
917 // (to avoid intensive resizing that slows scrolling)
918 if (sticky && shouldBeSticky) {
919 return;
920 }
921
922 // Account for horizontal scroll
923 var scrollLeft = $(window).scrollLeft();
924 // When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
925 if (navBarIsFixed && (scrollLeft != prevScrollLeft)) {
926 updateSideNavPosition();
927 prevScrollLeft = scrollLeft;
928 }
929
930 // If sticky header visible and position is now near top, hide sticky
931 if (sticky && !shouldBeSticky) {
Dirk Dougherty08032402014-02-15 10:14:35 -0800932 sticky = false;
933 hiding = true;
Scott Main20cf2a92014-04-02 21:57:20 -0700934 // make the sidenav static again
935 $('#devdoc-nav')
936 .removeClass('fixed')
937 .css({'width':'auto','margin':''})
938 .prependTo('#side-nav');
939 // delay hide the sticky
940 $menuEl.removeClass('sticky-menu');
941 $stickyEl.fadeOut(250);
942 hiding = false;
943
944 // update the sidenaav position for side scrolling
945 updateSideNavPosition();
946 } else if (!sticky && shouldBeSticky) {
Dirk Dougherty08032402014-02-15 10:14:35 -0800947 sticky = true;
Scott Main20cf2a92014-04-02 21:57:20 -0700948 $stickyEl.fadeIn(10);
Dirk Dougherty08032402014-02-15 10:14:35 -0800949 $menuEl.addClass('sticky-menu');
950
Scott Main20cf2a92014-04-02 21:57:20 -0700951 // make the sidenav fixed
952 var width = $('#devdoc-nav').width();
953 $('#devdoc-nav')
954 .addClass('fixed')
955 .css({'width':width+'px'})
956 .prependTo('#body-content');
957
958 // update the sidenaav position for side scrolling
959 updateSideNavPosition();
960
Dirk Dougherty08032402014-02-15 10:14:35 -0800961 } else if (hiding && top < 15) {
962 $menuEl.removeClass('sticky-menu');
963 $stickyEl.hide();
964 hiding = false;
965 }
966
Scott Main20cf2a92014-04-02 21:57:20 -0700967 resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
Dirk Dougherty08032402014-02-15 10:14:35 -0800968 });
969
970 // Stack hover states
971 $('.section-card-menu').each(function(index, el) {
972 var height = $(el).height();
973 $(el).css({height:height+'px', position:'relative'});
974 var $cardInfo = $(el).find('.card-info');
975
976 $cardInfo.css({position: 'absolute', bottom:'0px', left:'0px', right:'0px', overflow:'visible'});
977 });
978
Scott Main20cf2a92014-04-02 21:57:20 -0700979 resizeNav(); // must resize once loading is finished
Dirk Dougherty08032402014-02-15 10:14:35 -0800980 });
981
982})();
Dirk Dougherty541b4942014-02-14 18:31:53 -0800983
984
985
986
987
988
989
990
991
992
993
994
995
996
997/* MISC LIBRARY FUNCTIONS */
998
999
1000
1001
1002
1003function toggle(obj, slide) {
1004 var ul = $("ul:first", obj);
1005 var li = ul.parent();
1006 if (li.hasClass("closed")) {
1007 if (slide) {
1008 ul.slideDown("fast");
1009 } else {
1010 ul.show();
1011 }
1012 li.removeClass("closed");
1013 li.addClass("open");
1014 $(".toggle-img", li).attr("title", "hide pages");
1015 } else {
1016 ul.slideUp("fast");
1017 li.removeClass("open");
1018 li.addClass("closed");
1019 $(".toggle-img", li).attr("title", "show pages");
1020 }
1021}
1022
1023
1024function buildToggleLists() {
1025 $(".toggle-list").each(
1026 function(i) {
1027 $("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
1028 $(this).addClass("closed");
1029 });
1030}
1031
1032
1033
1034function hideNestedItems(list, toggle) {
1035 $list = $(list);
1036 // hide nested lists
1037 if($list.hasClass('showing')) {
1038 $("li ol", $list).hide('fast');
1039 $list.removeClass('showing');
1040 // show nested lists
1041 } else {
1042 $("li ol", $list).show('fast');
1043 $list.addClass('showing');
1044 }
1045 $(".more,.less",$(toggle)).toggle();
1046}
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075/* REFERENCE NAV SWAP */
1076
1077
1078function getNavPref() {
1079 var v = readCookie('reference_nav');
1080 if (v != NAV_PREF_TREE) {
1081 v = NAV_PREF_PANELS;
1082 }
1083 return v;
1084}
1085
1086function chooseDefaultNav() {
1087 nav_pref = getNavPref();
1088 if (nav_pref == NAV_PREF_TREE) {
1089 $("#nav-panels").toggle();
1090 $("#panel-link").toggle();
1091 $("#nav-tree").toggle();
1092 $("#tree-link").toggle();
1093 }
1094}
1095
1096function swapNav() {
1097 if (nav_pref == NAV_PREF_TREE) {
1098 nav_pref = NAV_PREF_PANELS;
1099 } else {
1100 nav_pref = NAV_PREF_TREE;
1101 init_default_navtree(toRoot);
1102 }
1103 var date = new Date();
1104 date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
1105 writeCookie("nav", nav_pref, "reference", date.toGMTString());
1106
1107 $("#nav-panels").toggle();
1108 $("#panel-link").toggle();
1109 $("#nav-tree").toggle();
1110 $("#tree-link").toggle();
1111
1112 resizeNav();
1113
1114 // Gross nasty hack to make tree view show up upon first swap by setting height manually
1115 $("#nav-tree .jspContainer:visible")
1116 .css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
1117 // Another nasty hack to make the scrollbar appear now that we have height
1118 resizeNav();
1119
1120 if ($("#nav-tree").is(':visible')) {
1121 scrollIntoView("nav-tree");
1122 } else {
1123 scrollIntoView("packages-nav");
1124 scrollIntoView("classes-nav");
1125 }
1126}
1127
1128
1129
1130/* ############################################ */
1131/* ########## LOCALIZATION ############ */
1132/* ############################################ */
1133
1134function getBaseUri(uri) {
1135 var intlUrl = (uri.substring(0,6) == "/intl/");
1136 if (intlUrl) {
1137 base = uri.substring(uri.indexOf('intl/')+5,uri.length);
1138 base = base.substring(base.indexOf('/')+1, base.length);
1139 //alert("intl, returning base url: /" + base);
1140 return ("/" + base);
1141 } else {
1142 //alert("not intl, returning uri as found.");
1143 return uri;
1144 }
1145}
1146
1147function requestAppendHL(uri) {
1148//append "?hl=<lang> to an outgoing request (such as to blog)
1149 var lang = getLangPref();
1150 if (lang) {
1151 var q = 'hl=' + lang;
1152 uri += '?' + q;
1153 window.location = uri;
1154 return false;
1155 } else {
1156 return true;
1157 }
1158}
1159
1160
1161function changeNavLang(lang) {
1162 var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
1163 $links.each(function(i){ // for each link with a translation
1164 var $link = $(this);
1165 if (lang != "en") { // No need to worry about English, because a language change invokes new request
1166 // put the desired language from the attribute as the text
1167 $link.text($link.attr(lang+"-lang"))
1168 }
1169 });
1170}
1171
1172function changeLangPref(lang, submit) {
1173 var date = new Date();
1174 expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000)));
1175 // keep this for 50 years
1176 //alert("expires: " + expires)
1177 writeCookie("pref_lang", lang, null, expires);
1178
1179 // ####### TODO: Remove this condition once we're stable on devsite #######
1180 // This condition is only needed if we still need to support legacy GAE server
1181 if (devsite) {
1182 // Switch language when on Devsite server
1183 if (submit) {
1184 $("#setlang").submit();
1185 }
1186 } else {
1187 // Switch language when on legacy GAE server
1188 if (submit) {
1189 window.location = getBaseUri(location.pathname);
1190 }
1191 }
1192}
1193
1194function loadLangPref() {
1195 var lang = readCookie("pref_lang");
1196 if (lang != 0) {
1197 $("#language").find("option[value='"+lang+"']").attr("selected",true);
1198 }
1199}
1200
1201function getLangPref() {
1202 var lang = $("#language").find(":selected").attr("value");
1203 if (!lang) {
1204 lang = readCookie("pref_lang");
1205 }
1206 return (lang != 0) ? lang : 'en';
1207}
1208
1209/* ########## END LOCALIZATION ############ */
1210
1211
1212
1213
1214
1215
1216/* Used to hide and reveal supplemental content, such as long code samples.
1217 See the companion CSS in android-developer-docs.css */
1218function toggleContent(obj) {
1219 var div = $(obj).closest(".toggle-content");
1220 var toggleMe = $(".toggle-content-toggleme:eq(0)",div);
1221 if (div.hasClass("closed")) { // if it's closed, open it
1222 toggleMe.slideDown();
1223 $(".toggle-content-text:eq(0)", obj).toggle();
1224 div.removeClass("closed").addClass("open");
1225 $(".toggle-content-img:eq(0)", div).attr("title", "hide").attr("src", toRoot
1226 + "assets/images/triangle-opened.png");
1227 } else { // if it's open, close it
1228 toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
1229 $(".toggle-content-text:eq(0)", obj).toggle();
1230 div.removeClass("open").addClass("closed");
1231 div.find(".toggle-content").removeClass("open").addClass("closed")
1232 .find(".toggle-content-toggleme").hide();
1233 $(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
1234 + "assets/images/triangle-closed.png");
1235 });
1236 }
1237 return false;
1238}
1239
1240
1241/* New version of expandable content */
1242function toggleExpandable(link,id) {
1243 if($(id).is(':visible')) {
1244 $(id).slideUp();
1245 $(link).removeClass('expanded');
1246 } else {
1247 $(id).slideDown();
1248 $(link).addClass('expanded');
1249 }
1250}
1251
1252function hideExpandable(ids) {
1253 $(ids).slideUp();
1254 $(ids).prev('h4').find('a.expandable').removeClass('expanded');
1255}
1256
1257
1258
1259
1260
1261/*
1262 * Slideshow 1.0
1263 * Used on /index.html and /develop/index.html for carousel
1264 *
1265 * Sample usage:
1266 * HTML -
1267 * <div class="slideshow-container">
1268 * <a href="" class="slideshow-prev">Prev</a>
1269 * <a href="" class="slideshow-next">Next</a>
1270 * <ul>
1271 * <li class="item"><img src="images/marquee1.jpg"></li>
1272 * <li class="item"><img src="images/marquee2.jpg"></li>
1273 * <li class="item"><img src="images/marquee3.jpg"></li>
1274 * <li class="item"><img src="images/marquee4.jpg"></li>
1275 * </ul>
1276 * </div>
1277 *
1278 * <script type="text/javascript">
1279 * $('.slideshow-container').dacSlideshow({
1280 * auto: true,
1281 * btnPrev: '.slideshow-prev',
1282 * btnNext: '.slideshow-next'
1283 * });
1284 * </script>
1285 *
1286 * Options:
1287 * btnPrev: optional identifier for previous button
1288 * btnNext: optional identifier for next button
1289 * btnPause: optional identifier for pause button
1290 * auto: whether or not to auto-proceed
1291 * speed: animation speed
1292 * autoTime: time between auto-rotation
1293 * easing: easing function for transition
1294 * start: item to select by default
1295 * scroll: direction to scroll in
1296 * pagination: whether or not to include dotted pagination
1297 *
1298 */
1299
1300 (function($) {
1301 $.fn.dacSlideshow = function(o) {
1302
1303 //Options - see above
1304 o = $.extend({
1305 btnPrev: null,
1306 btnNext: null,
1307 btnPause: null,
1308 auto: true,
1309 speed: 500,
1310 autoTime: 12000,
1311 easing: null,
1312 start: 0,
1313 scroll: 1,
1314 pagination: true
1315
1316 }, o || {});
1317
1318 //Set up a carousel for each
1319 return this.each(function() {
1320
1321 var running = false;
1322 var animCss = o.vertical ? "top" : "left";
1323 var sizeCss = o.vertical ? "height" : "width";
1324 var div = $(this);
1325 var ul = $("ul", div);
1326 var tLi = $("li", ul);
1327 var tl = tLi.size();
1328 var timer = null;
1329
1330 var li = $("li", ul);
1331 var itemLength = li.size();
1332 var curr = o.start;
1333
1334 li.css({float: o.vertical ? "none" : "left"});
1335 ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
1336 div.css({position: "relative", "z-index": "2", left: "0px"});
1337
1338 var liSize = o.vertical ? height(li) : width(li);
1339 var ulSize = liSize * itemLength;
1340 var divSize = liSize;
1341
1342 li.css({width: li.width(), height: li.height()});
1343 ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
1344
1345 div.css(sizeCss, divSize+"px");
1346
1347 //Pagination
1348 if (o.pagination) {
1349 var pagination = $("<div class='pagination'></div>");
1350 var pag_ul = $("<ul></ul>");
1351 if (tl > 1) {
1352 for (var i=0;i<tl;i++) {
1353 var li = $("<li>"+i+"</li>");
1354 pag_ul.append(li);
1355 if (i==o.start) li.addClass('active');
1356 li.click(function() {
1357 go(parseInt($(this).text()));
1358 })
1359 }
1360 pagination.append(pag_ul);
1361 div.append(pagination);
1362 }
1363 }
1364
1365 //Previous button
1366 if(o.btnPrev)
1367 $(o.btnPrev).click(function(e) {
1368 e.preventDefault();
1369 return go(curr-o.scroll);
1370 });
1371
1372 //Next button
1373 if(o.btnNext)
1374 $(o.btnNext).click(function(e) {
1375 e.preventDefault();
1376 return go(curr+o.scroll);
1377 });
1378
1379 //Pause button
1380 if(o.btnPause)
1381 $(o.btnPause).click(function(e) {
1382 e.preventDefault();
1383 if ($(this).hasClass('paused')) {
1384 startRotateTimer();
1385 } else {
1386 pauseRotateTimer();
1387 }
1388 });
1389
1390 //Auto rotation
1391 if(o.auto) startRotateTimer();
1392
1393 function startRotateTimer() {
1394 clearInterval(timer);
1395 timer = setInterval(function() {
1396 if (curr == tl-1) {
1397 go(0);
1398 } else {
1399 go(curr+o.scroll);
1400 }
1401 }, o.autoTime);
1402 $(o.btnPause).removeClass('paused');
1403 }
1404
1405 function pauseRotateTimer() {
1406 clearInterval(timer);
1407 $(o.btnPause).addClass('paused');
1408 }
1409
1410 //Go to an item
1411 function go(to) {
1412 if(!running) {
1413
1414 if(to<0) {
1415 to = itemLength-1;
1416 } else if (to>itemLength-1) {
1417 to = 0;
1418 }
1419 curr = to;
1420
1421 running = true;
1422
1423 ul.animate(
1424 animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
1425 function() {
1426 running = false;
1427 }
1428 );
1429
1430 $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
1431 $( (curr-o.scroll<0 && o.btnPrev)
1432 ||
1433 (curr+o.scroll > itemLength && o.btnNext)
1434 ||
1435 []
1436 ).addClass("disabled");
1437
1438
1439 var nav_items = $('li', pagination);
1440 nav_items.removeClass('active');
1441 nav_items.eq(to).addClass('active');
1442
1443
1444 }
1445 if(o.auto) startRotateTimer();
1446 return false;
1447 };
1448 });
1449 };
1450
1451 function css(el, prop) {
1452 return parseInt($.css(el[0], prop)) || 0;
1453 };
1454 function width(el) {
1455 return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
1456 };
1457 function height(el) {
1458 return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
1459 };
1460
1461 })(jQuery);
1462
1463
1464/*
1465 * dacSlideshow 1.0
1466 * Used on develop/index.html for side-sliding tabs
1467 *
1468 * Sample usage:
1469 * HTML -
1470 * <div class="slideshow-container">
1471 * <a href="" class="slideshow-prev">Prev</a>
1472 * <a href="" class="slideshow-next">Next</a>
1473 * <ul>
1474 * <li class="item"><img src="images/marquee1.jpg"></li>
1475 * <li class="item"><img src="images/marquee2.jpg"></li>
1476 * <li class="item"><img src="images/marquee3.jpg"></li>
1477 * <li class="item"><img src="images/marquee4.jpg"></li>
1478 * </ul>
1479 * </div>
1480 *
1481 * <script type="text/javascript">
1482 * $('.slideshow-container').dacSlideshow({
1483 * auto: true,
1484 * btnPrev: '.slideshow-prev',
1485 * btnNext: '.slideshow-next'
1486 * });
1487 * </script>
1488 *
1489 * Options:
1490 * btnPrev: optional identifier for previous button
1491 * btnNext: optional identifier for next button
1492 * auto: whether or not to auto-proceed
1493 * speed: animation speed
1494 * autoTime: time between auto-rotation
1495 * easing: easing function for transition
1496 * start: item to select by default
1497 * scroll: direction to scroll in
1498 * pagination: whether or not to include dotted pagination
1499 *
1500 */
1501 (function($) {
1502 $.fn.dacTabbedList = function(o) {
1503
1504 //Options - see above
1505 o = $.extend({
1506 speed : 250,
1507 easing: null,
1508 nav_id: null,
1509 frame_id: null
1510 }, o || {});
1511
1512 //Set up a carousel for each
1513 return this.each(function() {
1514
1515 var curr = 0;
1516 var running = false;
1517 var animCss = "margin-left";
1518 var sizeCss = "width";
1519 var div = $(this);
1520
1521 var nav = $(o.nav_id, div);
1522 var nav_li = $("li", nav);
1523 var nav_size = nav_li.size();
1524 var frame = div.find(o.frame_id);
1525 var content_width = $(frame).find('ul').width();
1526 //Buttons
1527 $(nav_li).click(function(e) {
1528 go($(nav_li).index($(this)));
1529 })
1530
1531 //Go to an item
1532 function go(to) {
1533 if(!running) {
1534 curr = to;
1535 running = true;
1536
1537 frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
1538 function() {
1539 running = false;
1540 }
1541 );
1542
1543
1544 nav_li.removeClass('active');
1545 nav_li.eq(to).addClass('active');
1546
1547
1548 }
1549 return false;
1550 };
1551 });
1552 };
1553
1554 function css(el, prop) {
1555 return parseInt($.css(el[0], prop)) || 0;
1556 };
1557 function width(el) {
1558 return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
1559 };
1560 function height(el) {
1561 return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
1562 };
1563
1564 })(jQuery);
1565
1566
1567
1568
1569
1570/* ######################################################## */
1571/* ################ SEARCH SUGGESTIONS ################## */
1572/* ######################################################## */
1573
1574
1575
1576var gSelectedIndex = -1; // the index position of currently highlighted suggestion
1577var gSelectedColumn = -1; // which column of suggestion lists is currently focused
1578
1579var gMatches = new Array();
1580var gLastText = "";
1581var gInitialized = false;
1582var ROW_COUNT_FRAMEWORK = 20; // max number of results in list
1583var gListLength = 0;
1584
1585
1586var gGoogleMatches = new Array();
1587var ROW_COUNT_GOOGLE = 15; // max number of results in list
1588var gGoogleListLength = 0;
1589
1590var gDocsMatches = new Array();
1591var ROW_COUNT_DOCS = 100; // max number of results in list
1592var gDocsListLength = 0;
1593
1594function onSuggestionClick(link) {
1595 // When user clicks a suggested document, track it
1596 _gaq.push(['_trackEvent', 'Suggestion Click', 'clicked: ' + $(link).text(),
1597 'from: ' + $("#search_autocomplete").val()]);
1598}
1599
1600function set_item_selected($li, selected)
1601{
1602 if (selected) {
1603 $li.attr('class','jd-autocomplete jd-selected');
1604 } else {
1605 $li.attr('class','jd-autocomplete');
1606 }
1607}
1608
1609function set_item_values(toroot, $li, match)
1610{
1611 var $link = $('a',$li);
1612 $link.html(match.__hilabel || match.label);
1613 $link.attr('href',toroot + match.link);
1614}
1615
1616function set_item_values_jd(toroot, $li, match)
1617{
1618 var $link = $('a',$li);
1619 $link.html(match.title);
1620 $link.attr('href',toroot + match.url);
1621}
1622
1623function new_suggestion($list) {
1624 var $li = $("<li class='jd-autocomplete'></li>");
1625 $list.append($li);
1626
1627 $li.mousedown(function() {
1628 window.location = this.firstChild.getAttribute("href");
1629 });
1630 $li.mouseover(function() {
1631 $('.search_filtered_wrapper li').removeClass('jd-selected');
1632 $(this).addClass('jd-selected');
1633 gSelectedColumn = $(".search_filtered:visible").index($(this).closest('.search_filtered'));
1634 gSelectedIndex = $("li", $(".search_filtered:visible")[gSelectedColumn]).index(this);
1635 });
1636 $li.append("<a onclick='onSuggestionClick(this)'></a>");
1637 $li.attr('class','show-item');
1638 return $li;
1639}
1640
1641function sync_selection_table(toroot)
1642{
1643 var $li; //list item jquery object
1644 var i; //list item iterator
1645
1646 // if there are NO results at all, hide all columns
1647 if (!(gMatches.length > 0) && !(gGoogleMatches.length > 0) && !(gDocsMatches.length > 0)) {
1648 $('.suggest-card').hide(300);
1649 return;
1650 }
1651
1652 // if there are api results
1653 if ((gMatches.length > 0) || (gGoogleMatches.length > 0)) {
1654 // reveal suggestion list
1655 $('.suggest-card.dummy').show();
1656 $('.suggest-card.reference').show();
1657 var listIndex = 0; // list index position
1658
1659 // reset the lists
1660 $(".search_filtered_wrapper.reference li").remove();
1661
1662 // ########### ANDROID RESULTS #############
1663 if (gMatches.length > 0) {
1664
1665 // determine android results to show
1666 gListLength = gMatches.length < ROW_COUNT_FRAMEWORK ?
1667 gMatches.length : ROW_COUNT_FRAMEWORK;
1668 for (i=0; i<gListLength; i++) {
1669 var $li = new_suggestion($(".suggest-card.reference ul"));
1670 set_item_values(toroot, $li, gMatches[i]);
1671 set_item_selected($li, i == gSelectedIndex);
1672 }
1673 }
1674
1675 // ########### GOOGLE RESULTS #############
1676 if (gGoogleMatches.length > 0) {
1677 // show header for list
1678 $(".suggest-card.reference ul").append("<li class='header'>in Google Services:</li>");
1679
1680 // determine google results to show
1681 gGoogleListLength = gGoogleMatches.length < ROW_COUNT_GOOGLE ? gGoogleMatches.length : ROW_COUNT_GOOGLE;
1682 for (i=0; i<gGoogleListLength; i++) {
1683 var $li = new_suggestion($(".suggest-card.reference ul"));
1684 set_item_values(toroot, $li, gGoogleMatches[i]);
1685 set_item_selected($li, i == gSelectedIndex);
1686 }
1687 }
1688 } else {
1689 $('.suggest-card.reference').hide();
1690 $('.suggest-card.dummy').hide();
1691 }
1692
1693 // ########### JD DOC RESULTS #############
1694 if (gDocsMatches.length > 0) {
1695 // reset the lists
1696 $(".search_filtered_wrapper.docs li").remove();
1697
1698 // determine google results to show
1699 // NOTE: The order of the conditions below for the sugg.type MUST BE SPECIFIC:
1700 // The order must match the reverse order that each section appears as a card in
1701 // the suggestion UI... this may be only for the "develop" grouped items though.
1702 gDocsListLength = gDocsMatches.length < ROW_COUNT_DOCS ? gDocsMatches.length : ROW_COUNT_DOCS;
1703 for (i=0; i<gDocsListLength; i++) {
1704 var sugg = gDocsMatches[i];
1705 var $li;
1706 if (sugg.type == "design") {
1707 $li = new_suggestion($(".suggest-card.design ul"));
1708 } else
1709 if (sugg.type == "distribute") {
1710 $li = new_suggestion($(".suggest-card.distribute ul"));
1711 } else
1712 if (sugg.type == "samples") {
1713 $li = new_suggestion($(".suggest-card.develop .child-card.samples"));
1714 } else
1715 if (sugg.type == "training") {
1716 $li = new_suggestion($(".suggest-card.develop .child-card.training"));
1717 } else
1718 if (sugg.type == "about"||"guide"||"tools"||"google") {
1719 $li = new_suggestion($(".suggest-card.develop .child-card.guides"));
1720 } else {
1721 continue;
1722 }
1723
1724 set_item_values_jd(toroot, $li, sugg);
1725 set_item_selected($li, i == gSelectedIndex);
1726 }
1727
1728 // add heading and show or hide card
1729 if ($(".suggest-card.design li").length > 0) {
1730 $(".suggest-card.design ul").prepend("<li class='header'>Design:</li>");
1731 $(".suggest-card.design").show(300);
1732 } else {
1733 $('.suggest-card.design').hide(300);
1734 }
1735 if ($(".suggest-card.distribute li").length > 0) {
1736 $(".suggest-card.distribute ul").prepend("<li class='header'>Distribute:</li>");
1737 $(".suggest-card.distribute").show(300);
1738 } else {
1739 $('.suggest-card.distribute').hide(300);
1740 }
1741 if ($(".child-card.guides li").length > 0) {
1742 $(".child-card.guides").prepend("<li class='header'>Guides:</li>");
1743 $(".child-card.guides li").appendTo(".suggest-card.develop ul");
1744 }
1745 if ($(".child-card.training li").length > 0) {
1746 $(".child-card.training").prepend("<li class='header'>Training:</li>");
1747 $(".child-card.training li").appendTo(".suggest-card.develop ul");
1748 }
1749 if ($(".child-card.samples li").length > 0) {
1750 $(".child-card.samples").prepend("<li class='header'>Samples:</li>");
1751 $(".child-card.samples li").appendTo(".suggest-card.develop ul");
1752 }
1753
1754 if ($(".suggest-card.develop li").length > 0) {
1755 $(".suggest-card.develop").show(300);
1756 } else {
1757 $('.suggest-card.develop').hide(300);
1758 }
1759
1760 } else {
1761 $('.search_filtered_wrapper.docs .suggest-card:not(.dummy)').hide(300);
1762 }
1763}
1764
1765/** Called by the search input's onkeydown and onkeyup events.
1766 * Handles navigation with keyboard arrows, Enter key to invoke search,
1767 * otherwise invokes search suggestions on key-up event.
1768 * @param e The JS event
1769 * @param kd True if the event is key-down
1770 * @param toroot A string for the site's root path
1771 * @returns True if the event should bubble up
1772 */
1773function search_changed(e, kd, toroot)
1774{
1775 var currentLang = getLangPref();
1776 var search = document.getElementById("search_autocomplete");
1777 var text = search.value.replace(/(^ +)|( +$)/g, '');
1778 // get the ul hosting the currently selected item
1779 gSelectedColumn = gSelectedColumn >= 0 ? gSelectedColumn : 0;
1780 var $columns = $(".search_filtered_wrapper").find(".search_filtered:visible");
1781 var $selectedUl = $columns[gSelectedColumn];
1782
1783 // show/hide the close button
1784 if (text != '') {
1785 $(".search .close").removeClass("hide");
1786 } else {
1787 $(".search .close").addClass("hide");
1788 }
1789 // 27 = esc
1790 if (e.keyCode == 27) {
1791 // close all search results
1792 if (kd) $('.search .close').trigger('click');
1793 return true;
1794 }
1795 // 13 = enter
1796 else if (e.keyCode == 13) {
1797 if (gSelectedIndex < 0) {
1798 $('.suggest-card').hide();
1799 if ($("#searchResults").is(":hidden") && (search.value != "")) {
1800 // if results aren't showing (and text not empty), return true to allow search to execute
Scott Main4868e9b2014-04-14 19:00:12 -07001801 $('body,html').animate({scrollTop:0}, '500', 'swing');
Dirk Dougherty541b4942014-02-14 18:31:53 -08001802 return true;
1803 } else {
1804 // otherwise, results are already showing, so allow ajax to auto refresh the results
1805 // and ignore this Enter press to avoid the reload.
1806 return false;
1807 }
1808 } else if (kd && gSelectedIndex >= 0) {
1809 // click the link corresponding to selected item
1810 $("a",$("li",$selectedUl)[gSelectedIndex]).get()[0].click();
1811 return false;
1812 }
1813 }
1814 // Stop here if Google results are showing
1815 else if ($("#searchResults").is(":visible")) {
1816 return true;
1817 }
1818 // 38 UP ARROW
1819 else if (kd && (e.keyCode == 38)) {
1820 // if the next item is a header, skip it
1821 if ($($("li", $selectedUl)[gSelectedIndex-1]).hasClass("header")) {
1822 gSelectedIndex--;
1823 }
1824 if (gSelectedIndex >= 0) {
1825 $('li', $selectedUl).removeClass('jd-selected');
1826 gSelectedIndex--;
1827 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1828 // If user reaches top, reset selected column
1829 if (gSelectedIndex < 0) {
1830 gSelectedColumn = -1;
1831 }
1832 }
1833 return false;
1834 }
1835 // 40 DOWN ARROW
1836 else if (kd && (e.keyCode == 40)) {
1837 // if the next item is a header, skip it
1838 if ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header")) {
1839 gSelectedIndex++;
1840 }
1841 if ((gSelectedIndex < $("li", $selectedUl).length-1) ||
1842 ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header"))) {
1843 $('li', $selectedUl).removeClass('jd-selected');
1844 gSelectedIndex++;
1845 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1846 }
1847 return false;
1848 }
1849 // Consider left/right arrow navigation
1850 // NOTE: Order of suggest columns are reverse order (index position 0 is on right)
1851 else if (kd && $columns.length > 1 && gSelectedColumn >= 0) {
1852 // 37 LEFT ARROW
1853 // go left only if current column is not left-most column (last column)
1854 if (e.keyCode == 37 && gSelectedColumn < $columns.length - 1) {
1855 $('li', $selectedUl).removeClass('jd-selected');
1856 gSelectedColumn++;
1857 $selectedUl = $columns[gSelectedColumn];
1858 // keep or reset the selected item to last item as appropriate
1859 gSelectedIndex = gSelectedIndex >
1860 $("li", $selectedUl).length-1 ?
1861 $("li", $selectedUl).length-1 : gSelectedIndex;
1862 // if the corresponding item is a header, move down
1863 if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
1864 gSelectedIndex++;
1865 }
1866 // set item selected
1867 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1868 return false;
1869 }
1870 // 39 RIGHT ARROW
1871 // go right only if current column is not the right-most column (first column)
1872 else if (e.keyCode == 39 && gSelectedColumn > 0) {
1873 $('li', $selectedUl).removeClass('jd-selected');
1874 gSelectedColumn--;
1875 $selectedUl = $columns[gSelectedColumn];
1876 // keep or reset the selected item to last item as appropriate
1877 gSelectedIndex = gSelectedIndex >
1878 $("li", $selectedUl).length-1 ?
1879 $("li", $selectedUl).length-1 : gSelectedIndex;
1880 // if the corresponding item is a header, move down
1881 if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
1882 gSelectedIndex++;
1883 }
1884 // set item selected
1885 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1886 return false;
1887 }
1888 }
1889
1890 // if key-up event and not arrow down/up/left/right,
1891 // read the search query and add suggestions to gMatches
1892 else if (!kd && (e.keyCode != 40)
1893 && (e.keyCode != 38)
1894 && (e.keyCode != 37)
1895 && (e.keyCode != 39)) {
1896 gSelectedIndex = -1;
1897 gMatches = new Array();
1898 matchedCount = 0;
1899 gGoogleMatches = new Array();
1900 matchedCountGoogle = 0;
1901 gDocsMatches = new Array();
1902 matchedCountDocs = 0;
1903
1904 // Search for Android matches
1905 for (var i=0; i<DATA.length; i++) {
1906 var s = DATA[i];
1907 if (text.length != 0 &&
1908 s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
1909 gMatches[matchedCount] = s;
1910 matchedCount++;
1911 }
1912 }
1913 rank_autocomplete_api_results(text, gMatches);
1914 for (var i=0; i<gMatches.length; i++) {
1915 var s = gMatches[i];
1916 }
1917
1918
1919 // Search for Google matches
1920 for (var i=0; i<GOOGLE_DATA.length; i++) {
1921 var s = GOOGLE_DATA[i];
1922 if (text.length != 0 &&
1923 s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
1924 gGoogleMatches[matchedCountGoogle] = s;
1925 matchedCountGoogle++;
1926 }
1927 }
1928 rank_autocomplete_api_results(text, gGoogleMatches);
1929 for (var i=0; i<gGoogleMatches.length; i++) {
1930 var s = gGoogleMatches[i];
1931 }
1932
1933 highlight_autocomplete_result_labels(text);
1934
1935
1936
1937 // Search for matching JD docs
1938 if (text.length >= 3) {
1939 // Regex to match only the beginning of a word
1940 var textRegex = new RegExp("\\b" + text.toLowerCase(), "g");
1941
1942
1943 // Search for Training classes
1944 for (var i=0; i<TRAINING_RESOURCES.length; i++) {
1945 // current search comparison, with counters for tag and title,
1946 // used later to improve ranking
1947 var s = TRAINING_RESOURCES[i];
1948 s.matched_tag = 0;
1949 s.matched_title = 0;
1950 var matched = false;
1951
1952 // Check if query matches any tags; work backwards toward 1 to assist ranking
1953 for (var j = s.keywords.length - 1; j >= 0; j--) {
1954 // it matches a tag
1955 if (s.keywords[j].toLowerCase().match(textRegex)) {
1956 matched = true;
1957 s.matched_tag = j + 1; // add 1 to index position
1958 }
1959 }
1960 // Don't consider doc title for lessons (only for class landing pages),
1961 // unless the lesson has a tag that already matches
1962 if ((s.lang == currentLang) &&
1963 (!(s.type == "training" && s.url.indexOf("index.html") == -1) || matched)) {
1964 // it matches the doc title
1965 if (s.title.toLowerCase().match(textRegex)) {
1966 matched = true;
1967 s.matched_title = 1;
1968 }
1969 }
1970 if (matched) {
1971 gDocsMatches[matchedCountDocs] = s;
1972 matchedCountDocs++;
1973 }
1974 }
1975
1976
1977 // Search for API Guides
1978 for (var i=0; i<GUIDE_RESOURCES.length; i++) {
1979 // current search comparison, with counters for tag and title,
1980 // used later to improve ranking
1981 var s = GUIDE_RESOURCES[i];
1982 s.matched_tag = 0;
1983 s.matched_title = 0;
1984 var matched = false;
1985
1986 // Check if query matches any tags; work backwards toward 1 to assist ranking
1987 for (var j = s.keywords.length - 1; j >= 0; j--) {
1988 // it matches a tag
1989 if (s.keywords[j].toLowerCase().match(textRegex)) {
1990 matched = true;
1991 s.matched_tag = j + 1; // add 1 to index position
1992 }
1993 }
1994 // Check if query matches the doc title, but only for current language
1995 if (s.lang == currentLang) {
1996 // if query matches the doc title
1997 if (s.title.toLowerCase().match(textRegex)) {
1998 matched = true;
1999 s.matched_title = 1;
2000 }
2001 }
2002 if (matched) {
2003 gDocsMatches[matchedCountDocs] = s;
2004 matchedCountDocs++;
2005 }
2006 }
2007
2008
2009 // Search for Tools Guides
2010 for (var i=0; i<TOOLS_RESOURCES.length; i++) {
2011 // current search comparison, with counters for tag and title,
2012 // used later to improve ranking
2013 var s = TOOLS_RESOURCES[i];
2014 s.matched_tag = 0;
2015 s.matched_title = 0;
2016 var matched = false;
2017
2018 // Check if query matches any tags; work backwards toward 1 to assist ranking
2019 for (var j = s.keywords.length - 1; j >= 0; j--) {
2020 // it matches a tag
2021 if (s.keywords[j].toLowerCase().match(textRegex)) {
2022 matched = true;
2023 s.matched_tag = j + 1; // add 1 to index position
2024 }
2025 }
2026 // Check if query matches the doc title, but only for current language
2027 if (s.lang == currentLang) {
2028 // if query matches the doc title
2029 if (s.title.toLowerCase().match(textRegex)) {
2030 matched = true;
2031 s.matched_title = 1;
2032 }
2033 }
2034 if (matched) {
2035 gDocsMatches[matchedCountDocs] = s;
2036 matchedCountDocs++;
2037 }
2038 }
2039
2040
2041 // Search for About docs
2042 for (var i=0; i<ABOUT_RESOURCES.length; i++) {
2043 // current search comparison, with counters for tag and title,
2044 // used later to improve ranking
2045 var s = ABOUT_RESOURCES[i];
2046 s.matched_tag = 0;
2047 s.matched_title = 0;
2048 var matched = false;
2049
2050 // Check if query matches any tags; work backwards toward 1 to assist ranking
2051 for (var j = s.keywords.length - 1; j >= 0; j--) {
2052 // it matches a tag
2053 if (s.keywords[j].toLowerCase().match(textRegex)) {
2054 matched = true;
2055 s.matched_tag = j + 1; // add 1 to index position
2056 }
2057 }
2058 // Check if query matches the doc title, but only for current language
2059 if (s.lang == currentLang) {
2060 // if query matches the doc title
2061 if (s.title.toLowerCase().match(textRegex)) {
2062 matched = true;
2063 s.matched_title = 1;
2064 }
2065 }
2066 if (matched) {
2067 gDocsMatches[matchedCountDocs] = s;
2068 matchedCountDocs++;
2069 }
2070 }
2071
2072
2073 // Search for Design guides
2074 for (var i=0; i<DESIGN_RESOURCES.length; i++) {
2075 // current search comparison, with counters for tag and title,
2076 // used later to improve ranking
2077 var s = DESIGN_RESOURCES[i];
2078 s.matched_tag = 0;
2079 s.matched_title = 0;
2080 var matched = false;
2081
2082 // Check if query matches any tags; work backwards toward 1 to assist ranking
2083 for (var j = s.keywords.length - 1; j >= 0; j--) {
2084 // it matches a tag
2085 if (s.keywords[j].toLowerCase().match(textRegex)) {
2086 matched = true;
2087 s.matched_tag = j + 1; // add 1 to index position
2088 }
2089 }
2090 // Check if query matches the doc title, but only for current language
2091 if (s.lang == currentLang) {
2092 // if query matches the doc title
2093 if (s.title.toLowerCase().match(textRegex)) {
2094 matched = true;
2095 s.matched_title = 1;
2096 }
2097 }
2098 if (matched) {
2099 gDocsMatches[matchedCountDocs] = s;
2100 matchedCountDocs++;
2101 }
2102 }
2103
2104
2105 // Search for Distribute guides
2106 for (var i=0; i<DISTRIBUTE_RESOURCES.length; i++) {
2107 // current search comparison, with counters for tag and title,
2108 // used later to improve ranking
2109 var s = DISTRIBUTE_RESOURCES[i];
2110 s.matched_tag = 0;
2111 s.matched_title = 0;
2112 var matched = false;
2113
2114 // Check if query matches any tags; work backwards toward 1 to assist ranking
2115 for (var j = s.keywords.length - 1; j >= 0; j--) {
2116 // it matches a tag
2117 if (s.keywords[j].toLowerCase().match(textRegex)) {
2118 matched = true;
2119 s.matched_tag = j + 1; // add 1 to index position
2120 }
2121 }
2122 // Check if query matches the doc title, but only for current language
2123 if (s.lang == currentLang) {
2124 // if query matches the doc title
2125 if (s.title.toLowerCase().match(textRegex)) {
2126 matched = true;
2127 s.matched_title = 1;
2128 }
2129 }
2130 if (matched) {
2131 gDocsMatches[matchedCountDocs] = s;
2132 matchedCountDocs++;
2133 }
2134 }
2135
2136
2137 // Search for Google guides
2138 for (var i=0; i<GOOGLE_RESOURCES.length; i++) {
2139 // current search comparison, with counters for tag and title,
2140 // used later to improve ranking
2141 var s = GOOGLE_RESOURCES[i];
2142 s.matched_tag = 0;
2143 s.matched_title = 0;
2144 var matched = false;
2145
2146 // Check if query matches any tags; work backwards toward 1 to assist ranking
2147 for (var j = s.keywords.length - 1; j >= 0; j--) {
2148 // it matches a tag
2149 if (s.keywords[j].toLowerCase().match(textRegex)) {
2150 matched = true;
2151 s.matched_tag = j + 1; // add 1 to index position
2152 }
2153 }
2154 // Check if query matches the doc title, but only for current language
2155 if (s.lang == currentLang) {
2156 // if query matches the doc title
2157 if (s.title.toLowerCase().match(textRegex)) {
2158 matched = true;
2159 s.matched_title = 1;
2160 }
2161 }
2162 if (matched) {
2163 gDocsMatches[matchedCountDocs] = s;
2164 matchedCountDocs++;
2165 }
2166 }
2167
2168
2169 // Search for Samples
2170 for (var i=0; i<SAMPLES_RESOURCES.length; i++) {
2171 // current search comparison, with counters for tag and title,
2172 // used later to improve ranking
2173 var s = SAMPLES_RESOURCES[i];
2174 s.matched_tag = 0;
2175 s.matched_title = 0;
2176 var matched = false;
2177 // Check if query matches any tags; work backwards toward 1 to assist ranking
2178 for (var j = s.keywords.length - 1; j >= 0; j--) {
2179 // it matches a tag
2180 if (s.keywords[j].toLowerCase().match(textRegex)) {
2181 matched = true;
2182 s.matched_tag = j + 1; // add 1 to index position
2183 }
2184 }
2185 // Check if query matches the doc title, but only for current language
2186 if (s.lang == currentLang) {
2187 // if query matches the doc title.t
2188 if (s.title.toLowerCase().match(textRegex)) {
2189 matched = true;
2190 s.matched_title = 1;
2191 }
2192 }
2193 if (matched) {
2194 gDocsMatches[matchedCountDocs] = s;
2195 matchedCountDocs++;
2196 }
2197 }
2198
2199 // Rank/sort all the matched pages
2200 rank_autocomplete_doc_results(text, gDocsMatches);
2201 }
2202
2203 // draw the suggestions
2204 sync_selection_table(toroot);
2205 return true; // allow the event to bubble up to the search api
2206 }
2207}
2208
2209/* Order the jd doc result list based on match quality */
2210function rank_autocomplete_doc_results(query, matches) {
2211 query = query || '';
2212 if (!matches || !matches.length)
2213 return;
2214
2215 var _resultScoreFn = function(match) {
2216 var score = 1.0;
2217
2218 // if the query matched a tag
2219 if (match.matched_tag > 0) {
2220 // multiply score by factor relative to position in tags list (max of 3)
2221 score *= 3 / match.matched_tag;
2222
2223 // if it also matched the title
2224 if (match.matched_title > 0) {
2225 score *= 2;
2226 }
2227 } else if (match.matched_title > 0) {
2228 score *= 3;
2229 }
2230
2231 return score;
2232 };
2233
2234 for (var i=0; i<matches.length; i++) {
2235 matches[i].__resultScore = _resultScoreFn(matches[i]);
2236 }
2237
2238 matches.sort(function(a,b){
2239 var n = b.__resultScore - a.__resultScore;
2240 if (n == 0) // lexicographical sort if scores are the same
2241 n = (a.label < b.label) ? -1 : 1;
2242 return n;
2243 });
2244}
2245
2246/* Order the result list based on match quality */
2247function rank_autocomplete_api_results(query, matches) {
2248 query = query || '';
2249 if (!matches || !matches.length)
2250 return;
2251
2252 // helper function that gets the last occurence index of the given regex
2253 // in the given string, or -1 if not found
2254 var _lastSearch = function(s, re) {
2255 if (s == '')
2256 return -1;
2257 var l = -1;
2258 var tmp;
2259 while ((tmp = s.search(re)) >= 0) {
2260 if (l < 0) l = 0;
2261 l += tmp;
2262 s = s.substr(tmp + 1);
2263 }
2264 return l;
2265 };
2266
2267 // helper function that counts the occurrences of a given character in
2268 // a given string
2269 var _countChar = function(s, c) {
2270 var n = 0;
2271 for (var i=0; i<s.length; i++)
2272 if (s.charAt(i) == c) ++n;
2273 return n;
2274 };
2275
2276 var queryLower = query.toLowerCase();
2277 var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
2278 var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
2279 var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
2280
2281 var _resultScoreFn = function(result) {
2282 // scores are calculated based on exact and prefix matches,
2283 // and then number of path separators (dots) from the last
2284 // match (i.e. favoring classes and deep package names)
2285 var score = 1.0;
2286 var labelLower = result.label.toLowerCase();
2287 var t;
2288 t = _lastSearch(labelLower, partExactAlnumRE);
2289 if (t >= 0) {
2290 // exact part match
2291 var partsAfter = _countChar(labelLower.substr(t + 1), '.');
2292 score *= 200 / (partsAfter + 1);
2293 } else {
2294 t = _lastSearch(labelLower, partPrefixAlnumRE);
2295 if (t >= 0) {
2296 // part prefix match
2297 var partsAfter = _countChar(labelLower.substr(t + 1), '.');
2298 score *= 20 / (partsAfter + 1);
2299 }
2300 }
2301
2302 return score;
2303 };
2304
2305 for (var i=0; i<matches.length; i++) {
2306 // if the API is deprecated, default score is 0; otherwise, perform scoring
2307 if (matches[i].deprecated == "true") {
2308 matches[i].__resultScore = 0;
2309 } else {
2310 matches[i].__resultScore = _resultScoreFn(matches[i]);
2311 }
2312 }
2313
2314 matches.sort(function(a,b){
2315 var n = b.__resultScore - a.__resultScore;
2316 if (n == 0) // lexicographical sort if scores are the same
2317 n = (a.label < b.label) ? -1 : 1;
2318 return n;
2319 });
2320}
2321
2322/* Add emphasis to part of string that matches query */
2323function highlight_autocomplete_result_labels(query) {
2324 query = query || '';
2325 if ((!gMatches || !gMatches.length) && (!gGoogleMatches || !gGoogleMatches.length))
2326 return;
2327
2328 var queryLower = query.toLowerCase();
2329 var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
2330 var queryRE = new RegExp(
2331 '(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
2332 for (var i=0; i<gMatches.length; i++) {
2333 gMatches[i].__hilabel = gMatches[i].label.replace(
2334 queryRE, '<b>$1</b>');
2335 }
2336 for (var i=0; i<gGoogleMatches.length; i++) {
2337 gGoogleMatches[i].__hilabel = gGoogleMatches[i].label.replace(
2338 queryRE, '<b>$1</b>');
2339 }
2340}
2341
2342function search_focus_changed(obj, focused)
2343{
2344 if (!focused) {
2345 if(obj.value == ""){
2346 $(".search .close").addClass("hide");
2347 }
2348 $(".suggest-card").hide();
2349 }
2350}
2351
2352function submit_search() {
2353 var query = document.getElementById('search_autocomplete').value;
2354 location.hash = 'q=' + query;
2355 loadSearchResults();
2356 $("#searchResults").slideDown('slow');
2357 return false;
2358}
2359
2360
2361function hideResults() {
2362 $("#searchResults").slideUp();
2363 $(".search .close").addClass("hide");
2364 location.hash = '';
2365
2366 $("#search_autocomplete").val("").blur();
2367
2368 // reset the ajax search callback to nothing, so results don't appear unless ENTER
2369 searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
2370
2371 // forcefully regain key-up event control (previously jacked by search api)
2372 $("#search_autocomplete").keyup(function(event) {
2373 return search_changed(event, false, toRoot);
2374 });
2375
2376 return false;
2377}
2378
2379
2380
2381/* ########################################################## */
2382/* ################ CUSTOM SEARCH ENGINE ################## */
2383/* ########################################################## */
2384
2385var searchControl;
2386google.load('search', '1', {"callback" : function() {
2387 searchControl = new google.search.SearchControl();
2388 } });
2389
2390function loadSearchResults() {
2391 document.getElementById("search_autocomplete").style.color = "#000";
2392
2393 searchControl = new google.search.SearchControl();
2394
2395 // use our existing search form and use tabs when multiple searchers are used
2396 drawOptions = new google.search.DrawOptions();
2397 drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
2398 drawOptions.setInput(document.getElementById("search_autocomplete"));
2399
2400 // configure search result options
2401 searchOptions = new google.search.SearcherOptions();
2402 searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
2403
2404 // configure each of the searchers, for each tab
2405 devSiteSearcher = new google.search.WebSearch();
2406 devSiteSearcher.setUserDefinedLabel("All");
2407 devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
2408
2409 designSearcher = new google.search.WebSearch();
2410 designSearcher.setUserDefinedLabel("Design");
2411 designSearcher.setSiteRestriction("http://developer.android.com/design/");
2412
2413 trainingSearcher = new google.search.WebSearch();
2414 trainingSearcher.setUserDefinedLabel("Training");
2415 trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
2416
2417 guidesSearcher = new google.search.WebSearch();
2418 guidesSearcher.setUserDefinedLabel("Guides");
2419 guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
2420
2421 referenceSearcher = new google.search.WebSearch();
2422 referenceSearcher.setUserDefinedLabel("Reference");
2423 referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
2424
2425 googleSearcher = new google.search.WebSearch();
2426 googleSearcher.setUserDefinedLabel("Google Services");
2427 googleSearcher.setSiteRestriction("http://developer.android.com/google/");
2428
2429 blogSearcher = new google.search.WebSearch();
2430 blogSearcher.setUserDefinedLabel("Blog");
2431 blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
2432
2433 // add each searcher to the search control
2434 searchControl.addSearcher(devSiteSearcher, searchOptions);
2435 searchControl.addSearcher(designSearcher, searchOptions);
2436 searchControl.addSearcher(trainingSearcher, searchOptions);
2437 searchControl.addSearcher(guidesSearcher, searchOptions);
2438 searchControl.addSearcher(referenceSearcher, searchOptions);
2439 searchControl.addSearcher(googleSearcher, searchOptions);
2440 searchControl.addSearcher(blogSearcher, searchOptions);
2441
2442 // configure result options
2443 searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
2444 searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
2445 searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
2446 searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
2447
2448 // upon ajax search, refresh the url and search title
2449 searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
2450 updateResultTitle(query);
2451 var query = document.getElementById('search_autocomplete').value;
2452 location.hash = 'q=' + query;
2453 });
2454
2455 // once search results load, set up click listeners
2456 searchControl.setSearchCompleteCallback(this, function(control, searcher, query) {
2457 addResultClickListeners();
2458 });
2459
2460 // draw the search results box
2461 searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
2462
2463 // get query and execute the search
2464 searchControl.execute(decodeURI(getQuery(location.hash)));
2465
2466 document.getElementById("search_autocomplete").focus();
2467 addTabListeners();
2468}
2469// End of loadSearchResults
2470
2471
2472google.setOnLoadCallback(function(){
2473 if (location.hash.indexOf("q=") == -1) {
2474 // if there's no query in the url, don't search and make sure results are hidden
2475 $('#searchResults').hide();
2476 return;
2477 } else {
2478 // first time loading search results for this page
2479 $('#searchResults').slideDown('slow');
2480 $(".search .close").removeClass("hide");
2481 loadSearchResults();
2482 }
2483}, true);
2484
2485// when an event on the browser history occurs (back, forward, load) requery hash and do search
2486$(window).hashchange( function(){
Scott Main4868e9b2014-04-14 19:00:12 -07002487 // If the hash isn't a search query or there's an error in the query,
2488 // then adjust the scroll position to account for sticky header, then exit.
Dirk Dougherty541b4942014-02-14 18:31:53 -08002489 if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
2490 // If the results pane is open, close it.
2491 if (!$("#searchResults").is(":hidden")) {
2492 hideResults();
2493 }
Scott Main4868e9b2014-04-14 19:00:12 -07002494 // Adjust the scroll position to account for sticky header
2495 $(window).scrollTop($(window).scrollTop() - 60);
Dirk Dougherty541b4942014-02-14 18:31:53 -08002496 return;
2497 }
2498
2499 // Otherwise, we have a search to do
2500 var query = decodeURI(getQuery(location.hash));
2501 searchControl.execute(query);
2502 $('#searchResults').slideDown('slow');
2503 $("#search_autocomplete").focus();
2504 $(".search .close").removeClass("hide");
2505
2506 updateResultTitle(query);
2507});
2508
2509function updateResultTitle(query) {
2510 $("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
2511}
2512
2513// forcefully regain key-up event control (previously jacked by search api)
2514$("#search_autocomplete").keyup(function(event) {
2515 return search_changed(event, false, toRoot);
2516});
2517
2518// add event listeners to each tab so we can track the browser history
2519function addTabListeners() {
2520 var tabHeaders = $(".gsc-tabHeader");
2521 for (var i = 0; i < tabHeaders.length; i++) {
2522 $(tabHeaders[i]).attr("id",i).click(function() {
2523 /*
2524 // make a copy of the page numbers for the search left pane
2525 setTimeout(function() {
2526 // remove any residual page numbers
2527 $('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
2528 // move the page numbers to the left position; make a clone,
2529 // because the element is drawn to the DOM only once
2530 // and because we're going to remove it (previous line),
2531 // we need it to be available to move again as the user navigates
2532 $('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
2533 .clone().appendTo('#searchResults .gsc-tabsArea');
2534 }, 200);
2535 */
2536 });
2537 }
2538 setTimeout(function(){$(tabHeaders[0]).click()},200);
2539}
2540
2541// add analytics tracking events to each result link
2542function addResultClickListeners() {
2543 $("#searchResults a.gs-title").each(function(index, link) {
2544 // When user clicks enter for Google search results, track it
2545 $(link).click(function() {
2546 _gaq.push(['_trackEvent', 'Google Click', 'clicked: ' + $(this).text(),
2547 'from: ' + $("#search_autocomplete").val()]);
2548 });
2549 });
2550}
2551
2552
2553function getQuery(hash) {
2554 var queryParts = hash.split('=');
2555 return queryParts[1];
2556}
2557
2558/* returns the given string with all HTML brackets converted to entities
2559 TODO: move this to the site's JS library */
2560function escapeHTML(string) {
2561 return string.replace(/</g,"&lt;")
2562 .replace(/>/g,"&gt;");
2563}
2564
2565
2566
2567
2568
2569
2570
2571/* ######################################################## */
2572/* ################# JAVADOC REFERENCE ################### */
2573/* ######################################################## */
2574
2575/* Initialize some droiddoc stuff, but only if we're in the reference */
2576if (location.pathname.indexOf("/reference") == 0) {
2577 if(!(location.pathname.indexOf("/reference-gms/packages.html") == 0)
2578 && !(location.pathname.indexOf("/reference-gcm/packages.html") == 0)
2579 && !(location.pathname.indexOf("/reference/com/google") == 0)) {
2580 $(document).ready(function() {
2581 // init available apis based on user pref
2582 changeApiLevel();
2583 initSidenavHeightResize()
2584 });
2585 }
2586}
2587
2588var API_LEVEL_COOKIE = "api_level";
2589var minLevel = 1;
2590var maxLevel = 1;
2591
2592/******* SIDENAV DIMENSIONS ************/
2593
2594 function initSidenavHeightResize() {
2595 // Change the drag bar size to nicely fit the scrollbar positions
2596 var $dragBar = $(".ui-resizable-s");
2597 $dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
2598
2599 $( "#resize-packages-nav" ).resizable({
2600 containment: "#nav-panels",
2601 handles: "s",
2602 alsoResize: "#packages-nav",
2603 resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
2604 stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
2605 });
2606
2607 }
2608
2609function updateSidenavFixedWidth() {
2610 if (!navBarIsFixed) return;
2611 $('#devdoc-nav').css({
2612 'width' : $('#side-nav').css('width'),
2613 'margin' : $('#side-nav').css('margin')
2614 });
2615 $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
2616
2617 initSidenavHeightResize();
2618}
2619
2620function updateSidenavFullscreenWidth() {
2621 if (!navBarIsFixed) return;
2622 $('#devdoc-nav').css({
2623 'width' : $('#side-nav').css('width'),
2624 'margin' : $('#side-nav').css('margin')
2625 });
2626 $('#devdoc-nav .totop').css({'left': 'inherit'});
2627
2628 initSidenavHeightResize();
2629}
2630
2631function buildApiLevelSelector() {
2632 maxLevel = SINCE_DATA.length;
2633 var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
2634 userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
2635
2636 minLevel = parseInt($("#doc-api-level").attr("class"));
2637 // Handle provisional api levels; the provisional level will always be the highest possible level
2638 // Provisional api levels will also have a length; other stuff that's just missing a level won't,
2639 // so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
2640 if (isNaN(minLevel) && minLevel.length) {
2641 minLevel = maxLevel;
2642 }
2643 var select = $("#apiLevelSelector").html("").change(changeApiLevel);
2644 for (var i = maxLevel-1; i >= 0; i--) {
2645 var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
2646 // if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
2647 select.append(option);
2648 }
2649
2650 // get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
2651 var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
2652 selectedLevelItem.setAttribute('selected',true);
2653}
2654
2655function changeApiLevel() {
2656 maxLevel = SINCE_DATA.length;
2657 var selectedLevel = maxLevel;
2658
2659 selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
2660 toggleVisisbleApis(selectedLevel, "body");
2661
2662 var date = new Date();
2663 date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
2664 var expiration = date.toGMTString();
2665 writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
2666
2667 if (selectedLevel < minLevel) {
2668 var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
2669 $("#naMessage").show().html("<div><p><strong>This " + thing
2670 + " requires API level " + minLevel + " or higher.</strong></p>"
2671 + "<p>This document is hidden because your selected API level for the documentation is "
2672 + selectedLevel + ". You can change the documentation API level with the selector "
2673 + "above the left navigation.</p>"
2674 + "<p>For more information about specifying the API level your app requires, "
2675 + "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
2676 + ">Supporting Different Platform Versions</a>.</p>"
2677 + "<input type='button' value='OK, make this page visible' "
2678 + "title='Change the API level to " + minLevel + "' "
2679 + "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
2680 + "</div>");
2681 } else {
2682 $("#naMessage").hide();
2683 }
2684}
2685
2686function toggleVisisbleApis(selectedLevel, context) {
2687 var apis = $(".api",context);
2688 apis.each(function(i) {
2689 var obj = $(this);
2690 var className = obj.attr("class");
2691 var apiLevelIndex = className.lastIndexOf("-")+1;
2692 var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
2693 apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
2694 var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
2695 if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
2696 return;
2697 }
2698 apiLevel = parseInt(apiLevel);
2699
2700 // Handle provisional api levels; if this item's level is the provisional one, set it to the max
2701 var selectedLevelNum = parseInt(selectedLevel)
2702 var apiLevelNum = parseInt(apiLevel);
2703 if (isNaN(apiLevelNum)) {
2704 apiLevelNum = maxLevel;
2705 }
2706
2707 // Grey things out that aren't available and give a tooltip title
2708 if (apiLevelNum > selectedLevelNum) {
2709 obj.addClass("absent").attr("title","Requires API Level \""
2710 + apiLevel + "\" or higher. To reveal, change the target API level "
2711 + "above the left navigation.");
2712 }
2713 else obj.removeClass("absent").removeAttr("title");
2714 });
2715}
2716
2717
2718
2719
2720/* ################# SIDENAV TREE VIEW ################### */
2721
2722function new_node(me, mom, text, link, children_data, api_level)
2723{
2724 var node = new Object();
2725 node.children = Array();
2726 node.children_data = children_data;
2727 node.depth = mom.depth + 1;
2728
2729 node.li = document.createElement("li");
2730 mom.get_children_ul().appendChild(node.li);
2731
2732 node.label_div = document.createElement("div");
2733 node.label_div.className = "label";
2734 if (api_level != null) {
2735 $(node.label_div).addClass("api");
2736 $(node.label_div).addClass("api-level-"+api_level);
2737 }
2738 node.li.appendChild(node.label_div);
2739
2740 if (children_data != null) {
2741 node.expand_toggle = document.createElement("a");
2742 node.expand_toggle.href = "javascript:void(0)";
2743 node.expand_toggle.onclick = function() {
2744 if (node.expanded) {
2745 $(node.get_children_ul()).slideUp("fast");
2746 node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
2747 node.expanded = false;
2748 } else {
2749 expand_node(me, node);
2750 }
2751 };
2752 node.label_div.appendChild(node.expand_toggle);
2753
2754 node.plus_img = document.createElement("img");
2755 node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
2756 node.plus_img.className = "plus";
2757 node.plus_img.width = "8";
2758 node.plus_img.border = "0";
2759 node.expand_toggle.appendChild(node.plus_img);
2760
2761 node.expanded = false;
2762 }
2763
2764 var a = document.createElement("a");
2765 node.label_div.appendChild(a);
2766 node.label = document.createTextNode(text);
2767 a.appendChild(node.label);
2768 if (link) {
2769 a.href = me.toroot + link;
2770 } else {
2771 if (children_data != null) {
2772 a.className = "nolink";
2773 a.href = "javascript:void(0)";
2774 a.onclick = node.expand_toggle.onclick;
2775 // This next line shouldn't be necessary. I'll buy a beer for the first
2776 // person who figures out how to remove this line and have the link
2777 // toggle shut on the first try. --joeo@android.com
2778 node.expanded = false;
2779 }
2780 }
2781
2782
2783 node.children_ul = null;
2784 node.get_children_ul = function() {
2785 if (!node.children_ul) {
2786 node.children_ul = document.createElement("ul");
2787 node.children_ul.className = "children_ul";
2788 node.children_ul.style.display = "none";
2789 node.li.appendChild(node.children_ul);
2790 }
2791 return node.children_ul;
2792 };
2793
2794 return node;
2795}
2796
2797
2798
2799
2800function expand_node(me, node)
2801{
2802 if (node.children_data && !node.expanded) {
2803 if (node.children_visited) {
2804 $(node.get_children_ul()).slideDown("fast");
2805 } else {
2806 get_node(me, node);
2807 if ($(node.label_div).hasClass("absent")) {
2808 $(node.get_children_ul()).addClass("absent");
2809 }
2810 $(node.get_children_ul()).slideDown("fast");
2811 }
2812 node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
2813 node.expanded = true;
2814
2815 // perform api level toggling because new nodes are new to the DOM
2816 var selectedLevel = $("#apiLevelSelector option:selected").val();
2817 toggleVisisbleApis(selectedLevel, "#side-nav");
2818 }
2819}
2820
2821function get_node(me, mom)
2822{
2823 mom.children_visited = true;
2824 for (var i in mom.children_data) {
2825 var node_data = mom.children_data[i];
2826 mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
2827 node_data[2], node_data[3]);
2828 }
2829}
2830
2831function this_page_relative(toroot)
2832{
2833 var full = document.location.pathname;
2834 var file = "";
2835 if (toroot.substr(0, 1) == "/") {
2836 if (full.substr(0, toroot.length) == toroot) {
2837 return full.substr(toroot.length);
2838 } else {
2839 // the file isn't under toroot. Fail.
2840 return null;
2841 }
2842 } else {
2843 if (toroot != "./") {
2844 toroot = "./" + toroot;
2845 }
2846 do {
2847 if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
2848 var pos = full.lastIndexOf("/");
2849 file = full.substr(pos) + file;
2850 full = full.substr(0, pos);
2851 toroot = toroot.substr(0, toroot.length-3);
2852 }
2853 } while (toroot != "" && toroot != "/");
2854 return file.substr(1);
2855 }
2856}
2857
2858function find_page(url, data)
2859{
2860 var nodes = data;
2861 var result = null;
2862 for (var i in nodes) {
2863 var d = nodes[i];
2864 if (d[1] == url) {
2865 return new Array(i);
2866 }
2867 else if (d[2] != null) {
2868 result = find_page(url, d[2]);
2869 if (result != null) {
2870 return (new Array(i).concat(result));
2871 }
2872 }
2873 }
2874 return null;
2875}
2876
2877function init_default_navtree(toroot) {
2878 // load json file for navtree data
2879 $.getScript(toRoot + 'navtree_data.js', function(data, textStatus, jqxhr) {
2880 // when the file is loaded, initialize the tree
2881 if(jqxhr.status === 200) {
2882 init_navtree("tree-list", toroot, NAVTREE_DATA);
2883 }
2884 });
2885
2886 // perform api level toggling because because the whole tree is new to the DOM
2887 var selectedLevel = $("#apiLevelSelector option:selected").val();
2888 toggleVisisbleApis(selectedLevel, "#side-nav");
2889}
2890
2891function init_navtree(navtree_id, toroot, root_nodes)
2892{
2893 var me = new Object();
2894 me.toroot = toroot;
2895 me.node = new Object();
2896
2897 me.node.li = document.getElementById(navtree_id);
2898 me.node.children_data = root_nodes;
2899 me.node.children = new Array();
2900 me.node.children_ul = document.createElement("ul");
2901 me.node.get_children_ul = function() { return me.node.children_ul; };
2902 //me.node.children_ul.className = "children_ul";
2903 me.node.li.appendChild(me.node.children_ul);
2904 me.node.depth = 0;
2905
2906 get_node(me, me.node);
2907
2908 me.this_page = this_page_relative(toroot);
2909 me.breadcrumbs = find_page(me.this_page, root_nodes);
2910 if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
2911 var mom = me.node;
2912 for (var i in me.breadcrumbs) {
2913 var j = me.breadcrumbs[i];
2914 mom = mom.children[j];
2915 expand_node(me, mom);
2916 }
2917 mom.label_div.className = mom.label_div.className + " selected";
2918 addLoadEvent(function() {
2919 scrollIntoView("nav-tree");
2920 });
2921 }
2922}
2923
2924
2925
2926
2927
2928
2929
2930
2931/* TODO: eliminate redundancy with non-google functions */
2932function init_google_navtree(navtree_id, toroot, root_nodes)
2933{
2934 var me = new Object();
2935 me.toroot = toroot;
2936 me.node = new Object();
2937
2938 me.node.li = document.getElementById(navtree_id);
2939 me.node.children_data = root_nodes;
2940 me.node.children = new Array();
2941 me.node.children_ul = document.createElement("ul");
2942 me.node.get_children_ul = function() { return me.node.children_ul; };
2943 //me.node.children_ul.className = "children_ul";
2944 me.node.li.appendChild(me.node.children_ul);
2945 me.node.depth = 0;
2946
2947 get_google_node(me, me.node);
2948}
2949
2950function new_google_node(me, mom, text, link, children_data, api_level)
2951{
2952 var node = new Object();
2953 var child;
2954 node.children = Array();
2955 node.children_data = children_data;
2956 node.depth = mom.depth + 1;
2957 node.get_children_ul = function() {
2958 if (!node.children_ul) {
2959 node.children_ul = document.createElement("ul");
2960 node.children_ul.className = "tree-list-children";
2961 node.li.appendChild(node.children_ul);
2962 }
2963 return node.children_ul;
2964 };
2965 node.li = document.createElement("li");
2966
2967 mom.get_children_ul().appendChild(node.li);
2968
2969
2970 if(link) {
2971 child = document.createElement("a");
2972
2973 }
2974 else {
2975 child = document.createElement("span");
2976 child.className = "tree-list-subtitle";
2977
2978 }
2979 if (children_data != null) {
2980 node.li.className="nav-section";
2981 node.label_div = document.createElement("div");
2982 node.label_div.className = "nav-section-header-ref";
2983 node.li.appendChild(node.label_div);
2984 get_google_node(me, node);
2985 node.label_div.appendChild(child);
2986 }
2987 else {
2988 node.li.appendChild(child);
2989 }
2990 if(link) {
2991 child.href = me.toroot + link;
2992 }
2993 node.label = document.createTextNode(text);
2994 child.appendChild(node.label);
2995
2996 node.children_ul = null;
2997
2998 return node;
2999}
3000
3001function get_google_node(me, mom)
3002{
3003 mom.children_visited = true;
3004 var linkText;
3005 for (var i in mom.children_data) {
3006 var node_data = mom.children_data[i];
3007 linkText = node_data[0];
3008
3009 if(linkText.match("^"+"com.google.android")=="com.google.android"){
3010 linkText = linkText.substr(19, linkText.length);
3011 }
3012 mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
3013 node_data[2], node_data[3]);
3014 }
3015}
3016
3017
3018
3019
3020
3021
3022/****** NEW version of script to build google and sample navs dynamically ******/
3023// TODO: update Google reference docs to tolerate this new implementation
3024
3025var NODE_NAME = 0;
3026var NODE_HREF = 1;
3027var NODE_GROUP = 2;
3028var NODE_TAGS = 3;
3029var NODE_CHILDREN = 4;
3030
3031function init_google_navtree2(navtree_id, data)
3032{
3033 var $containerUl = $("#"+navtree_id);
3034 for (var i in data) {
3035 var node_data = data[i];
3036 $containerUl.append(new_google_node2(node_data));
3037 }
3038
3039 // Make all third-generation list items 'sticky' to prevent them from collapsing
3040 $containerUl.find('li li li.nav-section').addClass('sticky');
3041
3042 initExpandableNavItems("#"+navtree_id);
3043}
3044
3045function new_google_node2(node_data)
3046{
3047 var linkText = node_data[NODE_NAME];
3048 if(linkText.match("^"+"com.google.android")=="com.google.android"){
3049 linkText = linkText.substr(19, linkText.length);
3050 }
3051 var $li = $('<li>');
3052 var $a;
3053 if (node_data[NODE_HREF] != null) {
3054 $a = $('<a href="' + toRoot + node_data[NODE_HREF] + '" title="' + linkText + '" >'
3055 + linkText + '</a>');
3056 } else {
3057 $a = $('<a href="#" onclick="return false;" title="' + linkText + '" >'
3058 + linkText + '/</a>');
3059 }
3060 var $childUl = $('<ul>');
3061 if (node_data[NODE_CHILDREN] != null) {
3062 $li.addClass("nav-section");
3063 $a = $('<div class="nav-section-header">').append($a);
3064 if (node_data[NODE_HREF] == null) $a.addClass('empty');
3065
3066 for (var i in node_data[NODE_CHILDREN]) {
3067 var child_node_data = node_data[NODE_CHILDREN][i];
3068 $childUl.append(new_google_node2(child_node_data));
3069 }
3070 $li.append($childUl);
3071 }
3072 $li.prepend($a);
3073
3074 return $li;
3075}
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087function showGoogleRefTree() {
3088 init_default_google_navtree(toRoot);
3089 init_default_gcm_navtree(toRoot);
3090}
3091
3092function init_default_google_navtree(toroot) {
3093 // load json file for navtree data
3094 $.getScript(toRoot + 'gms_navtree_data.js', function(data, textStatus, jqxhr) {
3095 // when the file is loaded, initialize the tree
3096 if(jqxhr.status === 200) {
3097 init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
3098 highlightSidenav();
3099 resizeNav();
3100 }
3101 });
3102}
3103
3104function init_default_gcm_navtree(toroot) {
3105 // load json file for navtree data
3106 $.getScript(toRoot + 'gcm_navtree_data.js', function(data, textStatus, jqxhr) {
3107 // when the file is loaded, initialize the tree
3108 if(jqxhr.status === 200) {
3109 init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
3110 highlightSidenav();
3111 resizeNav();
3112 }
3113 });
3114}
3115
3116function showSamplesRefTree() {
3117 init_default_samples_navtree(toRoot);
3118}
3119
3120function init_default_samples_navtree(toroot) {
3121 // load json file for navtree data
3122 $.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
3123 // when the file is loaded, initialize the tree
3124 if(jqxhr.status === 200) {
3125 // hack to remove the "about the samples" link then put it back in
3126 // after we nuke the list to remove the dummy static list of samples
3127 var $firstLi = $("#nav.samples-nav > li:first-child").clone();
3128 $("#nav.samples-nav").empty();
3129 $("#nav.samples-nav").append($firstLi);
3130
3131 init_google_navtree2("nav.samples-nav", SAMPLES_NAVTREE_DATA);
3132 highlightSidenav();
3133 resizeNav();
3134 if ($("#jd-content #samples").length) {
3135 showSamples();
3136 }
3137 }
3138 });
3139}
3140
3141/* TOGGLE INHERITED MEMBERS */
3142
3143/* Toggle an inherited class (arrow toggle)
3144 * @param linkObj The link that was clicked.
3145 * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
3146 * 'null' to simply toggle.
3147 */
3148function toggleInherited(linkObj, expand) {
3149 var base = linkObj.getAttribute("id");
3150 var list = document.getElementById(base + "-list");
3151 var summary = document.getElementById(base + "-summary");
3152 var trigger = document.getElementById(base + "-trigger");
3153 var a = $(linkObj);
3154 if ( (expand == null && a.hasClass("closed")) || expand ) {
3155 list.style.display = "none";
3156 summary.style.display = "block";
3157 trigger.src = toRoot + "assets/images/triangle-opened.png";
3158 a.removeClass("closed");
3159 a.addClass("opened");
3160 } else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
3161 list.style.display = "block";
3162 summary.style.display = "none";
3163 trigger.src = toRoot + "assets/images/triangle-closed.png";
3164 a.removeClass("opened");
3165 a.addClass("closed");
3166 }
3167 return false;
3168}
3169
3170/* Toggle all inherited classes in a single table (e.g. all inherited methods)
3171 * @param linkObj The link that was clicked.
3172 * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
3173 * 'null' to simply toggle.
3174 */
3175function toggleAllInherited(linkObj, expand) {
3176 var a = $(linkObj);
3177 var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
3178 var expandos = $(".jd-expando-trigger", table);
3179 if ( (expand == null && a.text() == "[Expand]") || expand ) {
3180 expandos.each(function(i) {
3181 toggleInherited(this, true);
3182 });
3183 a.text("[Collapse]");
3184 } else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
3185 expandos.each(function(i) {
3186 toggleInherited(this, false);
3187 });
3188 a.text("[Expand]");
3189 }
3190 return false;
3191}
3192
3193/* Toggle all inherited members in the class (link in the class title)
3194 */
3195function toggleAllClassInherited() {
3196 var a = $("#toggleAllClassInherited"); // get toggle link from class title
3197 var toggles = $(".toggle-all", $("#body-content"));
3198 if (a.text() == "[Expand All]") {
3199 toggles.each(function(i) {
3200 toggleAllInherited(this, true);
3201 });
3202 a.text("[Collapse All]");
3203 } else {
3204 toggles.each(function(i) {
3205 toggleAllInherited(this, false);
3206 });
3207 a.text("[Expand All]");
3208 }
3209 return false;
3210}
3211
3212/* Expand all inherited members in the class. Used when initiating page search */
3213function ensureAllInheritedExpanded() {
3214 var toggles = $(".toggle-all", $("#body-content"));
3215 toggles.each(function(i) {
3216 toggleAllInherited(this, true);
3217 });
3218 $("#toggleAllClassInherited").text("[Collapse All]");
3219}
3220
3221
3222/* HANDLE KEY EVENTS
3223 * - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
3224 */
3225var agent = navigator['userAgent'].toLowerCase();
3226var mac = agent.indexOf("macintosh") != -1;
3227
3228$(document).keydown( function(e) {
3229var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
3230 if (control && e.which == 70) { // 70 is "F"
3231 ensureAllInheritedExpanded();
3232 }
3233});
3234
3235
3236
3237
3238
3239
3240/* On-demand functions */
3241
3242/** Move sample code line numbers out of PRE block and into non-copyable column */
3243function initCodeLineNumbers() {
3244 var numbers = $("#codesample-block a.number");
3245 if (numbers.length) {
3246 $("#codesample-line-numbers").removeClass("hidden").append(numbers);
3247 }
3248
3249 $(document).ready(function() {
3250 // select entire line when clicked
3251 $("span.code-line").click(function() {
3252 if (!shifted) {
3253 selectText(this);
3254 }
3255 });
3256 // invoke line link on double click
3257 $(".code-line").dblclick(function() {
3258 document.location.hash = $(this).attr('id');
3259 });
3260 // highlight the line when hovering on the number
3261 $("#codesample-line-numbers a.number").mouseover(function() {
3262 var id = $(this).attr('href');
3263 $(id).css('background','#e7e7e7');
3264 });
3265 $("#codesample-line-numbers a.number").mouseout(function() {
3266 var id = $(this).attr('href');
3267 $(id).css('background','none');
3268 });
3269 });
3270}
3271
3272// create SHIFT key binder to avoid the selectText method when selecting multiple lines
3273var shifted = false;
3274$(document).bind('keyup keydown', function(e){shifted = e.shiftKey; return true;} );
3275
3276// courtesy of jasonedelman.com
3277function selectText(element) {
3278 var doc = document
3279 , range, selection
3280 ;
3281 if (doc.body.createTextRange) { //ms
3282 range = doc.body.createTextRange();
3283 range.moveToElementText(element);
3284 range.select();
3285 } else if (window.getSelection) { //all others
3286 selection = window.getSelection();
3287 range = doc.createRange();
3288 range.selectNodeContents(element);
3289 selection.removeAllRanges();
3290 selection.addRange(range);
3291 }
3292}
3293
3294
3295
3296
3297/** Display links and other information about samples that match the
3298 group specified by the URL */
3299function showSamples() {
3300 var group = $("#samples").attr('class');
3301 $("#samples").html("<p>Here are some samples for <b>" + group + "</b> apps:</p>");
3302
3303 var $ul = $("<ul>");
3304 $selectedLi = $("#nav li.selected");
3305
3306 $selectedLi.children("ul").children("li").each(function() {
3307 var $li = $("<li>").append($(this).find("a").first().clone());
3308 $ul.append($li);
3309 });
3310
3311 $("#samples").append($ul);
3312
3313}
Dirk Dougherty08032402014-02-15 10:14:35 -08003314
3315
3316
3317/* ########################################################## */
3318/* ################### RESOURCE CARDS ##################### */
3319/* ########################################################## */
3320
3321/** Handle resource queries, collections, and grids (sections). Requires
3322 jd_tag_helpers.js and the *_unified_data.js to be loaded. */
3323
3324(function() {
3325 // Prevent the same resource from being loaded more than once per page.
3326 var addedPageResources = {};
3327
3328 $(document).ready(function() {
3329 $('.resource-widget').each(function() {
3330 initResourceWidget(this);
3331 });
3332
3333 // Might remove this, but adds ellipsis to card descriptions rather
3334 // than just cutting them off, not sure if it performs well
3335 $('.card-info .text').ellipsis();
3336 });
3337
3338 /*
3339 Three types of resource layouts:
3340 Flow - Uses a fixed row-height flow using float left style.
3341 Carousel - Single card slideshow all same dimension absoute.
3342 Stack - Uses fixed columns and flexible element height.
3343 */
3344 function initResourceWidget(widget) {
3345 var $widget = $(widget);
3346 var isFlow = $widget.hasClass('resource-flow-layout'),
3347 isCarousel = $widget.hasClass('resource-carousel-layout'),
3348 isStack = $widget.hasClass('resource-stack-layout');
3349
3350 // find size of widget by pulling out its class name
3351 var sizeCols = 1;
3352 var m = $widget.get(0).className.match(/\bcol-(\d+)\b/);
3353 if (m) {
3354 sizeCols = parseInt(m[1], 10);
3355 }
3356
3357 var opts = {
3358 cardSizes: ($widget.data('cardsizes') || '').split(','),
3359 maxResults: parseInt($widget.data('maxresults') || '100', 10),
3360 itemsPerPage: $widget.data('itemsperpage'),
3361 sortOrder: $widget.data('sortorder'),
3362 query: $widget.data('query'),
3363 section: $widget.data('section'),
3364 sizeCols: sizeCols
3365 };
3366
3367 // run the search for the set of resources to show
3368
3369 var resources = buildResourceList(opts);
3370
3371 if (isFlow) {
3372 drawResourcesFlowWidget($widget, opts, resources);
3373 } else if (isCarousel) {
3374 drawResourcesCarouselWidget($widget, opts, resources);
3375 } else if (isStack) {
3376 var sections = buildSectionList(opts);
3377 opts['numStacks'] = $widget.data('numstacks');
3378 drawResourcesStackWidget($widget, opts, resources, sections);
3379 }
3380 }
3381
3382 /* Initializes a Resource Carousel Widget */
3383 function drawResourcesCarouselWidget($widget, opts, resources) {
3384 $widget.empty();
3385
3386 $widget.addClass('resource-card slideshow-container')
3387 .append($('<a>').addClass('slideshow-prev').text('Prev'))
3388 .append($('<a>').addClass('slideshow-next').text('Next'));
3389
3390 var css = { 'width': $widget.width() + 'px',
3391 'height': $widget.height() + 'px' };
3392
3393 var $ul = $('<ul>');
3394
3395 for (var i = 0; i < resources.length; ++i) {
3396 //keep url clean for matching and offline mode handling
3397 var urlPrefix = resources[i].url.indexOf("//") > -1 ? "" : toRoot;
3398 var $card = $('<a>')
3399 .attr('href', urlPrefix + resources[i].url)
3400 .decorateResourceCard(resources[i]);
3401
3402 $('<li>').css(css)
3403 .append($card)
3404 .appendTo($ul);
3405 }
3406
3407 $('<div>').addClass('frame')
3408 .append($ul)
3409 .appendTo($widget);
3410
3411 $widget.dacSlideshow({
3412 auto: true,
3413 btnPrev: '.slideshow-prev',
3414 btnNext: '.slideshow-next'
3415 });
3416 };
3417
3418 /* Initializes a Resource Card Stack Widget (column-based layout) */
3419 function drawResourcesStackWidget($widget, opts, resources, sections) {
3420 // Don't empty widget, grab all items inside since they will be the first
3421 // items stacked, followed by the resource query
3422
3423 var cards = $widget.find('.resource-card').detach().toArray();
3424 var numStacks = opts.numStacks || 1;
3425 var $stacks = [];
3426 var urlString;
3427
3428 for (var i = 0; i < numStacks; ++i) {
3429 $stacks[i] = $('<div>').addClass('resource-card-stack')
3430 .appendTo($widget);
3431 }
3432
3433 var sectionResources = [];
3434
3435 // Extract any subsections that are actually resource cards
3436 for (var i = 0; i < sections.length; ++i) {
3437 if (!sections[i].sections || !sections[i].sections.length) {
3438 //keep url clean for matching and offline mode handling
3439 urlPrefix = sections[i].url.indexOf("//") > -1 ? "" : toRoot;
3440 // Render it as a resource card
3441
3442 sectionResources.push(
3443 $('<a>')
3444 .addClass('resource-card section-card')
3445 .attr('href', urlPrefix + sections[i].resource.url)
3446 .decorateResourceCard(sections[i].resource)[0]
3447 );
3448
3449 } else {
3450 cards.push(
3451 $('<div>')
3452 .addClass('resource-card section-card-menu')
3453 .decorateResourceSection(sections[i])[0]
3454 );
3455 }
3456 }
3457
3458 cards = cards.concat(sectionResources);
3459
3460 for (var i = 0; i < resources.length; ++i) {
3461 //keep url clean for matching and offline mode handling
3462 urlPrefix = resources[i].url.indexOf("//") > -1 ? "" : toRoot;
3463 var $card = $('<a>')
3464 .addClass('resource-card related-card')
3465 .attr('href', urlPrefix + resources[i].url)
3466 .decorateResourceCard(resources[i]);
3467
3468 cards.push($card[0]);
3469 }
3470
3471 for (var i = 0; i < cards.length; ++i) {
3472 // Find the stack with the shortest height, but give preference to
3473 // left to right order.
3474 var minHeight = $stacks[0].height();
3475 var minIndex = 0;
3476
3477 for (var j = 1; j < numStacks; ++j) {
3478 var height = $stacks[j].height();
3479 if (height < minHeight - 45) {
3480 minHeight = height;
3481 minIndex = j;
3482 }
3483 }
3484
3485 $stacks[minIndex].append($(cards[i]));
3486 }
3487
3488 };
3489
3490 /* Initializes a flow widget, see distribute.scss for generating accompanying css */
3491 function drawResourcesFlowWidget($widget, opts, resources) {
3492 $widget.empty();
3493 var cardSizes = opts.cardSizes || ['6x6'];
3494 var i = 0, j = 0;
3495
3496 while (i < resources.length) {
3497 var cardSize = cardSizes[j++ % cardSizes.length];
3498 cardSize = cardSize.replace(/^\s+|\s+$/,'');
3499
3500 // A stack has a third dimension which is the number of stacked items
3501 var isStack = cardSize.match(/(\d+)x(\d+)x(\d+)/);
3502 var stackCount = 0;
3503 var $stackDiv = null;
3504
3505 if (isStack) {
3506 // Create a stack container which should have the dimensions defined
3507 // by the product of the items inside.
3508 $stackDiv = $('<div>').addClass('resource-card-stack resource-card-' + isStack[1]
3509 + 'x' + isStack[2] * isStack[3]) .appendTo($widget);
3510 }
3511
3512 // Build each stack item or just a single item
3513 do {
3514 var resource = resources[i];
3515 //keep url clean for matching and offline mode handling
3516 urlPrefix = resource.url.indexOf("//") > -1 ? "" : toRoot;
3517 var $card = $('<a>')
3518 .addClass('resource-card resource-card-' + cardSize + ' resource-card-' + resource.type)
3519 .attr('href', urlPrefix + resource.url);
3520
3521 if (isStack) {
3522 $card.addClass('resource-card-' + isStack[1] + 'x' + isStack[2]);
3523 if (++stackCount == parseInt(isStack[3])) {
3524 $card.addClass('resource-card-row-stack-last');
3525 stackCount = 0;
3526 }
3527 } else {
3528 stackCount = 0;
3529 }
3530
3531 $card.decorateResourceCard(resource)
3532 .appendTo($stackDiv || $widget);
3533
3534 } while (++i < resources.length && stackCount > 0);
3535 }
3536 }
3537
3538 /* Build a site map of resources using a section as a root. */
3539 function buildSectionList(opts) {
3540 if (opts.section && SECTION_BY_ID[opts.section]) {
3541 return SECTION_BY_ID[opts.section].sections || [];
3542 }
3543 return [];
3544 }
3545
3546 function buildResourceList(opts) {
3547 var maxResults = opts.maxResults || 100;
3548
3549 var query = opts.query || '';
3550 var expressions = parseResourceQuery(query);
3551 var addedResourceIndices = {};
3552 var results = [];
3553
3554 for (var i = 0; i < expressions.length; i++) {
3555 var clauses = expressions[i];
3556
3557 // build initial set of resources from first clause
3558 var firstClause = clauses[0];
3559 var resources = [];
3560 switch (firstClause.attr) {
3561 case 'type':
3562 resources = ALL_RESOURCES_BY_TYPE[firstClause.value];
3563 break;
3564 case 'lang':
3565 resources = ALL_RESOURCES_BY_LANG[firstClause.value];
3566 break;
3567 case 'tag':
3568 resources = ALL_RESOURCES_BY_TAG[firstClause.value];
3569 break;
3570 case 'collection':
3571 var urls = RESOURCE_COLLECTIONS[firstClause.value].resources || [];
3572 resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
3573 break;
3574 case 'section':
3575 var urls = SITE_MAP[firstClause.value].sections || [];
3576 resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
3577 break;
3578 }
Scott Main20cf2a92014-04-02 21:57:20 -07003579 // console.log(firstClause.attr + ':' + firstClause.value);
Dirk Dougherty08032402014-02-15 10:14:35 -08003580 resources = resources || [];
3581
3582 // use additional clauses to filter corpus
3583 if (clauses.length > 1) {
3584 var otherClauses = clauses.slice(1);
3585 resources = resources.filter(getResourceMatchesClausesFilter(otherClauses));
3586 }
3587
3588 // filter out resources already added
3589 if (i > 1) {
3590 resources = resources.filter(getResourceNotAlreadyAddedFilter(addedResourceIndices));
3591 }
3592
3593 // add to list of already added indices
3594 for (var j = 0; j < resources.length; j++) {
Scott Main20cf2a92014-04-02 21:57:20 -07003595 // console.log(resources[j].title);
Dirk Dougherty08032402014-02-15 10:14:35 -08003596 addedResourceIndices[resources[j].index] = 1;
3597 }
3598
3599 // concat to final results list
3600 results = results.concat(resources);
3601 }
3602
3603 if (opts.sortOrder && results.length) {
3604 var attr = opts.sortOrder;
3605
3606 if (opts.sortOrder == 'random') {
3607 var i = results.length, j, temp;
3608 while (--i) {
3609 j = Math.floor(Math.random() * (i + 1));
3610 temp = results[i];
3611 results[i] = results[j];
3612 results[j] = temp;
3613 }
3614 } else {
3615 var desc = attr.charAt(0) == '-';
3616 if (desc) {
3617 attr = attr.substring(1);
3618 }
3619 results = results.sort(function(x,y) {
3620 return (desc ? -1 : 1) * (parseInt(x[attr], 10) - parseInt(y[attr], 10));
3621 });
3622 }
3623 }
3624
3625 results = results.filter(getResourceNotAlreadyAddedFilter(addedPageResources));
3626 results = results.slice(0, maxResults);
3627
3628 for (var j = 0; j < results.length; ++j) {
3629 addedPageResources[results[j].index] = 1;
3630 }
3631
3632 return results;
3633 }
3634
3635
3636 function getResourceNotAlreadyAddedFilter(addedResourceIndices) {
3637 return function(resource) {
3638 return !addedResourceIndices[resource.index];
3639 };
3640 }
3641
3642
3643 function getResourceMatchesClausesFilter(clauses) {
3644 return function(resource) {
3645 return doesResourceMatchClauses(resource, clauses);
3646 };
3647 }
3648
3649
3650 function doesResourceMatchClauses(resource, clauses) {
3651 for (var i = 0; i < clauses.length; i++) {
3652 var map;
3653 switch (clauses[i].attr) {
3654 case 'type':
3655 map = IS_RESOURCE_OF_TYPE[clauses[i].value];
3656 break;
3657 case 'lang':
3658 map = IS_RESOURCE_IN_LANG[clauses[i].value];
3659 break;
3660 case 'tag':
3661 map = IS_RESOURCE_TAGGED[clauses[i].value];
3662 break;
3663 }
3664
3665 if (!map || (!!clauses[i].negative ? map[resource.index] : !map[resource.index])) {
3666 return clauses[i].negative;
3667 }
3668 }
3669 return true;
3670 }
3671
3672
3673 function parseResourceQuery(query) {
3674 // Parse query into array of expressions (expression e.g. 'tag:foo + type:video')
3675 var expressions = [];
3676 var expressionStrs = query.split(',') || [];
3677 for (var i = 0; i < expressionStrs.length; i++) {
3678 var expr = expressionStrs[i] || '';
3679
3680 // Break expression into clauses (clause e.g. 'tag:foo')
3681 var clauses = [];
3682 var clauseStrs = expr.split(/(?=[\+\-])/);
3683 for (var j = 0; j < clauseStrs.length; j++) {
3684 var clauseStr = clauseStrs[j] || '';
3685
3686 // Get attribute and value from clause (e.g. attribute='tag', value='foo')
3687 var parts = clauseStr.split(':');
3688 var clause = {};
3689
3690 clause.attr = parts[0].replace(/^\s+|\s+$/g,'');
3691 if (clause.attr) {
3692 if (clause.attr.charAt(0) == '+') {
3693 clause.attr = clause.attr.substring(1);
3694 } else if (clause.attr.charAt(0) == '-') {
3695 clause.negative = true;
3696 clause.attr = clause.attr.substring(1);
3697 }
3698 }
3699
3700 if (parts.length > 1) {
3701 clause.value = parts[1].replace(/^\s+|\s+$/g,'');
3702 }
3703
3704 clauses.push(clause);
3705 }
3706
3707 if (!clauses.length) {
3708 continue;
3709 }
3710
3711 expressions.push(clauses);
3712 }
3713
3714 return expressions;
3715 }
3716})();
3717
3718(function($) {
3719 /* Simple jquery function to create dom for a standard resource card */
3720 $.fn.decorateResourceCard = function(resource) {
3721 var section = resource.group || resource.type;
3722 var imgUrl;
3723 if (resource.image) {
3724 //keep url clean for matching and offline mode handling
3725 var urlPrefix = resource.image.indexOf("//") > -1 ? "" : toRoot;
3726 imgUrl = urlPrefix + resource.image;
3727 }
3728
3729 $('<div>')
3730 .addClass('card-bg')
3731 .css('background-image', 'url(' + (imgUrl || toRoot + 'assets/images/resource-card-default-android.jpg') + ')')
3732 .appendTo(this);
3733
3734 $('<div>').addClass('card-info' + (!resource.summary ? ' empty-desc' : ''))
3735 .append($('<div>').addClass('section').text(section))
3736 .append($('<div>').addClass('title').html(resource.title))
3737 .append($('<div>').addClass('description')
3738 .append($('<div>').addClass('text').html(resource.summary))
3739 .append($('<div>').addClass('util')
3740 .append($('<div>').addClass('g-plusone')
3741 .attr('data-size', 'small')
3742 .attr('data-align', 'right')
3743 .attr('data-href', resource.url))))
3744 .appendTo(this);
3745
3746 return this;
3747 };
3748
3749 /* Simple jquery function to create dom for a resource section card (menu) */
3750 $.fn.decorateResourceSection = function(section) {
3751 var resource = section.resource;
3752 //keep url clean for matching and offline mode handling
3753 var urlPrefix = resource.image.indexOf("//") > -1 ? "" : toRoot;
3754 var $base = $('<a>')
3755 .addClass('card-bg')
3756 .attr('href', resource.url)
3757 .append($('<div>').addClass('card-section-icon')
3758 .append($('<div>').addClass('icon'))
3759 .append($('<div>').addClass('section').html(resource.title)))
3760 .appendTo(this);
3761
3762 var $cardInfo = $('<div>').addClass('card-info').appendTo(this);
3763
3764 if (section.sections && section.sections.length) {
3765 // Recurse the section sub-tree to find a resource image.
3766 var stack = [section];
3767
3768 while (stack.length) {
3769 if (stack[0].resource.image) {
3770 $base.css('background-image', 'url(' + urlPrefix + stack[0].resource.image + ')');
3771 break;
3772 }
3773
3774 if (stack[0].sections) {
3775 stack = stack.concat(stack[0].sections);
3776 }
3777
3778 stack.shift();
3779 }
3780
3781 var $ul = $('<ul>')
3782 .appendTo($cardInfo);
3783
3784 var max = section.sections.length > 3 ? 3 : section.sections.length;
3785
3786 for (var i = 0; i < max; ++i) {
3787
3788 var subResource = section.sections[i];
3789 $('<li>')
3790 .append($('<a>').attr('href', subResource.url)
3791 .append($('<div>').addClass('title').html(subResource.title))
3792 .append($('<div>').addClass('description')
3793 .append($('<div>').addClass('text').html(subResource.summary))
3794 .append($('<div>').addClass('util')
3795 .append($('<div>').addClass('g-plusone')
3796 .attr('data-size', 'small')
3797 .attr('data-align', 'right')
3798 .attr('data-href', resource.url)))))
3799 .appendTo($ul);
3800 }
3801
3802 // Add a more row
3803 if (max < section.sections.length) {
3804 $('<li>')
3805 .append($('<a>').attr('href', resource.url)
3806 .append($('<div>')
3807 .addClass('title')
3808 .text('More')))
3809 .appendTo($ul);
3810 }
3811 } else {
3812 // No sub-resources, just render description?
3813 }
3814
3815 return this;
3816 };
3817})(jQuery);
3818
3819
3820(function($) {
3821 $.fn.ellipsis = function(options) {
3822
3823 // default option
3824 var defaults = {
3825 'row' : 1, // show rows
3826 'onlyFullWords': true, // set to true to avoid cutting the text in the middle of a word
Dirk Dougherty46b443a2014-04-06 15:27:33 -07003827 'char' : '\u2026', // ellipsis
Dirk Dougherty08032402014-02-15 10:14:35 -08003828 'callback': function() {},
3829 'position': 'tail' // middle, tail
3830 };
3831
3832 options = $.extend(defaults, options);
3833
3834 this.each(function() {
3835 // get element text
3836 var $this = $(this);
3837
3838 var targetHeight = $this.height();
3839 $this.css({'height': 'auto'});
3840 var text = $this.text();
3841 var origText = text;
3842 var origLength = origText.length;
3843 var origHeight = $this.height();
3844
3845 if (origHeight <= targetHeight) {
3846 $this.text(text);
3847 options.callback.call(this);
3848 return;
3849 }
3850
3851 var start = 1, length = 0;
3852 var end = text.length;
3853
3854 if(options.position === 'tail') {
3855 while (start < end) { // Binary search for max length
3856 length = Math.ceil((start + end) / 2);
3857
3858 $this.text(text.slice(0, length) + options['char']);
3859
3860 if ($this.height() <= targetHeight) {
3861 start = length;
3862 } else {
3863 end = length - 1;
3864 }
3865 }
3866
3867 text = text.slice(0, start);
3868
3869 if (options.onlyFullWords) {
3870 // remove fragment of the last word together with possible soft-hyphen chars
3871 text = text.replace(/[\u00AD\w\uac00-\ud7af]+$/, '');
3872 }
3873 text += options['char'];
3874
3875 }else if(options.position === 'middle') {
3876
3877 var sliceLength = 0;
3878 while (start < end) { // Binary search for max length
3879 length = Math.ceil((start + end) / 2);
3880 sliceLength = Math.max(origLength - length, 0);
3881
3882 $this.text(
3883 origText.slice(0, Math.floor((origLength - sliceLength) / 2)) +
3884 options['char'] +
3885 origText.slice(Math.floor((origLength + sliceLength) / 2), origLength)
3886 );
3887
3888 if ($this.height() <= targetHeight) {
3889 start = length;
3890 } else {
3891 end = length - 1;
3892 }
3893 }
3894
3895 sliceLength = Math.max(origLength - start, 0);
3896 var head = origText.slice(0, Math.floor((origLength - sliceLength) / 2));
3897 var tail = origText.slice(Math.floor((origLength + sliceLength) / 2), origLength);
3898
3899 if (options.onlyFullWords) {
3900 // remove fragment of the last or first word together with possible soft-hyphen characters
3901 head = head.replace(/[\u00AD\w\uac00-\ud7af]+$/, '');
3902 }
3903
3904 text = head + options['char'] + tail;
3905 }
3906
3907 $this.text(text);
3908 options.callback.call(this);
3909 });
3910
3911 return this;
3912 };
Scott Main20cf2a92014-04-02 21:57:20 -07003913}) (jQuery);