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