blob: 00a1b2b85f66fd569d96ce94e78d963f8e7fe13a [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');
894 //var scrollThrottle = -1;
895 var lastScroll = 0;
896 var autoScrolling = false;
897
Scott Main20cf2a92014-04-02 21:57:20 -0700898 var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
Dirk Dougherty08032402014-02-15 10:14:35 -0800899
Scott Main20cf2a92014-04-02 21:57:20 -0700900 $(window).scroll(function() {
901 // Exit if there's no sidenav
902 if ($('#side-nav').length == 0) return;
903 // Exit if the mouse target is a DIV, because that means the event is coming
904 // from a scrollable div and so there's no need to make adjustments to our layout
905 if (event.target.nodeName == "DIV") {
906 return;
907 }
908
909
910 var top = $(window).scrollTop();
911 // we set the navbar fixed when the scroll position is beyond the height of the site header...
912 var shouldBeSticky = top >= stickyTop;
913 // ... except if the document content is shorter than the sidenav height.
914 // (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
915 if ($("#doc-col").height() < $("#side-nav").height()) {
916 shouldBeSticky = false;
917 }
918
919 // Don't continue if the header is sufficently far away
920 // (to avoid intensive resizing that slows scrolling)
921 if (sticky && shouldBeSticky) {
922 return;
923 }
924
925 // Account for horizontal scroll
926 var scrollLeft = $(window).scrollLeft();
927 // When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
928 if (navBarIsFixed && (scrollLeft != prevScrollLeft)) {
929 updateSideNavPosition();
930 prevScrollLeft = scrollLeft;
931 }
932
933 // If sticky header visible and position is now near top, hide sticky
934 if (sticky && !shouldBeSticky) {
Dirk Dougherty08032402014-02-15 10:14:35 -0800935 sticky = false;
936 hiding = true;
Scott Main20cf2a92014-04-02 21:57:20 -0700937 // make the sidenav static again
938 $('#devdoc-nav')
939 .removeClass('fixed')
940 .css({'width':'auto','margin':''})
941 .prependTo('#side-nav');
942 // delay hide the sticky
943 $menuEl.removeClass('sticky-menu');
944 $stickyEl.fadeOut(250);
945 hiding = false;
946
947 // update the sidenaav position for side scrolling
948 updateSideNavPosition();
949 } else if (!sticky && shouldBeSticky) {
Dirk Dougherty08032402014-02-15 10:14:35 -0800950 sticky = true;
Scott Main20cf2a92014-04-02 21:57:20 -0700951 $stickyEl.fadeIn(10);
Dirk Dougherty08032402014-02-15 10:14:35 -0800952 $menuEl.addClass('sticky-menu');
953
Dirk Dougherty08032402014-02-15 10:14:35 -0800954
955 // If its a jump then make sure to modify the scroll because of the
956 // sticky nav
957 if (!autoScrolling && Math.abs(top - lastScroll > 100)) {
958 autoScrolling = true;
959 $('body,html').animate({scrollTop:(top = top - 60)}, '250', 'swing', function() { autoScrolling = false; });
960 }
Scott Main20cf2a92014-04-02 21:57:20 -0700961
962 // make the sidenav fixed
963 var width = $('#devdoc-nav').width();
964 $('#devdoc-nav')
965 .addClass('fixed')
966 .css({'width':width+'px'})
967 .prependTo('#body-content');
968
969 // update the sidenaav position for side scrolling
970 updateSideNavPosition();
971
Dirk Dougherty08032402014-02-15 10:14:35 -0800972 } else if (hiding && top < 15) {
973 $menuEl.removeClass('sticky-menu');
974 $stickyEl.hide();
975 hiding = false;
976 }
977
978 lastScroll = top;
Scott Main20cf2a92014-04-02 21:57:20 -0700979 resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
Dirk Dougherty08032402014-02-15 10:14:35 -0800980 });
981
982 // Stack hover states
983 $('.section-card-menu').each(function(index, el) {
984 var height = $(el).height();
985 $(el).css({height:height+'px', position:'relative'});
986 var $cardInfo = $(el).find('.card-info');
987
988 $cardInfo.css({position: 'absolute', bottom:'0px', left:'0px', right:'0px', overflow:'visible'});
989 });
990
Scott Main20cf2a92014-04-02 21:57:20 -0700991 resizeNav(); // must resize once loading is finished
Dirk Dougherty08032402014-02-15 10:14:35 -0800992 });
993
994})();
Dirk Dougherty541b4942014-02-14 18:31:53 -0800995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009/* MISC LIBRARY FUNCTIONS */
1010
1011
1012
1013
1014
1015function toggle(obj, slide) {
1016 var ul = $("ul:first", obj);
1017 var li = ul.parent();
1018 if (li.hasClass("closed")) {
1019 if (slide) {
1020 ul.slideDown("fast");
1021 } else {
1022 ul.show();
1023 }
1024 li.removeClass("closed");
1025 li.addClass("open");
1026 $(".toggle-img", li).attr("title", "hide pages");
1027 } else {
1028 ul.slideUp("fast");
1029 li.removeClass("open");
1030 li.addClass("closed");
1031 $(".toggle-img", li).attr("title", "show pages");
1032 }
1033}
1034
1035
1036function buildToggleLists() {
1037 $(".toggle-list").each(
1038 function(i) {
1039 $("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
1040 $(this).addClass("closed");
1041 });
1042}
1043
1044
1045
1046function hideNestedItems(list, toggle) {
1047 $list = $(list);
1048 // hide nested lists
1049 if($list.hasClass('showing')) {
1050 $("li ol", $list).hide('fast');
1051 $list.removeClass('showing');
1052 // show nested lists
1053 } else {
1054 $("li ol", $list).show('fast');
1055 $list.addClass('showing');
1056 }
1057 $(".more,.less",$(toggle)).toggle();
1058}
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087/* REFERENCE NAV SWAP */
1088
1089
1090function getNavPref() {
1091 var v = readCookie('reference_nav');
1092 if (v != NAV_PREF_TREE) {
1093 v = NAV_PREF_PANELS;
1094 }
1095 return v;
1096}
1097
1098function chooseDefaultNav() {
1099 nav_pref = getNavPref();
1100 if (nav_pref == NAV_PREF_TREE) {
1101 $("#nav-panels").toggle();
1102 $("#panel-link").toggle();
1103 $("#nav-tree").toggle();
1104 $("#tree-link").toggle();
1105 }
1106}
1107
1108function swapNav() {
1109 if (nav_pref == NAV_PREF_TREE) {
1110 nav_pref = NAV_PREF_PANELS;
1111 } else {
1112 nav_pref = NAV_PREF_TREE;
1113 init_default_navtree(toRoot);
1114 }
1115 var date = new Date();
1116 date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
1117 writeCookie("nav", nav_pref, "reference", date.toGMTString());
1118
1119 $("#nav-panels").toggle();
1120 $("#panel-link").toggle();
1121 $("#nav-tree").toggle();
1122 $("#tree-link").toggle();
1123
1124 resizeNav();
1125
1126 // Gross nasty hack to make tree view show up upon first swap by setting height manually
1127 $("#nav-tree .jspContainer:visible")
1128 .css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
1129 // Another nasty hack to make the scrollbar appear now that we have height
1130 resizeNav();
1131
1132 if ($("#nav-tree").is(':visible')) {
1133 scrollIntoView("nav-tree");
1134 } else {
1135 scrollIntoView("packages-nav");
1136 scrollIntoView("classes-nav");
1137 }
1138}
1139
1140
1141
1142/* ############################################ */
1143/* ########## LOCALIZATION ############ */
1144/* ############################################ */
1145
1146function getBaseUri(uri) {
1147 var intlUrl = (uri.substring(0,6) == "/intl/");
1148 if (intlUrl) {
1149 base = uri.substring(uri.indexOf('intl/')+5,uri.length);
1150 base = base.substring(base.indexOf('/')+1, base.length);
1151 //alert("intl, returning base url: /" + base);
1152 return ("/" + base);
1153 } else {
1154 //alert("not intl, returning uri as found.");
1155 return uri;
1156 }
1157}
1158
1159function requestAppendHL(uri) {
1160//append "?hl=<lang> to an outgoing request (such as to blog)
1161 var lang = getLangPref();
1162 if (lang) {
1163 var q = 'hl=' + lang;
1164 uri += '?' + q;
1165 window.location = uri;
1166 return false;
1167 } else {
1168 return true;
1169 }
1170}
1171
1172
1173function changeNavLang(lang) {
1174 var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
1175 $links.each(function(i){ // for each link with a translation
1176 var $link = $(this);
1177 if (lang != "en") { // No need to worry about English, because a language change invokes new request
1178 // put the desired language from the attribute as the text
1179 $link.text($link.attr(lang+"-lang"))
1180 }
1181 });
1182}
1183
1184function changeLangPref(lang, submit) {
1185 var date = new Date();
1186 expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000)));
1187 // keep this for 50 years
1188 //alert("expires: " + expires)
1189 writeCookie("pref_lang", lang, null, expires);
1190
1191 // ####### TODO: Remove this condition once we're stable on devsite #######
1192 // This condition is only needed if we still need to support legacy GAE server
1193 if (devsite) {
1194 // Switch language when on Devsite server
1195 if (submit) {
1196 $("#setlang").submit();
1197 }
1198 } else {
1199 // Switch language when on legacy GAE server
1200 if (submit) {
1201 window.location = getBaseUri(location.pathname);
1202 }
1203 }
1204}
1205
1206function loadLangPref() {
1207 var lang = readCookie("pref_lang");
1208 if (lang != 0) {
1209 $("#language").find("option[value='"+lang+"']").attr("selected",true);
1210 }
1211}
1212
1213function getLangPref() {
1214 var lang = $("#language").find(":selected").attr("value");
1215 if (!lang) {
1216 lang = readCookie("pref_lang");
1217 }
1218 return (lang != 0) ? lang : 'en';
1219}
1220
1221/* ########## END LOCALIZATION ############ */
1222
1223
1224
1225
1226
1227
1228/* Used to hide and reveal supplemental content, such as long code samples.
1229 See the companion CSS in android-developer-docs.css */
1230function toggleContent(obj) {
1231 var div = $(obj).closest(".toggle-content");
1232 var toggleMe = $(".toggle-content-toggleme:eq(0)",div);
1233 if (div.hasClass("closed")) { // if it's closed, open it
1234 toggleMe.slideDown();
1235 $(".toggle-content-text:eq(0)", obj).toggle();
1236 div.removeClass("closed").addClass("open");
1237 $(".toggle-content-img:eq(0)", div).attr("title", "hide").attr("src", toRoot
1238 + "assets/images/triangle-opened.png");
1239 } else { // if it's open, close it
1240 toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
1241 $(".toggle-content-text:eq(0)", obj).toggle();
1242 div.removeClass("open").addClass("closed");
1243 div.find(".toggle-content").removeClass("open").addClass("closed")
1244 .find(".toggle-content-toggleme").hide();
1245 $(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
1246 + "assets/images/triangle-closed.png");
1247 });
1248 }
1249 return false;
1250}
1251
1252
1253/* New version of expandable content */
1254function toggleExpandable(link,id) {
1255 if($(id).is(':visible')) {
1256 $(id).slideUp();
1257 $(link).removeClass('expanded');
1258 } else {
1259 $(id).slideDown();
1260 $(link).addClass('expanded');
1261 }
1262}
1263
1264function hideExpandable(ids) {
1265 $(ids).slideUp();
1266 $(ids).prev('h4').find('a.expandable').removeClass('expanded');
1267}
1268
1269
1270
1271
1272
1273/*
1274 * Slideshow 1.0
1275 * Used on /index.html and /develop/index.html for carousel
1276 *
1277 * Sample usage:
1278 * HTML -
1279 * <div class="slideshow-container">
1280 * <a href="" class="slideshow-prev">Prev</a>
1281 * <a href="" class="slideshow-next">Next</a>
1282 * <ul>
1283 * <li class="item"><img src="images/marquee1.jpg"></li>
1284 * <li class="item"><img src="images/marquee2.jpg"></li>
1285 * <li class="item"><img src="images/marquee3.jpg"></li>
1286 * <li class="item"><img src="images/marquee4.jpg"></li>
1287 * </ul>
1288 * </div>
1289 *
1290 * <script type="text/javascript">
1291 * $('.slideshow-container').dacSlideshow({
1292 * auto: true,
1293 * btnPrev: '.slideshow-prev',
1294 * btnNext: '.slideshow-next'
1295 * });
1296 * </script>
1297 *
1298 * Options:
1299 * btnPrev: optional identifier for previous button
1300 * btnNext: optional identifier for next button
1301 * btnPause: optional identifier for pause button
1302 * auto: whether or not to auto-proceed
1303 * speed: animation speed
1304 * autoTime: time between auto-rotation
1305 * easing: easing function for transition
1306 * start: item to select by default
1307 * scroll: direction to scroll in
1308 * pagination: whether or not to include dotted pagination
1309 *
1310 */
1311
1312 (function($) {
1313 $.fn.dacSlideshow = function(o) {
1314
1315 //Options - see above
1316 o = $.extend({
1317 btnPrev: null,
1318 btnNext: null,
1319 btnPause: null,
1320 auto: true,
1321 speed: 500,
1322 autoTime: 12000,
1323 easing: null,
1324 start: 0,
1325 scroll: 1,
1326 pagination: true
1327
1328 }, o || {});
1329
1330 //Set up a carousel for each
1331 return this.each(function() {
1332
1333 var running = false;
1334 var animCss = o.vertical ? "top" : "left";
1335 var sizeCss = o.vertical ? "height" : "width";
1336 var div = $(this);
1337 var ul = $("ul", div);
1338 var tLi = $("li", ul);
1339 var tl = tLi.size();
1340 var timer = null;
1341
1342 var li = $("li", ul);
1343 var itemLength = li.size();
1344 var curr = o.start;
1345
1346 li.css({float: o.vertical ? "none" : "left"});
1347 ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
1348 div.css({position: "relative", "z-index": "2", left: "0px"});
1349
1350 var liSize = o.vertical ? height(li) : width(li);
1351 var ulSize = liSize * itemLength;
1352 var divSize = liSize;
1353
1354 li.css({width: li.width(), height: li.height()});
1355 ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
1356
1357 div.css(sizeCss, divSize+"px");
1358
1359 //Pagination
1360 if (o.pagination) {
1361 var pagination = $("<div class='pagination'></div>");
1362 var pag_ul = $("<ul></ul>");
1363 if (tl > 1) {
1364 for (var i=0;i<tl;i++) {
1365 var li = $("<li>"+i+"</li>");
1366 pag_ul.append(li);
1367 if (i==o.start) li.addClass('active');
1368 li.click(function() {
1369 go(parseInt($(this).text()));
1370 })
1371 }
1372 pagination.append(pag_ul);
1373 div.append(pagination);
1374 }
1375 }
1376
1377 //Previous button
1378 if(o.btnPrev)
1379 $(o.btnPrev).click(function(e) {
1380 e.preventDefault();
1381 return go(curr-o.scroll);
1382 });
1383
1384 //Next button
1385 if(o.btnNext)
1386 $(o.btnNext).click(function(e) {
1387 e.preventDefault();
1388 return go(curr+o.scroll);
1389 });
1390
1391 //Pause button
1392 if(o.btnPause)
1393 $(o.btnPause).click(function(e) {
1394 e.preventDefault();
1395 if ($(this).hasClass('paused')) {
1396 startRotateTimer();
1397 } else {
1398 pauseRotateTimer();
1399 }
1400 });
1401
1402 //Auto rotation
1403 if(o.auto) startRotateTimer();
1404
1405 function startRotateTimer() {
1406 clearInterval(timer);
1407 timer = setInterval(function() {
1408 if (curr == tl-1) {
1409 go(0);
1410 } else {
1411 go(curr+o.scroll);
1412 }
1413 }, o.autoTime);
1414 $(o.btnPause).removeClass('paused');
1415 }
1416
1417 function pauseRotateTimer() {
1418 clearInterval(timer);
1419 $(o.btnPause).addClass('paused');
1420 }
1421
1422 //Go to an item
1423 function go(to) {
1424 if(!running) {
1425
1426 if(to<0) {
1427 to = itemLength-1;
1428 } else if (to>itemLength-1) {
1429 to = 0;
1430 }
1431 curr = to;
1432
1433 running = true;
1434
1435 ul.animate(
1436 animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
1437 function() {
1438 running = false;
1439 }
1440 );
1441
1442 $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
1443 $( (curr-o.scroll<0 && o.btnPrev)
1444 ||
1445 (curr+o.scroll > itemLength && o.btnNext)
1446 ||
1447 []
1448 ).addClass("disabled");
1449
1450
1451 var nav_items = $('li', pagination);
1452 nav_items.removeClass('active');
1453 nav_items.eq(to).addClass('active');
1454
1455
1456 }
1457 if(o.auto) startRotateTimer();
1458 return false;
1459 };
1460 });
1461 };
1462
1463 function css(el, prop) {
1464 return parseInt($.css(el[0], prop)) || 0;
1465 };
1466 function width(el) {
1467 return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
1468 };
1469 function height(el) {
1470 return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
1471 };
1472
1473 })(jQuery);
1474
1475
1476/*
1477 * dacSlideshow 1.0
1478 * Used on develop/index.html for side-sliding tabs
1479 *
1480 * Sample usage:
1481 * HTML -
1482 * <div class="slideshow-container">
1483 * <a href="" class="slideshow-prev">Prev</a>
1484 * <a href="" class="slideshow-next">Next</a>
1485 * <ul>
1486 * <li class="item"><img src="images/marquee1.jpg"></li>
1487 * <li class="item"><img src="images/marquee2.jpg"></li>
1488 * <li class="item"><img src="images/marquee3.jpg"></li>
1489 * <li class="item"><img src="images/marquee4.jpg"></li>
1490 * </ul>
1491 * </div>
1492 *
1493 * <script type="text/javascript">
1494 * $('.slideshow-container').dacSlideshow({
1495 * auto: true,
1496 * btnPrev: '.slideshow-prev',
1497 * btnNext: '.slideshow-next'
1498 * });
1499 * </script>
1500 *
1501 * Options:
1502 * btnPrev: optional identifier for previous button
1503 * btnNext: optional identifier for next button
1504 * auto: whether or not to auto-proceed
1505 * speed: animation speed
1506 * autoTime: time between auto-rotation
1507 * easing: easing function for transition
1508 * start: item to select by default
1509 * scroll: direction to scroll in
1510 * pagination: whether or not to include dotted pagination
1511 *
1512 */
1513 (function($) {
1514 $.fn.dacTabbedList = function(o) {
1515
1516 //Options - see above
1517 o = $.extend({
1518 speed : 250,
1519 easing: null,
1520 nav_id: null,
1521 frame_id: null
1522 }, o || {});
1523
1524 //Set up a carousel for each
1525 return this.each(function() {
1526
1527 var curr = 0;
1528 var running = false;
1529 var animCss = "margin-left";
1530 var sizeCss = "width";
1531 var div = $(this);
1532
1533 var nav = $(o.nav_id, div);
1534 var nav_li = $("li", nav);
1535 var nav_size = nav_li.size();
1536 var frame = div.find(o.frame_id);
1537 var content_width = $(frame).find('ul').width();
1538 //Buttons
1539 $(nav_li).click(function(e) {
1540 go($(nav_li).index($(this)));
1541 })
1542
1543 //Go to an item
1544 function go(to) {
1545 if(!running) {
1546 curr = to;
1547 running = true;
1548
1549 frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
1550 function() {
1551 running = false;
1552 }
1553 );
1554
1555
1556 nav_li.removeClass('active');
1557 nav_li.eq(to).addClass('active');
1558
1559
1560 }
1561 return false;
1562 };
1563 });
1564 };
1565
1566 function css(el, prop) {
1567 return parseInt($.css(el[0], prop)) || 0;
1568 };
1569 function width(el) {
1570 return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
1571 };
1572 function height(el) {
1573 return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
1574 };
1575
1576 })(jQuery);
1577
1578
1579
1580
1581
1582/* ######################################################## */
1583/* ################ SEARCH SUGGESTIONS ################## */
1584/* ######################################################## */
1585
1586
1587
1588var gSelectedIndex = -1; // the index position of currently highlighted suggestion
1589var gSelectedColumn = -1; // which column of suggestion lists is currently focused
1590
1591var gMatches = new Array();
1592var gLastText = "";
1593var gInitialized = false;
1594var ROW_COUNT_FRAMEWORK = 20; // max number of results in list
1595var gListLength = 0;
1596
1597
1598var gGoogleMatches = new Array();
1599var ROW_COUNT_GOOGLE = 15; // max number of results in list
1600var gGoogleListLength = 0;
1601
1602var gDocsMatches = new Array();
1603var ROW_COUNT_DOCS = 100; // max number of results in list
1604var gDocsListLength = 0;
1605
1606function onSuggestionClick(link) {
1607 // When user clicks a suggested document, track it
1608 _gaq.push(['_trackEvent', 'Suggestion Click', 'clicked: ' + $(link).text(),
1609 'from: ' + $("#search_autocomplete").val()]);
1610}
1611
1612function set_item_selected($li, selected)
1613{
1614 if (selected) {
1615 $li.attr('class','jd-autocomplete jd-selected');
1616 } else {
1617 $li.attr('class','jd-autocomplete');
1618 }
1619}
1620
1621function set_item_values(toroot, $li, match)
1622{
1623 var $link = $('a',$li);
1624 $link.html(match.__hilabel || match.label);
1625 $link.attr('href',toroot + match.link);
1626}
1627
1628function set_item_values_jd(toroot, $li, match)
1629{
1630 var $link = $('a',$li);
1631 $link.html(match.title);
1632 $link.attr('href',toroot + match.url);
1633}
1634
1635function new_suggestion($list) {
1636 var $li = $("<li class='jd-autocomplete'></li>");
1637 $list.append($li);
1638
1639 $li.mousedown(function() {
1640 window.location = this.firstChild.getAttribute("href");
1641 });
1642 $li.mouseover(function() {
1643 $('.search_filtered_wrapper li').removeClass('jd-selected');
1644 $(this).addClass('jd-selected');
1645 gSelectedColumn = $(".search_filtered:visible").index($(this).closest('.search_filtered'));
1646 gSelectedIndex = $("li", $(".search_filtered:visible")[gSelectedColumn]).index(this);
1647 });
1648 $li.append("<a onclick='onSuggestionClick(this)'></a>");
1649 $li.attr('class','show-item');
1650 return $li;
1651}
1652
1653function sync_selection_table(toroot)
1654{
1655 var $li; //list item jquery object
1656 var i; //list item iterator
1657
1658 // if there are NO results at all, hide all columns
1659 if (!(gMatches.length > 0) && !(gGoogleMatches.length > 0) && !(gDocsMatches.length > 0)) {
1660 $('.suggest-card').hide(300);
1661 return;
1662 }
1663
1664 // if there are api results
1665 if ((gMatches.length > 0) || (gGoogleMatches.length > 0)) {
1666 // reveal suggestion list
1667 $('.suggest-card.dummy').show();
1668 $('.suggest-card.reference').show();
1669 var listIndex = 0; // list index position
1670
1671 // reset the lists
1672 $(".search_filtered_wrapper.reference li").remove();
1673
1674 // ########### ANDROID RESULTS #############
1675 if (gMatches.length > 0) {
1676
1677 // determine android results to show
1678 gListLength = gMatches.length < ROW_COUNT_FRAMEWORK ?
1679 gMatches.length : ROW_COUNT_FRAMEWORK;
1680 for (i=0; i<gListLength; i++) {
1681 var $li = new_suggestion($(".suggest-card.reference ul"));
1682 set_item_values(toroot, $li, gMatches[i]);
1683 set_item_selected($li, i == gSelectedIndex);
1684 }
1685 }
1686
1687 // ########### GOOGLE RESULTS #############
1688 if (gGoogleMatches.length > 0) {
1689 // show header for list
1690 $(".suggest-card.reference ul").append("<li class='header'>in Google Services:</li>");
1691
1692 // determine google results to show
1693 gGoogleListLength = gGoogleMatches.length < ROW_COUNT_GOOGLE ? gGoogleMatches.length : ROW_COUNT_GOOGLE;
1694 for (i=0; i<gGoogleListLength; i++) {
1695 var $li = new_suggestion($(".suggest-card.reference ul"));
1696 set_item_values(toroot, $li, gGoogleMatches[i]);
1697 set_item_selected($li, i == gSelectedIndex);
1698 }
1699 }
1700 } else {
1701 $('.suggest-card.reference').hide();
1702 $('.suggest-card.dummy').hide();
1703 }
1704
1705 // ########### JD DOC RESULTS #############
1706 if (gDocsMatches.length > 0) {
1707 // reset the lists
1708 $(".search_filtered_wrapper.docs li").remove();
1709
1710 // determine google results to show
1711 // NOTE: The order of the conditions below for the sugg.type MUST BE SPECIFIC:
1712 // The order must match the reverse order that each section appears as a card in
1713 // the suggestion UI... this may be only for the "develop" grouped items though.
1714 gDocsListLength = gDocsMatches.length < ROW_COUNT_DOCS ? gDocsMatches.length : ROW_COUNT_DOCS;
1715 for (i=0; i<gDocsListLength; i++) {
1716 var sugg = gDocsMatches[i];
1717 var $li;
1718 if (sugg.type == "design") {
1719 $li = new_suggestion($(".suggest-card.design ul"));
1720 } else
1721 if (sugg.type == "distribute") {
1722 $li = new_suggestion($(".suggest-card.distribute ul"));
1723 } else
1724 if (sugg.type == "samples") {
1725 $li = new_suggestion($(".suggest-card.develop .child-card.samples"));
1726 } else
1727 if (sugg.type == "training") {
1728 $li = new_suggestion($(".suggest-card.develop .child-card.training"));
1729 } else
1730 if (sugg.type == "about"||"guide"||"tools"||"google") {
1731 $li = new_suggestion($(".suggest-card.develop .child-card.guides"));
1732 } else {
1733 continue;
1734 }
1735
1736 set_item_values_jd(toroot, $li, sugg);
1737 set_item_selected($li, i == gSelectedIndex);
1738 }
1739
1740 // add heading and show or hide card
1741 if ($(".suggest-card.design li").length > 0) {
1742 $(".suggest-card.design ul").prepend("<li class='header'>Design:</li>");
1743 $(".suggest-card.design").show(300);
1744 } else {
1745 $('.suggest-card.design').hide(300);
1746 }
1747 if ($(".suggest-card.distribute li").length > 0) {
1748 $(".suggest-card.distribute ul").prepend("<li class='header'>Distribute:</li>");
1749 $(".suggest-card.distribute").show(300);
1750 } else {
1751 $('.suggest-card.distribute').hide(300);
1752 }
1753 if ($(".child-card.guides li").length > 0) {
1754 $(".child-card.guides").prepend("<li class='header'>Guides:</li>");
1755 $(".child-card.guides li").appendTo(".suggest-card.develop ul");
1756 }
1757 if ($(".child-card.training li").length > 0) {
1758 $(".child-card.training").prepend("<li class='header'>Training:</li>");
1759 $(".child-card.training li").appendTo(".suggest-card.develop ul");
1760 }
1761 if ($(".child-card.samples li").length > 0) {
1762 $(".child-card.samples").prepend("<li class='header'>Samples:</li>");
1763 $(".child-card.samples li").appendTo(".suggest-card.develop ul");
1764 }
1765
1766 if ($(".suggest-card.develop li").length > 0) {
1767 $(".suggest-card.develop").show(300);
1768 } else {
1769 $('.suggest-card.develop').hide(300);
1770 }
1771
1772 } else {
1773 $('.search_filtered_wrapper.docs .suggest-card:not(.dummy)').hide(300);
1774 }
1775}
1776
1777/** Called by the search input's onkeydown and onkeyup events.
1778 * Handles navigation with keyboard arrows, Enter key to invoke search,
1779 * otherwise invokes search suggestions on key-up event.
1780 * @param e The JS event
1781 * @param kd True if the event is key-down
1782 * @param toroot A string for the site's root path
1783 * @returns True if the event should bubble up
1784 */
1785function search_changed(e, kd, toroot)
1786{
1787 var currentLang = getLangPref();
1788 var search = document.getElementById("search_autocomplete");
1789 var text = search.value.replace(/(^ +)|( +$)/g, '');
1790 // get the ul hosting the currently selected item
1791 gSelectedColumn = gSelectedColumn >= 0 ? gSelectedColumn : 0;
1792 var $columns = $(".search_filtered_wrapper").find(".search_filtered:visible");
1793 var $selectedUl = $columns[gSelectedColumn];
1794
1795 // show/hide the close button
1796 if (text != '') {
1797 $(".search .close").removeClass("hide");
1798 } else {
1799 $(".search .close").addClass("hide");
1800 }
1801 // 27 = esc
1802 if (e.keyCode == 27) {
1803 // close all search results
1804 if (kd) $('.search .close').trigger('click');
1805 return true;
1806 }
1807 // 13 = enter
1808 else if (e.keyCode == 13) {
1809 if (gSelectedIndex < 0) {
1810 $('.suggest-card').hide();
1811 if ($("#searchResults").is(":hidden") && (search.value != "")) {
1812 // if results aren't showing (and text not empty), return true to allow search to execute
Dirk Dougherty08032402014-02-15 10:14:35 -08001813 $('body,html').animate({scrollTop:0}, '500', 'swing', function() { autoScrolling = false; });
Dirk Dougherty541b4942014-02-14 18:31:53 -08001814 return true;
1815 } else {
1816 // otherwise, results are already showing, so allow ajax to auto refresh the results
1817 // and ignore this Enter press to avoid the reload.
1818 return false;
1819 }
1820 } else if (kd && gSelectedIndex >= 0) {
1821 // click the link corresponding to selected item
1822 $("a",$("li",$selectedUl)[gSelectedIndex]).get()[0].click();
1823 return false;
1824 }
1825 }
1826 // Stop here if Google results are showing
1827 else if ($("#searchResults").is(":visible")) {
1828 return true;
1829 }
1830 // 38 UP ARROW
1831 else if (kd && (e.keyCode == 38)) {
1832 // if the next item is a header, skip it
1833 if ($($("li", $selectedUl)[gSelectedIndex-1]).hasClass("header")) {
1834 gSelectedIndex--;
1835 }
1836 if (gSelectedIndex >= 0) {
1837 $('li', $selectedUl).removeClass('jd-selected');
1838 gSelectedIndex--;
1839 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1840 // If user reaches top, reset selected column
1841 if (gSelectedIndex < 0) {
1842 gSelectedColumn = -1;
1843 }
1844 }
1845 return false;
1846 }
1847 // 40 DOWN ARROW
1848 else if (kd && (e.keyCode == 40)) {
1849 // if the next item is a header, skip it
1850 if ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header")) {
1851 gSelectedIndex++;
1852 }
1853 if ((gSelectedIndex < $("li", $selectedUl).length-1) ||
1854 ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header"))) {
1855 $('li', $selectedUl).removeClass('jd-selected');
1856 gSelectedIndex++;
1857 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1858 }
1859 return false;
1860 }
1861 // Consider left/right arrow navigation
1862 // NOTE: Order of suggest columns are reverse order (index position 0 is on right)
1863 else if (kd && $columns.length > 1 && gSelectedColumn >= 0) {
1864 // 37 LEFT ARROW
1865 // go left only if current column is not left-most column (last column)
1866 if (e.keyCode == 37 && gSelectedColumn < $columns.length - 1) {
1867 $('li', $selectedUl).removeClass('jd-selected');
1868 gSelectedColumn++;
1869 $selectedUl = $columns[gSelectedColumn];
1870 // keep or reset the selected item to last item as appropriate
1871 gSelectedIndex = gSelectedIndex >
1872 $("li", $selectedUl).length-1 ?
1873 $("li", $selectedUl).length-1 : gSelectedIndex;
1874 // if the corresponding item is a header, move down
1875 if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
1876 gSelectedIndex++;
1877 }
1878 // set item selected
1879 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1880 return false;
1881 }
1882 // 39 RIGHT ARROW
1883 // go right only if current column is not the right-most column (first column)
1884 else if (e.keyCode == 39 && gSelectedColumn > 0) {
1885 $('li', $selectedUl).removeClass('jd-selected');
1886 gSelectedColumn--;
1887 $selectedUl = $columns[gSelectedColumn];
1888 // keep or reset the selected item to last item as appropriate
1889 gSelectedIndex = gSelectedIndex >
1890 $("li", $selectedUl).length-1 ?
1891 $("li", $selectedUl).length-1 : gSelectedIndex;
1892 // if the corresponding item is a header, move down
1893 if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
1894 gSelectedIndex++;
1895 }
1896 // set item selected
1897 $('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
1898 return false;
1899 }
1900 }
1901
1902 // if key-up event and not arrow down/up/left/right,
1903 // read the search query and add suggestions to gMatches
1904 else if (!kd && (e.keyCode != 40)
1905 && (e.keyCode != 38)
1906 && (e.keyCode != 37)
1907 && (e.keyCode != 39)) {
1908 gSelectedIndex = -1;
1909 gMatches = new Array();
1910 matchedCount = 0;
1911 gGoogleMatches = new Array();
1912 matchedCountGoogle = 0;
1913 gDocsMatches = new Array();
1914 matchedCountDocs = 0;
1915
1916 // Search for Android matches
1917 for (var i=0; i<DATA.length; i++) {
1918 var s = DATA[i];
1919 if (text.length != 0 &&
1920 s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
1921 gMatches[matchedCount] = s;
1922 matchedCount++;
1923 }
1924 }
1925 rank_autocomplete_api_results(text, gMatches);
1926 for (var i=0; i<gMatches.length; i++) {
1927 var s = gMatches[i];
1928 }
1929
1930
1931 // Search for Google matches
1932 for (var i=0; i<GOOGLE_DATA.length; i++) {
1933 var s = GOOGLE_DATA[i];
1934 if (text.length != 0 &&
1935 s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
1936 gGoogleMatches[matchedCountGoogle] = s;
1937 matchedCountGoogle++;
1938 }
1939 }
1940 rank_autocomplete_api_results(text, gGoogleMatches);
1941 for (var i=0; i<gGoogleMatches.length; i++) {
1942 var s = gGoogleMatches[i];
1943 }
1944
1945 highlight_autocomplete_result_labels(text);
1946
1947
1948
1949 // Search for matching JD docs
1950 if (text.length >= 3) {
1951 // Regex to match only the beginning of a word
1952 var textRegex = new RegExp("\\b" + text.toLowerCase(), "g");
1953
1954
1955 // Search for Training classes
1956 for (var i=0; i<TRAINING_RESOURCES.length; i++) {
1957 // current search comparison, with counters for tag and title,
1958 // used later to improve ranking
1959 var s = TRAINING_RESOURCES[i];
1960 s.matched_tag = 0;
1961 s.matched_title = 0;
1962 var matched = false;
1963
1964 // Check if query matches any tags; work backwards toward 1 to assist ranking
1965 for (var j = s.keywords.length - 1; j >= 0; j--) {
1966 // it matches a tag
1967 if (s.keywords[j].toLowerCase().match(textRegex)) {
1968 matched = true;
1969 s.matched_tag = j + 1; // add 1 to index position
1970 }
1971 }
1972 // Don't consider doc title for lessons (only for class landing pages),
1973 // unless the lesson has a tag that already matches
1974 if ((s.lang == currentLang) &&
1975 (!(s.type == "training" && s.url.indexOf("index.html") == -1) || matched)) {
1976 // it matches the doc title
1977 if (s.title.toLowerCase().match(textRegex)) {
1978 matched = true;
1979 s.matched_title = 1;
1980 }
1981 }
1982 if (matched) {
1983 gDocsMatches[matchedCountDocs] = s;
1984 matchedCountDocs++;
1985 }
1986 }
1987
1988
1989 // Search for API Guides
1990 for (var i=0; i<GUIDE_RESOURCES.length; i++) {
1991 // current search comparison, with counters for tag and title,
1992 // used later to improve ranking
1993 var s = GUIDE_RESOURCES[i];
1994 s.matched_tag = 0;
1995 s.matched_title = 0;
1996 var matched = false;
1997
1998 // Check if query matches any tags; work backwards toward 1 to assist ranking
1999 for (var j = s.keywords.length - 1; j >= 0; j--) {
2000 // it matches a tag
2001 if (s.keywords[j].toLowerCase().match(textRegex)) {
2002 matched = true;
2003 s.matched_tag = j + 1; // add 1 to index position
2004 }
2005 }
2006 // Check if query matches the doc title, but only for current language
2007 if (s.lang == currentLang) {
2008 // if query matches the doc title
2009 if (s.title.toLowerCase().match(textRegex)) {
2010 matched = true;
2011 s.matched_title = 1;
2012 }
2013 }
2014 if (matched) {
2015 gDocsMatches[matchedCountDocs] = s;
2016 matchedCountDocs++;
2017 }
2018 }
2019
2020
2021 // Search for Tools Guides
2022 for (var i=0; i<TOOLS_RESOURCES.length; i++) {
2023 // current search comparison, with counters for tag and title,
2024 // used later to improve ranking
2025 var s = TOOLS_RESOURCES[i];
2026 s.matched_tag = 0;
2027 s.matched_title = 0;
2028 var matched = false;
2029
2030 // Check if query matches any tags; work backwards toward 1 to assist ranking
2031 for (var j = s.keywords.length - 1; j >= 0; j--) {
2032 // it matches a tag
2033 if (s.keywords[j].toLowerCase().match(textRegex)) {
2034 matched = true;
2035 s.matched_tag = j + 1; // add 1 to index position
2036 }
2037 }
2038 // Check if query matches the doc title, but only for current language
2039 if (s.lang == currentLang) {
2040 // if query matches the doc title
2041 if (s.title.toLowerCase().match(textRegex)) {
2042 matched = true;
2043 s.matched_title = 1;
2044 }
2045 }
2046 if (matched) {
2047 gDocsMatches[matchedCountDocs] = s;
2048 matchedCountDocs++;
2049 }
2050 }
2051
2052
2053 // Search for About docs
2054 for (var i=0; i<ABOUT_RESOURCES.length; i++) {
2055 // current search comparison, with counters for tag and title,
2056 // used later to improve ranking
2057 var s = ABOUT_RESOURCES[i];
2058 s.matched_tag = 0;
2059 s.matched_title = 0;
2060 var matched = false;
2061
2062 // Check if query matches any tags; work backwards toward 1 to assist ranking
2063 for (var j = s.keywords.length - 1; j >= 0; j--) {
2064 // it matches a tag
2065 if (s.keywords[j].toLowerCase().match(textRegex)) {
2066 matched = true;
2067 s.matched_tag = j + 1; // add 1 to index position
2068 }
2069 }
2070 // Check if query matches the doc title, but only for current language
2071 if (s.lang == currentLang) {
2072 // if query matches the doc title
2073 if (s.title.toLowerCase().match(textRegex)) {
2074 matched = true;
2075 s.matched_title = 1;
2076 }
2077 }
2078 if (matched) {
2079 gDocsMatches[matchedCountDocs] = s;
2080 matchedCountDocs++;
2081 }
2082 }
2083
2084
2085 // Search for Design guides
2086 for (var i=0; i<DESIGN_RESOURCES.length; i++) {
2087 // current search comparison, with counters for tag and title,
2088 // used later to improve ranking
2089 var s = DESIGN_RESOURCES[i];
2090 s.matched_tag = 0;
2091 s.matched_title = 0;
2092 var matched = false;
2093
2094 // Check if query matches any tags; work backwards toward 1 to assist ranking
2095 for (var j = s.keywords.length - 1; j >= 0; j--) {
2096 // it matches a tag
2097 if (s.keywords[j].toLowerCase().match(textRegex)) {
2098 matched = true;
2099 s.matched_tag = j + 1; // add 1 to index position
2100 }
2101 }
2102 // Check if query matches the doc title, but only for current language
2103 if (s.lang == currentLang) {
2104 // if query matches the doc title
2105 if (s.title.toLowerCase().match(textRegex)) {
2106 matched = true;
2107 s.matched_title = 1;
2108 }
2109 }
2110 if (matched) {
2111 gDocsMatches[matchedCountDocs] = s;
2112 matchedCountDocs++;
2113 }
2114 }
2115
2116
2117 // Search for Distribute guides
2118 for (var i=0; i<DISTRIBUTE_RESOURCES.length; i++) {
2119 // current search comparison, with counters for tag and title,
2120 // used later to improve ranking
2121 var s = DISTRIBUTE_RESOURCES[i];
2122 s.matched_tag = 0;
2123 s.matched_title = 0;
2124 var matched = false;
2125
2126 // Check if query matches any tags; work backwards toward 1 to assist ranking
2127 for (var j = s.keywords.length - 1; j >= 0; j--) {
2128 // it matches a tag
2129 if (s.keywords[j].toLowerCase().match(textRegex)) {
2130 matched = true;
2131 s.matched_tag = j + 1; // add 1 to index position
2132 }
2133 }
2134 // Check if query matches the doc title, but only for current language
2135 if (s.lang == currentLang) {
2136 // if query matches the doc title
2137 if (s.title.toLowerCase().match(textRegex)) {
2138 matched = true;
2139 s.matched_title = 1;
2140 }
2141 }
2142 if (matched) {
2143 gDocsMatches[matchedCountDocs] = s;
2144 matchedCountDocs++;
2145 }
2146 }
2147
2148
2149 // Search for Google guides
2150 for (var i=0; i<GOOGLE_RESOURCES.length; i++) {
2151 // current search comparison, with counters for tag and title,
2152 // used later to improve ranking
2153 var s = GOOGLE_RESOURCES[i];
2154 s.matched_tag = 0;
2155 s.matched_title = 0;
2156 var matched = false;
2157
2158 // Check if query matches any tags; work backwards toward 1 to assist ranking
2159 for (var j = s.keywords.length - 1; j >= 0; j--) {
2160 // it matches a tag
2161 if (s.keywords[j].toLowerCase().match(textRegex)) {
2162 matched = true;
2163 s.matched_tag = j + 1; // add 1 to index position
2164 }
2165 }
2166 // Check if query matches the doc title, but only for current language
2167 if (s.lang == currentLang) {
2168 // if query matches the doc title
2169 if (s.title.toLowerCase().match(textRegex)) {
2170 matched = true;
2171 s.matched_title = 1;
2172 }
2173 }
2174 if (matched) {
2175 gDocsMatches[matchedCountDocs] = s;
2176 matchedCountDocs++;
2177 }
2178 }
2179
2180
2181 // Search for Samples
2182 for (var i=0; i<SAMPLES_RESOURCES.length; i++) {
2183 // current search comparison, with counters for tag and title,
2184 // used later to improve ranking
2185 var s = SAMPLES_RESOURCES[i];
2186 s.matched_tag = 0;
2187 s.matched_title = 0;
2188 var matched = false;
2189 // Check if query matches any tags; work backwards toward 1 to assist ranking
2190 for (var j = s.keywords.length - 1; j >= 0; j--) {
2191 // it matches a tag
2192 if (s.keywords[j].toLowerCase().match(textRegex)) {
2193 matched = true;
2194 s.matched_tag = j + 1; // add 1 to index position
2195 }
2196 }
2197 // Check if query matches the doc title, but only for current language
2198 if (s.lang == currentLang) {
2199 // if query matches the doc title.t
2200 if (s.title.toLowerCase().match(textRegex)) {
2201 matched = true;
2202 s.matched_title = 1;
2203 }
2204 }
2205 if (matched) {
2206 gDocsMatches[matchedCountDocs] = s;
2207 matchedCountDocs++;
2208 }
2209 }
2210
2211 // Rank/sort all the matched pages
2212 rank_autocomplete_doc_results(text, gDocsMatches);
2213 }
2214
2215 // draw the suggestions
2216 sync_selection_table(toroot);
2217 return true; // allow the event to bubble up to the search api
2218 }
2219}
2220
2221/* Order the jd doc result list based on match quality */
2222function rank_autocomplete_doc_results(query, matches) {
2223 query = query || '';
2224 if (!matches || !matches.length)
2225 return;
2226
2227 var _resultScoreFn = function(match) {
2228 var score = 1.0;
2229
2230 // if the query matched a tag
2231 if (match.matched_tag > 0) {
2232 // multiply score by factor relative to position in tags list (max of 3)
2233 score *= 3 / match.matched_tag;
2234
2235 // if it also matched the title
2236 if (match.matched_title > 0) {
2237 score *= 2;
2238 }
2239 } else if (match.matched_title > 0) {
2240 score *= 3;
2241 }
2242
2243 return score;
2244 };
2245
2246 for (var i=0; i<matches.length; i++) {
2247 matches[i].__resultScore = _resultScoreFn(matches[i]);
2248 }
2249
2250 matches.sort(function(a,b){
2251 var n = b.__resultScore - a.__resultScore;
2252 if (n == 0) // lexicographical sort if scores are the same
2253 n = (a.label < b.label) ? -1 : 1;
2254 return n;
2255 });
2256}
2257
2258/* Order the result list based on match quality */
2259function rank_autocomplete_api_results(query, matches) {
2260 query = query || '';
2261 if (!matches || !matches.length)
2262 return;
2263
2264 // helper function that gets the last occurence index of the given regex
2265 // in the given string, or -1 if not found
2266 var _lastSearch = function(s, re) {
2267 if (s == '')
2268 return -1;
2269 var l = -1;
2270 var tmp;
2271 while ((tmp = s.search(re)) >= 0) {
2272 if (l < 0) l = 0;
2273 l += tmp;
2274 s = s.substr(tmp + 1);
2275 }
2276 return l;
2277 };
2278
2279 // helper function that counts the occurrences of a given character in
2280 // a given string
2281 var _countChar = function(s, c) {
2282 var n = 0;
2283 for (var i=0; i<s.length; i++)
2284 if (s.charAt(i) == c) ++n;
2285 return n;
2286 };
2287
2288 var queryLower = query.toLowerCase();
2289 var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
2290 var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
2291 var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
2292
2293 var _resultScoreFn = function(result) {
2294 // scores are calculated based on exact and prefix matches,
2295 // and then number of path separators (dots) from the last
2296 // match (i.e. favoring classes and deep package names)
2297 var score = 1.0;
2298 var labelLower = result.label.toLowerCase();
2299 var t;
2300 t = _lastSearch(labelLower, partExactAlnumRE);
2301 if (t >= 0) {
2302 // exact part match
2303 var partsAfter = _countChar(labelLower.substr(t + 1), '.');
2304 score *= 200 / (partsAfter + 1);
2305 } else {
2306 t = _lastSearch(labelLower, partPrefixAlnumRE);
2307 if (t >= 0) {
2308 // part prefix match
2309 var partsAfter = _countChar(labelLower.substr(t + 1), '.');
2310 score *= 20 / (partsAfter + 1);
2311 }
2312 }
2313
2314 return score;
2315 };
2316
2317 for (var i=0; i<matches.length; i++) {
2318 // if the API is deprecated, default score is 0; otherwise, perform scoring
2319 if (matches[i].deprecated == "true") {
2320 matches[i].__resultScore = 0;
2321 } else {
2322 matches[i].__resultScore = _resultScoreFn(matches[i]);
2323 }
2324 }
2325
2326 matches.sort(function(a,b){
2327 var n = b.__resultScore - a.__resultScore;
2328 if (n == 0) // lexicographical sort if scores are the same
2329 n = (a.label < b.label) ? -1 : 1;
2330 return n;
2331 });
2332}
2333
2334/* Add emphasis to part of string that matches query */
2335function highlight_autocomplete_result_labels(query) {
2336 query = query || '';
2337 if ((!gMatches || !gMatches.length) && (!gGoogleMatches || !gGoogleMatches.length))
2338 return;
2339
2340 var queryLower = query.toLowerCase();
2341 var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
2342 var queryRE = new RegExp(
2343 '(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
2344 for (var i=0; i<gMatches.length; i++) {
2345 gMatches[i].__hilabel = gMatches[i].label.replace(
2346 queryRE, '<b>$1</b>');
2347 }
2348 for (var i=0; i<gGoogleMatches.length; i++) {
2349 gGoogleMatches[i].__hilabel = gGoogleMatches[i].label.replace(
2350 queryRE, '<b>$1</b>');
2351 }
2352}
2353
2354function search_focus_changed(obj, focused)
2355{
2356 if (!focused) {
2357 if(obj.value == ""){
2358 $(".search .close").addClass("hide");
2359 }
2360 $(".suggest-card").hide();
2361 }
2362}
2363
2364function submit_search() {
2365 var query = document.getElementById('search_autocomplete').value;
2366 location.hash = 'q=' + query;
2367 loadSearchResults();
2368 $("#searchResults").slideDown('slow');
2369 return false;
2370}
2371
2372
2373function hideResults() {
2374 $("#searchResults").slideUp();
2375 $(".search .close").addClass("hide");
2376 location.hash = '';
2377
2378 $("#search_autocomplete").val("").blur();
2379
2380 // reset the ajax search callback to nothing, so results don't appear unless ENTER
2381 searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
2382
2383 // forcefully regain key-up event control (previously jacked by search api)
2384 $("#search_autocomplete").keyup(function(event) {
2385 return search_changed(event, false, toRoot);
2386 });
2387
2388 return false;
2389}
2390
2391
2392
2393/* ########################################################## */
2394/* ################ CUSTOM SEARCH ENGINE ################## */
2395/* ########################################################## */
2396
2397var searchControl;
2398google.load('search', '1', {"callback" : function() {
2399 searchControl = new google.search.SearchControl();
2400 } });
2401
2402function loadSearchResults() {
2403 document.getElementById("search_autocomplete").style.color = "#000";
2404
2405 searchControl = new google.search.SearchControl();
2406
2407 // use our existing search form and use tabs when multiple searchers are used
2408 drawOptions = new google.search.DrawOptions();
2409 drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
2410 drawOptions.setInput(document.getElementById("search_autocomplete"));
2411
2412 // configure search result options
2413 searchOptions = new google.search.SearcherOptions();
2414 searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
2415
2416 // configure each of the searchers, for each tab
2417 devSiteSearcher = new google.search.WebSearch();
2418 devSiteSearcher.setUserDefinedLabel("All");
2419 devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
2420
2421 designSearcher = new google.search.WebSearch();
2422 designSearcher.setUserDefinedLabel("Design");
2423 designSearcher.setSiteRestriction("http://developer.android.com/design/");
2424
2425 trainingSearcher = new google.search.WebSearch();
2426 trainingSearcher.setUserDefinedLabel("Training");
2427 trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
2428
2429 guidesSearcher = new google.search.WebSearch();
2430 guidesSearcher.setUserDefinedLabel("Guides");
2431 guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
2432
2433 referenceSearcher = new google.search.WebSearch();
2434 referenceSearcher.setUserDefinedLabel("Reference");
2435 referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
2436
2437 googleSearcher = new google.search.WebSearch();
2438 googleSearcher.setUserDefinedLabel("Google Services");
2439 googleSearcher.setSiteRestriction("http://developer.android.com/google/");
2440
2441 blogSearcher = new google.search.WebSearch();
2442 blogSearcher.setUserDefinedLabel("Blog");
2443 blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
2444
2445 // add each searcher to the search control
2446 searchControl.addSearcher(devSiteSearcher, searchOptions);
2447 searchControl.addSearcher(designSearcher, searchOptions);
2448 searchControl.addSearcher(trainingSearcher, searchOptions);
2449 searchControl.addSearcher(guidesSearcher, searchOptions);
2450 searchControl.addSearcher(referenceSearcher, searchOptions);
2451 searchControl.addSearcher(googleSearcher, searchOptions);
2452 searchControl.addSearcher(blogSearcher, searchOptions);
2453
2454 // configure result options
2455 searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
2456 searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
2457 searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
2458 searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
2459
2460 // upon ajax search, refresh the url and search title
2461 searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
2462 updateResultTitle(query);
2463 var query = document.getElementById('search_autocomplete').value;
2464 location.hash = 'q=' + query;
2465 });
2466
2467 // once search results load, set up click listeners
2468 searchControl.setSearchCompleteCallback(this, function(control, searcher, query) {
2469 addResultClickListeners();
2470 });
2471
2472 // draw the search results box
2473 searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
2474
2475 // get query and execute the search
2476 searchControl.execute(decodeURI(getQuery(location.hash)));
2477
2478 document.getElementById("search_autocomplete").focus();
2479 addTabListeners();
2480}
2481// End of loadSearchResults
2482
2483
2484google.setOnLoadCallback(function(){
2485 if (location.hash.indexOf("q=") == -1) {
2486 // if there's no query in the url, don't search and make sure results are hidden
2487 $('#searchResults').hide();
2488 return;
2489 } else {
2490 // first time loading search results for this page
2491 $('#searchResults').slideDown('slow');
2492 $(".search .close").removeClass("hide");
2493 loadSearchResults();
2494 }
2495}, true);
2496
2497// when an event on the browser history occurs (back, forward, load) requery hash and do search
2498$(window).hashchange( function(){
2499 // Exit if the hash isn't a search query or there's an error in the query
2500 if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
2501 // If the results pane is open, close it.
2502 if (!$("#searchResults").is(":hidden")) {
2503 hideResults();
2504 }
2505 return;
2506 }
2507
2508 // Otherwise, we have a search to do
2509 var query = decodeURI(getQuery(location.hash));
2510 searchControl.execute(query);
2511 $('#searchResults').slideDown('slow');
2512 $("#search_autocomplete").focus();
2513 $(".search .close").removeClass("hide");
2514
2515 updateResultTitle(query);
2516});
2517
2518function updateResultTitle(query) {
2519 $("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
2520}
2521
2522// forcefully regain key-up event control (previously jacked by search api)
2523$("#search_autocomplete").keyup(function(event) {
2524 return search_changed(event, false, toRoot);
2525});
2526
2527// add event listeners to each tab so we can track the browser history
2528function addTabListeners() {
2529 var tabHeaders = $(".gsc-tabHeader");
2530 for (var i = 0; i < tabHeaders.length; i++) {
2531 $(tabHeaders[i]).attr("id",i).click(function() {
2532 /*
2533 // make a copy of the page numbers for the search left pane
2534 setTimeout(function() {
2535 // remove any residual page numbers
2536 $('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
2537 // move the page numbers to the left position; make a clone,
2538 // because the element is drawn to the DOM only once
2539 // and because we're going to remove it (previous line),
2540 // we need it to be available to move again as the user navigates
2541 $('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
2542 .clone().appendTo('#searchResults .gsc-tabsArea');
2543 }, 200);
2544 */
2545 });
2546 }
2547 setTimeout(function(){$(tabHeaders[0]).click()},200);
2548}
2549
2550// add analytics tracking events to each result link
2551function addResultClickListeners() {
2552 $("#searchResults a.gs-title").each(function(index, link) {
2553 // When user clicks enter for Google search results, track it
2554 $(link).click(function() {
2555 _gaq.push(['_trackEvent', 'Google Click', 'clicked: ' + $(this).text(),
2556 'from: ' + $("#search_autocomplete").val()]);
2557 });
2558 });
2559}
2560
2561
2562function getQuery(hash) {
2563 var queryParts = hash.split('=');
2564 return queryParts[1];
2565}
2566
2567/* returns the given string with all HTML brackets converted to entities
2568 TODO: move this to the site's JS library */
2569function escapeHTML(string) {
2570 return string.replace(/</g,"&lt;")
2571 .replace(/>/g,"&gt;");
2572}
2573
2574
2575
2576
2577
2578
2579
2580/* ######################################################## */
2581/* ################# JAVADOC REFERENCE ################### */
2582/* ######################################################## */
2583
2584/* Initialize some droiddoc stuff, but only if we're in the reference */
2585if (location.pathname.indexOf("/reference") == 0) {
2586 if(!(location.pathname.indexOf("/reference-gms/packages.html") == 0)
2587 && !(location.pathname.indexOf("/reference-gcm/packages.html") == 0)
2588 && !(location.pathname.indexOf("/reference/com/google") == 0)) {
2589 $(document).ready(function() {
2590 // init available apis based on user pref
2591 changeApiLevel();
2592 initSidenavHeightResize()
2593 });
2594 }
2595}
2596
2597var API_LEVEL_COOKIE = "api_level";
2598var minLevel = 1;
2599var maxLevel = 1;
2600
2601/******* SIDENAV DIMENSIONS ************/
2602
2603 function initSidenavHeightResize() {
2604 // Change the drag bar size to nicely fit the scrollbar positions
2605 var $dragBar = $(".ui-resizable-s");
2606 $dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
2607
2608 $( "#resize-packages-nav" ).resizable({
2609 containment: "#nav-panels",
2610 handles: "s",
2611 alsoResize: "#packages-nav",
2612 resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
2613 stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
2614 });
2615
2616 }
2617
2618function updateSidenavFixedWidth() {
2619 if (!navBarIsFixed) return;
2620 $('#devdoc-nav').css({
2621 'width' : $('#side-nav').css('width'),
2622 'margin' : $('#side-nav').css('margin')
2623 });
2624 $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
2625
2626 initSidenavHeightResize();
2627}
2628
2629function updateSidenavFullscreenWidth() {
2630 if (!navBarIsFixed) return;
2631 $('#devdoc-nav').css({
2632 'width' : $('#side-nav').css('width'),
2633 'margin' : $('#side-nav').css('margin')
2634 });
2635 $('#devdoc-nav .totop').css({'left': 'inherit'});
2636
2637 initSidenavHeightResize();
2638}
2639
2640function buildApiLevelSelector() {
2641 maxLevel = SINCE_DATA.length;
2642 var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
2643 userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
2644
2645 minLevel = parseInt($("#doc-api-level").attr("class"));
2646 // Handle provisional api levels; the provisional level will always be the highest possible level
2647 // Provisional api levels will also have a length; other stuff that's just missing a level won't,
2648 // so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
2649 if (isNaN(minLevel) && minLevel.length) {
2650 minLevel = maxLevel;
2651 }
2652 var select = $("#apiLevelSelector").html("").change(changeApiLevel);
2653 for (var i = maxLevel-1; i >= 0; i--) {
2654 var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
2655 // if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
2656 select.append(option);
2657 }
2658
2659 // get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
2660 var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
2661 selectedLevelItem.setAttribute('selected',true);
2662}
2663
2664function changeApiLevel() {
2665 maxLevel = SINCE_DATA.length;
2666 var selectedLevel = maxLevel;
2667
2668 selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
2669 toggleVisisbleApis(selectedLevel, "body");
2670
2671 var date = new Date();
2672 date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
2673 var expiration = date.toGMTString();
2674 writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
2675
2676 if (selectedLevel < minLevel) {
2677 var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
2678 $("#naMessage").show().html("<div><p><strong>This " + thing
2679 + " requires API level " + minLevel + " or higher.</strong></p>"
2680 + "<p>This document is hidden because your selected API level for the documentation is "
2681 + selectedLevel + ". You can change the documentation API level with the selector "
2682 + "above the left navigation.</p>"
2683 + "<p>For more information about specifying the API level your app requires, "
2684 + "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
2685 + ">Supporting Different Platform Versions</a>.</p>"
2686 + "<input type='button' value='OK, make this page visible' "
2687 + "title='Change the API level to " + minLevel + "' "
2688 + "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
2689 + "</div>");
2690 } else {
2691 $("#naMessage").hide();
2692 }
2693}
2694
2695function toggleVisisbleApis(selectedLevel, context) {
2696 var apis = $(".api",context);
2697 apis.each(function(i) {
2698 var obj = $(this);
2699 var className = obj.attr("class");
2700 var apiLevelIndex = className.lastIndexOf("-")+1;
2701 var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
2702 apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
2703 var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
2704 if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
2705 return;
2706 }
2707 apiLevel = parseInt(apiLevel);
2708
2709 // Handle provisional api levels; if this item's level is the provisional one, set it to the max
2710 var selectedLevelNum = parseInt(selectedLevel)
2711 var apiLevelNum = parseInt(apiLevel);
2712 if (isNaN(apiLevelNum)) {
2713 apiLevelNum = maxLevel;
2714 }
2715
2716 // Grey things out that aren't available and give a tooltip title
2717 if (apiLevelNum > selectedLevelNum) {
2718 obj.addClass("absent").attr("title","Requires API Level \""
2719 + apiLevel + "\" or higher. To reveal, change the target API level "
2720 + "above the left navigation.");
2721 }
2722 else obj.removeClass("absent").removeAttr("title");
2723 });
2724}
2725
2726
2727
2728
2729/* ################# SIDENAV TREE VIEW ################### */
2730
2731function new_node(me, mom, text, link, children_data, api_level)
2732{
2733 var node = new Object();
2734 node.children = Array();
2735 node.children_data = children_data;
2736 node.depth = mom.depth + 1;
2737
2738 node.li = document.createElement("li");
2739 mom.get_children_ul().appendChild(node.li);
2740
2741 node.label_div = document.createElement("div");
2742 node.label_div.className = "label";
2743 if (api_level != null) {
2744 $(node.label_div).addClass("api");
2745 $(node.label_div).addClass("api-level-"+api_level);
2746 }
2747 node.li.appendChild(node.label_div);
2748
2749 if (children_data != null) {
2750 node.expand_toggle = document.createElement("a");
2751 node.expand_toggle.href = "javascript:void(0)";
2752 node.expand_toggle.onclick = function() {
2753 if (node.expanded) {
2754 $(node.get_children_ul()).slideUp("fast");
2755 node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
2756 node.expanded = false;
2757 } else {
2758 expand_node(me, node);
2759 }
2760 };
2761 node.label_div.appendChild(node.expand_toggle);
2762
2763 node.plus_img = document.createElement("img");
2764 node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
2765 node.plus_img.className = "plus";
2766 node.plus_img.width = "8";
2767 node.plus_img.border = "0";
2768 node.expand_toggle.appendChild(node.plus_img);
2769
2770 node.expanded = false;
2771 }
2772
2773 var a = document.createElement("a");
2774 node.label_div.appendChild(a);
2775 node.label = document.createTextNode(text);
2776 a.appendChild(node.label);
2777 if (link) {
2778 a.href = me.toroot + link;
2779 } else {
2780 if (children_data != null) {
2781 a.className = "nolink";
2782 a.href = "javascript:void(0)";
2783 a.onclick = node.expand_toggle.onclick;
2784 // This next line shouldn't be necessary. I'll buy a beer for the first
2785 // person who figures out how to remove this line and have the link
2786 // toggle shut on the first try. --joeo@android.com
2787 node.expanded = false;
2788 }
2789 }
2790
2791
2792 node.children_ul = null;
2793 node.get_children_ul = function() {
2794 if (!node.children_ul) {
2795 node.children_ul = document.createElement("ul");
2796 node.children_ul.className = "children_ul";
2797 node.children_ul.style.display = "none";
2798 node.li.appendChild(node.children_ul);
2799 }
2800 return node.children_ul;
2801 };
2802
2803 return node;
2804}
2805
2806
2807
2808
2809function expand_node(me, node)
2810{
2811 if (node.children_data && !node.expanded) {
2812 if (node.children_visited) {
2813 $(node.get_children_ul()).slideDown("fast");
2814 } else {
2815 get_node(me, node);
2816 if ($(node.label_div).hasClass("absent")) {
2817 $(node.get_children_ul()).addClass("absent");
2818 }
2819 $(node.get_children_ul()).slideDown("fast");
2820 }
2821 node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
2822 node.expanded = true;
2823
2824 // perform api level toggling because new nodes are new to the DOM
2825 var selectedLevel = $("#apiLevelSelector option:selected").val();
2826 toggleVisisbleApis(selectedLevel, "#side-nav");
2827 }
2828}
2829
2830function get_node(me, mom)
2831{
2832 mom.children_visited = true;
2833 for (var i in mom.children_data) {
2834 var node_data = mom.children_data[i];
2835 mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
2836 node_data[2], node_data[3]);
2837 }
2838}
2839
2840function this_page_relative(toroot)
2841{
2842 var full = document.location.pathname;
2843 var file = "";
2844 if (toroot.substr(0, 1) == "/") {
2845 if (full.substr(0, toroot.length) == toroot) {
2846 return full.substr(toroot.length);
2847 } else {
2848 // the file isn't under toroot. Fail.
2849 return null;
2850 }
2851 } else {
2852 if (toroot != "./") {
2853 toroot = "./" + toroot;
2854 }
2855 do {
2856 if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
2857 var pos = full.lastIndexOf("/");
2858 file = full.substr(pos) + file;
2859 full = full.substr(0, pos);
2860 toroot = toroot.substr(0, toroot.length-3);
2861 }
2862 } while (toroot != "" && toroot != "/");
2863 return file.substr(1);
2864 }
2865}
2866
2867function find_page(url, data)
2868{
2869 var nodes = data;
2870 var result = null;
2871 for (var i in nodes) {
2872 var d = nodes[i];
2873 if (d[1] == url) {
2874 return new Array(i);
2875 }
2876 else if (d[2] != null) {
2877 result = find_page(url, d[2]);
2878 if (result != null) {
2879 return (new Array(i).concat(result));
2880 }
2881 }
2882 }
2883 return null;
2884}
2885
2886function init_default_navtree(toroot) {
2887 // load json file for navtree data
2888 $.getScript(toRoot + 'navtree_data.js', function(data, textStatus, jqxhr) {
2889 // when the file is loaded, initialize the tree
2890 if(jqxhr.status === 200) {
2891 init_navtree("tree-list", toroot, NAVTREE_DATA);
2892 }
2893 });
2894
2895 // perform api level toggling because because the whole tree is new to the DOM
2896 var selectedLevel = $("#apiLevelSelector option:selected").val();
2897 toggleVisisbleApis(selectedLevel, "#side-nav");
2898}
2899
2900function init_navtree(navtree_id, toroot, root_nodes)
2901{
2902 var me = new Object();
2903 me.toroot = toroot;
2904 me.node = new Object();
2905
2906 me.node.li = document.getElementById(navtree_id);
2907 me.node.children_data = root_nodes;
2908 me.node.children = new Array();
2909 me.node.children_ul = document.createElement("ul");
2910 me.node.get_children_ul = function() { return me.node.children_ul; };
2911 //me.node.children_ul.className = "children_ul";
2912 me.node.li.appendChild(me.node.children_ul);
2913 me.node.depth = 0;
2914
2915 get_node(me, me.node);
2916
2917 me.this_page = this_page_relative(toroot);
2918 me.breadcrumbs = find_page(me.this_page, root_nodes);
2919 if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
2920 var mom = me.node;
2921 for (var i in me.breadcrumbs) {
2922 var j = me.breadcrumbs[i];
2923 mom = mom.children[j];
2924 expand_node(me, mom);
2925 }
2926 mom.label_div.className = mom.label_div.className + " selected";
2927 addLoadEvent(function() {
2928 scrollIntoView("nav-tree");
2929 });
2930 }
2931}
2932
2933
2934
2935
2936
2937
2938
2939
2940/* TODO: eliminate redundancy with non-google functions */
2941function init_google_navtree(navtree_id, toroot, root_nodes)
2942{
2943 var me = new Object();
2944 me.toroot = toroot;
2945 me.node = new Object();
2946
2947 me.node.li = document.getElementById(navtree_id);
2948 me.node.children_data = root_nodes;
2949 me.node.children = new Array();
2950 me.node.children_ul = document.createElement("ul");
2951 me.node.get_children_ul = function() { return me.node.children_ul; };
2952 //me.node.children_ul.className = "children_ul";
2953 me.node.li.appendChild(me.node.children_ul);
2954 me.node.depth = 0;
2955
2956 get_google_node(me, me.node);
2957}
2958
2959function new_google_node(me, mom, text, link, children_data, api_level)
2960{
2961 var node = new Object();
2962 var child;
2963 node.children = Array();
2964 node.children_data = children_data;
2965 node.depth = mom.depth + 1;
2966 node.get_children_ul = function() {
2967 if (!node.children_ul) {
2968 node.children_ul = document.createElement("ul");
2969 node.children_ul.className = "tree-list-children";
2970 node.li.appendChild(node.children_ul);
2971 }
2972 return node.children_ul;
2973 };
2974 node.li = document.createElement("li");
2975
2976 mom.get_children_ul().appendChild(node.li);
2977
2978
2979 if(link) {
2980 child = document.createElement("a");
2981
2982 }
2983 else {
2984 child = document.createElement("span");
2985 child.className = "tree-list-subtitle";
2986
2987 }
2988 if (children_data != null) {
2989 node.li.className="nav-section";
2990 node.label_div = document.createElement("div");
2991 node.label_div.className = "nav-section-header-ref";
2992 node.li.appendChild(node.label_div);
2993 get_google_node(me, node);
2994 node.label_div.appendChild(child);
2995 }
2996 else {
2997 node.li.appendChild(child);
2998 }
2999 if(link) {
3000 child.href = me.toroot + link;
3001 }
3002 node.label = document.createTextNode(text);
3003 child.appendChild(node.label);
3004
3005 node.children_ul = null;
3006
3007 return node;
3008}
3009
3010function get_google_node(me, mom)
3011{
3012 mom.children_visited = true;
3013 var linkText;
3014 for (var i in mom.children_data) {
3015 var node_data = mom.children_data[i];
3016 linkText = node_data[0];
3017
3018 if(linkText.match("^"+"com.google.android")=="com.google.android"){
3019 linkText = linkText.substr(19, linkText.length);
3020 }
3021 mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
3022 node_data[2], node_data[3]);
3023 }
3024}
3025
3026
3027
3028
3029
3030
3031/****** NEW version of script to build google and sample navs dynamically ******/
3032// TODO: update Google reference docs to tolerate this new implementation
3033
3034var NODE_NAME = 0;
3035var NODE_HREF = 1;
3036var NODE_GROUP = 2;
3037var NODE_TAGS = 3;
3038var NODE_CHILDREN = 4;
3039
3040function init_google_navtree2(navtree_id, data)
3041{
3042 var $containerUl = $("#"+navtree_id);
3043 for (var i in data) {
3044 var node_data = data[i];
3045 $containerUl.append(new_google_node2(node_data));
3046 }
3047
3048 // Make all third-generation list items 'sticky' to prevent them from collapsing
3049 $containerUl.find('li li li.nav-section').addClass('sticky');
3050
3051 initExpandableNavItems("#"+navtree_id);
3052}
3053
3054function new_google_node2(node_data)
3055{
3056 var linkText = node_data[NODE_NAME];
3057 if(linkText.match("^"+"com.google.android")=="com.google.android"){
3058 linkText = linkText.substr(19, linkText.length);
3059 }
3060 var $li = $('<li>');
3061 var $a;
3062 if (node_data[NODE_HREF] != null) {
3063 $a = $('<a href="' + toRoot + node_data[NODE_HREF] + '" title="' + linkText + '" >'
3064 + linkText + '</a>');
3065 } else {
3066 $a = $('<a href="#" onclick="return false;" title="' + linkText + '" >'
3067 + linkText + '/</a>');
3068 }
3069 var $childUl = $('<ul>');
3070 if (node_data[NODE_CHILDREN] != null) {
3071 $li.addClass("nav-section");
3072 $a = $('<div class="nav-section-header">').append($a);
3073 if (node_data[NODE_HREF] == null) $a.addClass('empty');
3074
3075 for (var i in node_data[NODE_CHILDREN]) {
3076 var child_node_data = node_data[NODE_CHILDREN][i];
3077 $childUl.append(new_google_node2(child_node_data));
3078 }
3079 $li.append($childUl);
3080 }
3081 $li.prepend($a);
3082
3083 return $li;
3084}
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096function showGoogleRefTree() {
3097 init_default_google_navtree(toRoot);
3098 init_default_gcm_navtree(toRoot);
3099}
3100
3101function init_default_google_navtree(toroot) {
3102 // load json file for navtree data
3103 $.getScript(toRoot + 'gms_navtree_data.js', function(data, textStatus, jqxhr) {
3104 // when the file is loaded, initialize the tree
3105 if(jqxhr.status === 200) {
3106 init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
3107 highlightSidenav();
3108 resizeNav();
3109 }
3110 });
3111}
3112
3113function init_default_gcm_navtree(toroot) {
3114 // load json file for navtree data
3115 $.getScript(toRoot + 'gcm_navtree_data.js', function(data, textStatus, jqxhr) {
3116 // when the file is loaded, initialize the tree
3117 if(jqxhr.status === 200) {
3118 init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
3119 highlightSidenav();
3120 resizeNav();
3121 }
3122 });
3123}
3124
3125function showSamplesRefTree() {
3126 init_default_samples_navtree(toRoot);
3127}
3128
3129function init_default_samples_navtree(toroot) {
3130 // load json file for navtree data
3131 $.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
3132 // when the file is loaded, initialize the tree
3133 if(jqxhr.status === 200) {
3134 // hack to remove the "about the samples" link then put it back in
3135 // after we nuke the list to remove the dummy static list of samples
3136 var $firstLi = $("#nav.samples-nav > li:first-child").clone();
3137 $("#nav.samples-nav").empty();
3138 $("#nav.samples-nav").append($firstLi);
3139
3140 init_google_navtree2("nav.samples-nav", SAMPLES_NAVTREE_DATA);
3141 highlightSidenav();
3142 resizeNav();
3143 if ($("#jd-content #samples").length) {
3144 showSamples();
3145 }
3146 }
3147 });
3148}
3149
3150/* TOGGLE INHERITED MEMBERS */
3151
3152/* Toggle an inherited class (arrow toggle)
3153 * @param linkObj The link that was clicked.
3154 * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
3155 * 'null' to simply toggle.
3156 */
3157function toggleInherited(linkObj, expand) {
3158 var base = linkObj.getAttribute("id");
3159 var list = document.getElementById(base + "-list");
3160 var summary = document.getElementById(base + "-summary");
3161 var trigger = document.getElementById(base + "-trigger");
3162 var a = $(linkObj);
3163 if ( (expand == null && a.hasClass("closed")) || expand ) {
3164 list.style.display = "none";
3165 summary.style.display = "block";
3166 trigger.src = toRoot + "assets/images/triangle-opened.png";
3167 a.removeClass("closed");
3168 a.addClass("opened");
3169 } else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
3170 list.style.display = "block";
3171 summary.style.display = "none";
3172 trigger.src = toRoot + "assets/images/triangle-closed.png";
3173 a.removeClass("opened");
3174 a.addClass("closed");
3175 }
3176 return false;
3177}
3178
3179/* Toggle all inherited classes in a single table (e.g. all inherited methods)
3180 * @param linkObj The link that was clicked.
3181 * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
3182 * 'null' to simply toggle.
3183 */
3184function toggleAllInherited(linkObj, expand) {
3185 var a = $(linkObj);
3186 var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
3187 var expandos = $(".jd-expando-trigger", table);
3188 if ( (expand == null && a.text() == "[Expand]") || expand ) {
3189 expandos.each(function(i) {
3190 toggleInherited(this, true);
3191 });
3192 a.text("[Collapse]");
3193 } else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
3194 expandos.each(function(i) {
3195 toggleInherited(this, false);
3196 });
3197 a.text("[Expand]");
3198 }
3199 return false;
3200}
3201
3202/* Toggle all inherited members in the class (link in the class title)
3203 */
3204function toggleAllClassInherited() {
3205 var a = $("#toggleAllClassInherited"); // get toggle link from class title
3206 var toggles = $(".toggle-all", $("#body-content"));
3207 if (a.text() == "[Expand All]") {
3208 toggles.each(function(i) {
3209 toggleAllInherited(this, true);
3210 });
3211 a.text("[Collapse All]");
3212 } else {
3213 toggles.each(function(i) {
3214 toggleAllInherited(this, false);
3215 });
3216 a.text("[Expand All]");
3217 }
3218 return false;
3219}
3220
3221/* Expand all inherited members in the class. Used when initiating page search */
3222function ensureAllInheritedExpanded() {
3223 var toggles = $(".toggle-all", $("#body-content"));
3224 toggles.each(function(i) {
3225 toggleAllInherited(this, true);
3226 });
3227 $("#toggleAllClassInherited").text("[Collapse All]");
3228}
3229
3230
3231/* HANDLE KEY EVENTS
3232 * - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
3233 */
3234var agent = navigator['userAgent'].toLowerCase();
3235var mac = agent.indexOf("macintosh") != -1;
3236
3237$(document).keydown( function(e) {
3238var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
3239 if (control && e.which == 70) { // 70 is "F"
3240 ensureAllInheritedExpanded();
3241 }
3242});
3243
3244
3245
3246
3247
3248
3249/* On-demand functions */
3250
3251/** Move sample code line numbers out of PRE block and into non-copyable column */
3252function initCodeLineNumbers() {
3253 var numbers = $("#codesample-block a.number");
3254 if (numbers.length) {
3255 $("#codesample-line-numbers").removeClass("hidden").append(numbers);
3256 }
3257
3258 $(document).ready(function() {
3259 // select entire line when clicked
3260 $("span.code-line").click(function() {
3261 if (!shifted) {
3262 selectText(this);
3263 }
3264 });
3265 // invoke line link on double click
3266 $(".code-line").dblclick(function() {
3267 document.location.hash = $(this).attr('id');
3268 });
3269 // highlight the line when hovering on the number
3270 $("#codesample-line-numbers a.number").mouseover(function() {
3271 var id = $(this).attr('href');
3272 $(id).css('background','#e7e7e7');
3273 });
3274 $("#codesample-line-numbers a.number").mouseout(function() {
3275 var id = $(this).attr('href');
3276 $(id).css('background','none');
3277 });
3278 });
3279}
3280
3281// create SHIFT key binder to avoid the selectText method when selecting multiple lines
3282var shifted = false;
3283$(document).bind('keyup keydown', function(e){shifted = e.shiftKey; return true;} );
3284
3285// courtesy of jasonedelman.com
3286function selectText(element) {
3287 var doc = document
3288 , range, selection
3289 ;
3290 if (doc.body.createTextRange) { //ms
3291 range = doc.body.createTextRange();
3292 range.moveToElementText(element);
3293 range.select();
3294 } else if (window.getSelection) { //all others
3295 selection = window.getSelection();
3296 range = doc.createRange();
3297 range.selectNodeContents(element);
3298 selection.removeAllRanges();
3299 selection.addRange(range);
3300 }
3301}
3302
3303
3304
3305
3306/** Display links and other information about samples that match the
3307 group specified by the URL */
3308function showSamples() {
3309 var group = $("#samples").attr('class');
3310 $("#samples").html("<p>Here are some samples for <b>" + group + "</b> apps:</p>");
3311
3312 var $ul = $("<ul>");
3313 $selectedLi = $("#nav li.selected");
3314
3315 $selectedLi.children("ul").children("li").each(function() {
3316 var $li = $("<li>").append($(this).find("a").first().clone());
3317 $ul.append($li);
3318 });
3319
3320 $("#samples").append($ul);
3321
3322}
Dirk Dougherty08032402014-02-15 10:14:35 -08003323
3324
3325
3326/* ########################################################## */
3327/* ################### RESOURCE CARDS ##################### */
3328/* ########################################################## */
3329
3330/** Handle resource queries, collections, and grids (sections). Requires
3331 jd_tag_helpers.js and the *_unified_data.js to be loaded. */
3332
3333(function() {
3334 // Prevent the same resource from being loaded more than once per page.
3335 var addedPageResources = {};
3336
3337 $(document).ready(function() {
3338 $('.resource-widget').each(function() {
3339 initResourceWidget(this);
3340 });
3341
3342 // Might remove this, but adds ellipsis to card descriptions rather
3343 // than just cutting them off, not sure if it performs well
3344 $('.card-info .text').ellipsis();
3345 });
3346
3347 /*
3348 Three types of resource layouts:
3349 Flow - Uses a fixed row-height flow using float left style.
3350 Carousel - Single card slideshow all same dimension absoute.
3351 Stack - Uses fixed columns and flexible element height.
3352 */
3353 function initResourceWidget(widget) {
3354 var $widget = $(widget);
3355 var isFlow = $widget.hasClass('resource-flow-layout'),
3356 isCarousel = $widget.hasClass('resource-carousel-layout'),
3357 isStack = $widget.hasClass('resource-stack-layout');
3358
3359 // find size of widget by pulling out its class name
3360 var sizeCols = 1;
3361 var m = $widget.get(0).className.match(/\bcol-(\d+)\b/);
3362 if (m) {
3363 sizeCols = parseInt(m[1], 10);
3364 }
3365
3366 var opts = {
3367 cardSizes: ($widget.data('cardsizes') || '').split(','),
3368 maxResults: parseInt($widget.data('maxresults') || '100', 10),
3369 itemsPerPage: $widget.data('itemsperpage'),
3370 sortOrder: $widget.data('sortorder'),
3371 query: $widget.data('query'),
3372 section: $widget.data('section'),
3373 sizeCols: sizeCols
3374 };
3375
3376 // run the search for the set of resources to show
3377
3378 var resources = buildResourceList(opts);
3379
3380 if (isFlow) {
3381 drawResourcesFlowWidget($widget, opts, resources);
3382 } else if (isCarousel) {
3383 drawResourcesCarouselWidget($widget, opts, resources);
3384 } else if (isStack) {
3385 var sections = buildSectionList(opts);
3386 opts['numStacks'] = $widget.data('numstacks');
3387 drawResourcesStackWidget($widget, opts, resources, sections);
3388 }
3389 }
3390
3391 /* Initializes a Resource Carousel Widget */
3392 function drawResourcesCarouselWidget($widget, opts, resources) {
3393 $widget.empty();
3394
3395 $widget.addClass('resource-card slideshow-container')
3396 .append($('<a>').addClass('slideshow-prev').text('Prev'))
3397 .append($('<a>').addClass('slideshow-next').text('Next'));
3398
3399 var css = { 'width': $widget.width() + 'px',
3400 'height': $widget.height() + 'px' };
3401
3402 var $ul = $('<ul>');
3403
3404 for (var i = 0; i < resources.length; ++i) {
3405 //keep url clean for matching and offline mode handling
3406 var urlPrefix = resources[i].url.indexOf("//") > -1 ? "" : toRoot;
3407 var $card = $('<a>')
3408 .attr('href', urlPrefix + resources[i].url)
3409 .decorateResourceCard(resources[i]);
3410
3411 $('<li>').css(css)
3412 .append($card)
3413 .appendTo($ul);
3414 }
3415
3416 $('<div>').addClass('frame')
3417 .append($ul)
3418 .appendTo($widget);
3419
3420 $widget.dacSlideshow({
3421 auto: true,
3422 btnPrev: '.slideshow-prev',
3423 btnNext: '.slideshow-next'
3424 });
3425 };
3426
3427 /* Initializes a Resource Card Stack Widget (column-based layout) */
3428 function drawResourcesStackWidget($widget, opts, resources, sections) {
3429 // Don't empty widget, grab all items inside since they will be the first
3430 // items stacked, followed by the resource query
3431
3432 var cards = $widget.find('.resource-card').detach().toArray();
3433 var numStacks = opts.numStacks || 1;
3434 var $stacks = [];
3435 var urlString;
3436
3437 for (var i = 0; i < numStacks; ++i) {
3438 $stacks[i] = $('<div>').addClass('resource-card-stack')
3439 .appendTo($widget);
3440 }
3441
3442 var sectionResources = [];
3443
3444 // Extract any subsections that are actually resource cards
3445 for (var i = 0; i < sections.length; ++i) {
3446 if (!sections[i].sections || !sections[i].sections.length) {
3447 //keep url clean for matching and offline mode handling
3448 urlPrefix = sections[i].url.indexOf("//") > -1 ? "" : toRoot;
3449 // Render it as a resource card
3450
3451 sectionResources.push(
3452 $('<a>')
3453 .addClass('resource-card section-card')
3454 .attr('href', urlPrefix + sections[i].resource.url)
3455 .decorateResourceCard(sections[i].resource)[0]
3456 );
3457
3458 } else {
3459 cards.push(
3460 $('<div>')
3461 .addClass('resource-card section-card-menu')
3462 .decorateResourceSection(sections[i])[0]
3463 );
3464 }
3465 }
3466
3467 cards = cards.concat(sectionResources);
3468
3469 for (var i = 0; i < resources.length; ++i) {
3470 //keep url clean for matching and offline mode handling
3471 urlPrefix = resources[i].url.indexOf("//") > -1 ? "" : toRoot;
3472 var $card = $('<a>')
3473 .addClass('resource-card related-card')
3474 .attr('href', urlPrefix + resources[i].url)
3475 .decorateResourceCard(resources[i]);
3476
3477 cards.push($card[0]);
3478 }
3479
3480 for (var i = 0; i < cards.length; ++i) {
3481 // Find the stack with the shortest height, but give preference to
3482 // left to right order.
3483 var minHeight = $stacks[0].height();
3484 var minIndex = 0;
3485
3486 for (var j = 1; j < numStacks; ++j) {
3487 var height = $stacks[j].height();
3488 if (height < minHeight - 45) {
3489 minHeight = height;
3490 minIndex = j;
3491 }
3492 }
3493
3494 $stacks[minIndex].append($(cards[i]));
3495 }
3496
3497 };
3498
3499 /* Initializes a flow widget, see distribute.scss for generating accompanying css */
3500 function drawResourcesFlowWidget($widget, opts, resources) {
3501 $widget.empty();
3502 var cardSizes = opts.cardSizes || ['6x6'];
3503 var i = 0, j = 0;
3504
3505 while (i < resources.length) {
3506 var cardSize = cardSizes[j++ % cardSizes.length];
3507 cardSize = cardSize.replace(/^\s+|\s+$/,'');
3508
3509 // A stack has a third dimension which is the number of stacked items
3510 var isStack = cardSize.match(/(\d+)x(\d+)x(\d+)/);
3511 var stackCount = 0;
3512 var $stackDiv = null;
3513
3514 if (isStack) {
3515 // Create a stack container which should have the dimensions defined
3516 // by the product of the items inside.
3517 $stackDiv = $('<div>').addClass('resource-card-stack resource-card-' + isStack[1]
3518 + 'x' + isStack[2] * isStack[3]) .appendTo($widget);
3519 }
3520
3521 // Build each stack item or just a single item
3522 do {
3523 var resource = resources[i];
3524 //keep url clean for matching and offline mode handling
3525 urlPrefix = resource.url.indexOf("//") > -1 ? "" : toRoot;
3526 var $card = $('<a>')
3527 .addClass('resource-card resource-card-' + cardSize + ' resource-card-' + resource.type)
3528 .attr('href', urlPrefix + resource.url);
3529
3530 if (isStack) {
3531 $card.addClass('resource-card-' + isStack[1] + 'x' + isStack[2]);
3532 if (++stackCount == parseInt(isStack[3])) {
3533 $card.addClass('resource-card-row-stack-last');
3534 stackCount = 0;
3535 }
3536 } else {
3537 stackCount = 0;
3538 }
3539
3540 $card.decorateResourceCard(resource)
3541 .appendTo($stackDiv || $widget);
3542
3543 } while (++i < resources.length && stackCount > 0);
3544 }
3545 }
3546
3547 /* Build a site map of resources using a section as a root. */
3548 function buildSectionList(opts) {
3549 if (opts.section && SECTION_BY_ID[opts.section]) {
3550 return SECTION_BY_ID[opts.section].sections || [];
3551 }
3552 return [];
3553 }
3554
3555 function buildResourceList(opts) {
3556 var maxResults = opts.maxResults || 100;
3557
3558 var query = opts.query || '';
3559 var expressions = parseResourceQuery(query);
3560 var addedResourceIndices = {};
3561 var results = [];
3562
3563 for (var i = 0; i < expressions.length; i++) {
3564 var clauses = expressions[i];
3565
3566 // build initial set of resources from first clause
3567 var firstClause = clauses[0];
3568 var resources = [];
3569 switch (firstClause.attr) {
3570 case 'type':
3571 resources = ALL_RESOURCES_BY_TYPE[firstClause.value];
3572 break;
3573 case 'lang':
3574 resources = ALL_RESOURCES_BY_LANG[firstClause.value];
3575 break;
3576 case 'tag':
3577 resources = ALL_RESOURCES_BY_TAG[firstClause.value];
3578 break;
3579 case 'collection':
3580 var urls = RESOURCE_COLLECTIONS[firstClause.value].resources || [];
3581 resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
3582 break;
3583 case 'section':
3584 var urls = SITE_MAP[firstClause.value].sections || [];
3585 resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
3586 break;
3587 }
Scott Main20cf2a92014-04-02 21:57:20 -07003588 // console.log(firstClause.attr + ':' + firstClause.value);
Dirk Dougherty08032402014-02-15 10:14:35 -08003589 resources = resources || [];
3590
3591 // use additional clauses to filter corpus
3592 if (clauses.length > 1) {
3593 var otherClauses = clauses.slice(1);
3594 resources = resources.filter(getResourceMatchesClausesFilter(otherClauses));
3595 }
3596
3597 // filter out resources already added
3598 if (i > 1) {
3599 resources = resources.filter(getResourceNotAlreadyAddedFilter(addedResourceIndices));
3600 }
3601
3602 // add to list of already added indices
3603 for (var j = 0; j < resources.length; j++) {
Scott Main20cf2a92014-04-02 21:57:20 -07003604 // console.log(resources[j].title);
Dirk Dougherty08032402014-02-15 10:14:35 -08003605 addedResourceIndices[resources[j].index] = 1;
3606 }
3607
3608 // concat to final results list
3609 results = results.concat(resources);
3610 }
3611
3612 if (opts.sortOrder && results.length) {
3613 var attr = opts.sortOrder;
3614
3615 if (opts.sortOrder == 'random') {
3616 var i = results.length, j, temp;
3617 while (--i) {
3618 j = Math.floor(Math.random() * (i + 1));
3619 temp = results[i];
3620 results[i] = results[j];
3621 results[j] = temp;
3622 }
3623 } else {
3624 var desc = attr.charAt(0) == '-';
3625 if (desc) {
3626 attr = attr.substring(1);
3627 }
3628 results = results.sort(function(x,y) {
3629 return (desc ? -1 : 1) * (parseInt(x[attr], 10) - parseInt(y[attr], 10));
3630 });
3631 }
3632 }
3633
3634 results = results.filter(getResourceNotAlreadyAddedFilter(addedPageResources));
3635 results = results.slice(0, maxResults);
3636
3637 for (var j = 0; j < results.length; ++j) {
3638 addedPageResources[results[j].index] = 1;
3639 }
3640
3641 return results;
3642 }
3643
3644
3645 function getResourceNotAlreadyAddedFilter(addedResourceIndices) {
3646 return function(resource) {
3647 return !addedResourceIndices[resource.index];
3648 };
3649 }
3650
3651
3652 function getResourceMatchesClausesFilter(clauses) {
3653 return function(resource) {
3654 return doesResourceMatchClauses(resource, clauses);
3655 };
3656 }
3657
3658
3659 function doesResourceMatchClauses(resource, clauses) {
3660 for (var i = 0; i < clauses.length; i++) {
3661 var map;
3662 switch (clauses[i].attr) {
3663 case 'type':
3664 map = IS_RESOURCE_OF_TYPE[clauses[i].value];
3665 break;
3666 case 'lang':
3667 map = IS_RESOURCE_IN_LANG[clauses[i].value];
3668 break;
3669 case 'tag':
3670 map = IS_RESOURCE_TAGGED[clauses[i].value];
3671 break;
3672 }
3673
3674 if (!map || (!!clauses[i].negative ? map[resource.index] : !map[resource.index])) {
3675 return clauses[i].negative;
3676 }
3677 }
3678 return true;
3679 }
3680
3681
3682 function parseResourceQuery(query) {
3683 // Parse query into array of expressions (expression e.g. 'tag:foo + type:video')
3684 var expressions = [];
3685 var expressionStrs = query.split(',') || [];
3686 for (var i = 0; i < expressionStrs.length; i++) {
3687 var expr = expressionStrs[i] || '';
3688
3689 // Break expression into clauses (clause e.g. 'tag:foo')
3690 var clauses = [];
3691 var clauseStrs = expr.split(/(?=[\+\-])/);
3692 for (var j = 0; j < clauseStrs.length; j++) {
3693 var clauseStr = clauseStrs[j] || '';
3694
3695 // Get attribute and value from clause (e.g. attribute='tag', value='foo')
3696 var parts = clauseStr.split(':');
3697 var clause = {};
3698
3699 clause.attr = parts[0].replace(/^\s+|\s+$/g,'');
3700 if (clause.attr) {
3701 if (clause.attr.charAt(0) == '+') {
3702 clause.attr = clause.attr.substring(1);
3703 } else if (clause.attr.charAt(0) == '-') {
3704 clause.negative = true;
3705 clause.attr = clause.attr.substring(1);
3706 }
3707 }
3708
3709 if (parts.length > 1) {
3710 clause.value = parts[1].replace(/^\s+|\s+$/g,'');
3711 }
3712
3713 clauses.push(clause);
3714 }
3715
3716 if (!clauses.length) {
3717 continue;
3718 }
3719
3720 expressions.push(clauses);
3721 }
3722
3723 return expressions;
3724 }
3725})();
3726
3727(function($) {
3728 /* Simple jquery function to create dom for a standard resource card */
3729 $.fn.decorateResourceCard = function(resource) {
3730 var section = resource.group || resource.type;
3731 var imgUrl;
3732 if (resource.image) {
3733 //keep url clean for matching and offline mode handling
3734 var urlPrefix = resource.image.indexOf("//") > -1 ? "" : toRoot;
3735 imgUrl = urlPrefix + resource.image;
3736 }
3737
3738 $('<div>')
3739 .addClass('card-bg')
3740 .css('background-image', 'url(' + (imgUrl || toRoot + 'assets/images/resource-card-default-android.jpg') + ')')
3741 .appendTo(this);
3742
3743 $('<div>').addClass('card-info' + (!resource.summary ? ' empty-desc' : ''))
3744 .append($('<div>').addClass('section').text(section))
3745 .append($('<div>').addClass('title').html(resource.title))
3746 .append($('<div>').addClass('description')
3747 .append($('<div>').addClass('text').html(resource.summary))
3748 .append($('<div>').addClass('util')
3749 .append($('<div>').addClass('g-plusone')
3750 .attr('data-size', 'small')
3751 .attr('data-align', 'right')
3752 .attr('data-href', resource.url))))
3753 .appendTo(this);
3754
3755 return this;
3756 };
3757
3758 /* Simple jquery function to create dom for a resource section card (menu) */
3759 $.fn.decorateResourceSection = function(section) {
3760 var resource = section.resource;
3761 //keep url clean for matching and offline mode handling
3762 var urlPrefix = resource.image.indexOf("//") > -1 ? "" : toRoot;
3763 var $base = $('<a>')
3764 .addClass('card-bg')
3765 .attr('href', resource.url)
3766 .append($('<div>').addClass('card-section-icon')
3767 .append($('<div>').addClass('icon'))
3768 .append($('<div>').addClass('section').html(resource.title)))
3769 .appendTo(this);
3770
3771 var $cardInfo = $('<div>').addClass('card-info').appendTo(this);
3772
3773 if (section.sections && section.sections.length) {
3774 // Recurse the section sub-tree to find a resource image.
3775 var stack = [section];
3776
3777 while (stack.length) {
3778 if (stack[0].resource.image) {
3779 $base.css('background-image', 'url(' + urlPrefix + stack[0].resource.image + ')');
3780 break;
3781 }
3782
3783 if (stack[0].sections) {
3784 stack = stack.concat(stack[0].sections);
3785 }
3786
3787 stack.shift();
3788 }
3789
3790 var $ul = $('<ul>')
3791 .appendTo($cardInfo);
3792
3793 var max = section.sections.length > 3 ? 3 : section.sections.length;
3794
3795 for (var i = 0; i < max; ++i) {
3796
3797 var subResource = section.sections[i];
3798 $('<li>')
3799 .append($('<a>').attr('href', subResource.url)
3800 .append($('<div>').addClass('title').html(subResource.title))
3801 .append($('<div>').addClass('description')
3802 .append($('<div>').addClass('text').html(subResource.summary))
3803 .append($('<div>').addClass('util')
3804 .append($('<div>').addClass('g-plusone')
3805 .attr('data-size', 'small')
3806 .attr('data-align', 'right')
3807 .attr('data-href', resource.url)))))
3808 .appendTo($ul);
3809 }
3810
3811 // Add a more row
3812 if (max < section.sections.length) {
3813 $('<li>')
3814 .append($('<a>').attr('href', resource.url)
3815 .append($('<div>')
3816 .addClass('title')
3817 .text('More')))
3818 .appendTo($ul);
3819 }
3820 } else {
3821 // No sub-resources, just render description?
3822 }
3823
3824 return this;
3825 };
3826})(jQuery);
3827
3828
3829(function($) {
3830 $.fn.ellipsis = function(options) {
3831
3832 // default option
3833 var defaults = {
3834 'row' : 1, // show rows
3835 'onlyFullWords': true, // set to true to avoid cutting the text in the middle of a word
Dirk Dougherty46b443a2014-04-06 15:27:33 -07003836 'char' : '\u2026', // ellipsis
Dirk Dougherty08032402014-02-15 10:14:35 -08003837 'callback': function() {},
3838 'position': 'tail' // middle, tail
3839 };
3840
3841 options = $.extend(defaults, options);
3842
3843 this.each(function() {
3844 // get element text
3845 var $this = $(this);
3846
3847 var targetHeight = $this.height();
3848 $this.css({'height': 'auto'});
3849 var text = $this.text();
3850 var origText = text;
3851 var origLength = origText.length;
3852 var origHeight = $this.height();
3853
3854 if (origHeight <= targetHeight) {
3855 $this.text(text);
3856 options.callback.call(this);
3857 return;
3858 }
3859
3860 var start = 1, length = 0;
3861 var end = text.length;
3862
3863 if(options.position === 'tail') {
3864 while (start < end) { // Binary search for max length
3865 length = Math.ceil((start + end) / 2);
3866
3867 $this.text(text.slice(0, length) + options['char']);
3868
3869 if ($this.height() <= targetHeight) {
3870 start = length;
3871 } else {
3872 end = length - 1;
3873 }
3874 }
3875
3876 text = text.slice(0, start);
3877
3878 if (options.onlyFullWords) {
3879 // remove fragment of the last word together with possible soft-hyphen chars
3880 text = text.replace(/[\u00AD\w\uac00-\ud7af]+$/, '');
3881 }
3882 text += options['char'];
3883
3884 }else if(options.position === 'middle') {
3885
3886 var sliceLength = 0;
3887 while (start < end) { // Binary search for max length
3888 length = Math.ceil((start + end) / 2);
3889 sliceLength = Math.max(origLength - length, 0);
3890
3891 $this.text(
3892 origText.slice(0, Math.floor((origLength - sliceLength) / 2)) +
3893 options['char'] +
3894 origText.slice(Math.floor((origLength + sliceLength) / 2), origLength)
3895 );
3896
3897 if ($this.height() <= targetHeight) {
3898 start = length;
3899 } else {
3900 end = length - 1;
3901 }
3902 }
3903
3904 sliceLength = Math.max(origLength - start, 0);
3905 var head = origText.slice(0, Math.floor((origLength - sliceLength) / 2));
3906 var tail = origText.slice(Math.floor((origLength + sliceLength) / 2), origLength);
3907
3908 if (options.onlyFullWords) {
3909 // remove fragment of the last or first word together with possible soft-hyphen characters
3910 head = head.replace(/[\u00AD\w\uac00-\ud7af]+$/, '');
3911 }
3912
3913 text = head + options['char'] + tail;
3914 }
3915
3916 $this.text(text);
3917 options.callback.call(this);
3918 });
3919
3920 return this;
3921 };
Scott Main20cf2a92014-04-02 21:57:20 -07003922}) (jQuery);