1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/**
6 * Global variable containing the query we'd like to pass to Flickr. In this
7 * case, kittens!
8 *
9 * @type {string}
10 */
11var QUERY = 'kittens';
12
13var kittenGenerator = {
14  /**
15   * Flickr URL that will give us lots and lots of whatever we're looking for.
16   *
17   * See http://www.flickr.com/services/api/flickr.photos.search.html for
18   * details about the construction of this URL.
19   *
20   * @type {string}
21   * @private
22   */
23  searchOnFlickr_: 'https://secure.flickr.com/services/rest/?' +
24      'method=flickr.photos.search&' +
25      'api_key=90485e931f687a9b9c2a66bf58a3861a&' +
26      'text=' + encodeURIComponent(QUERY) + '&' +
27      'safe_search=1&' +
28      'content_type=1&' +
29      'sort=interestingness-desc&' +
30      'per_page=20',
31
32  /**
33   * Sends an XHR GET request to grab photos of lots and lots of kittens. The
34   * XHR's 'onload' event is hooks up to the 'showPhotos_' method.
35   *
36   * @public
37   */
38  requestKittens: function() {
39    var req = new XMLHttpRequest();
40    req.open("GET", this.searchOnFlickr_, true);
41    req.onload = this.showPhotos_.bind(this);
42    req.send(null);
43  },
44
45  /**
46   * Handle the 'onload' event of our kitten XHR request, generated in
47   * 'requestKittens', by generating 'img' elements, and stuffing them into
48   * the document for display.
49   *
50   * @param {ProgressEvent} e The XHR ProgressEvent.
51   * @private
52   */
53  showPhotos_: function (e) {
54    var kittens = e.target.responseXML.querySelectorAll('photo');
55    for (var i = 0; i < kittens.length; i++) {
56      var img = document.createElement('img');
57      img.src = this.constructKittenURL_(kittens[i]);
58      img.setAttribute('alt', kittens[i].getAttribute('title'));
59      document.body.appendChild(img);
60    }
61  },
62
63  /**
64   * Given a photo, construct a URL using the method outlined at
65   * http://www.flickr.com/services/api/misc.urlKittenl
66   *
67   * @param {DOMElement} A kitten.
68   * @return {string} The kitten's URL.
69   * @private
70   */
71  constructKittenURL_: function (photo) {
72    return "http://farm" + photo.getAttribute("farm") +
73        ".static.flickr.com/" + photo.getAttribute("server") +
74        "/" + photo.getAttribute("id") +
75        "_" + photo.getAttribute("secret") +
76        "_s.jpg";
77  }
78};
79
80// Run our kitten generation script as soon as the document's DOM is ready.
81document.addEventListener('DOMContentLoaded', function () {
82  kittenGenerator.requestKittens();
83});
84