<commit_before>/**
 * Construct a new ServiceFinder. This is a single-use object that does a DNS
 * multicast search on creation.
 * @constructor
 * @param {function} callback The callback to be invoked when this object is
 *                            updated, or when an error occurs (passes string).
 */
var ServiceFinder = function(callback) {
  this.callback_ = callback;
  this.byIP_ = {};
  this.byService_ = {};

  // Set up receive handlers.
  this.onReceiveListener_ = this.onReceive_.bind(this);
  chrome.sockets.udp.onReceive.addListener(this.onReceiveListener_);
  this.onReceiveErrorListener_ = this.onReceiveError_.bind(this);
  chrome.sockets.udp.onReceiveError.addListener(this.onReceiveErrorListener_);

  ServiceFinder.forEachAddress_(function(address, error) {
    if (error) {
      this.callback_(error);
      return true;
    }
    if (address.indexOf(':') != -1) {
      // TODO: ipv6.
      console.log('IPv6 address unsupported', address);
      return true;
    }
    console.log('Broadcasting to address', address);

    ServiceFinder.bindToAddress_(address, function(socket) {
      if (!socket) {
        this.callback_('could not bind UDP socket');
        return true;
      }
      // Broadcast on it.
      this.broadcast_(socket, address);
    }.bind(this));
  }.bind(this));

  // After a short time, if our database is empty, report an error.
  setTimeout(function() {
    if (!Object.keys(this.byIP_).length) {
      this.callback_('no mDNS services found!');
    }
  }.bind(this), 10 * 1000);
};

/**
 * Invokes the callback for every local network address on the system.
 * @private
 * @param {function} callback to invoke
 */
ServiceFinder.forEachAddress_ = function(callback) {
  chrome.system.network.getNetworkInterfaces(function(networkInterfaces) {
    if (!networkInterfaces.length) {
      callback(null, 'no network available!');
      return true;
    }
    networkInterfaces.forEach(function(networkInterface) {
      callback(networkInterface['address'], null);
    });
  });
};

/**
 * Creates UDP socket bound to the specified address, passing it to the
 * callback. Passes null on failure.
 * @private
 * @param {string} address to bind to
 * @param {function} callback to invoke when done
 */
ServiceFinder.bindToAddress_ = function(address, callback) {
  chrome.sockets.udp.create({}, function(createInfo) {
    chrome.sockets.udp.bind(createInfo['socketId'], address, 0,
        function(result) {
      callback((result >= 0) ? createInfo['socketId'] : null);
    });
  });
};

/**
 * Sorts the passed list of string IPs in-place.
 * @private
 */
ServiceFinder.sortIps_ = function(arg) {
  arg.sort(ServiceFinder.sortIps_.sort);
  return arg;
};
ServiceFinder.sortIps_.sort = function(l, r) {
  // TODO: support v6.
  var lp = l.split('.').map(ServiceFinder.sortIps_.toInt_);
  var rp = r.split('.').map(ServiceFinder.sortIps_.toInt_);
  for (var i = 0; i < Math.min(lp.length, rp.length); ++i) {
    if (lp[i] < rp[i]) {
      return -1;
    } else if (lp[i] > rp[i]) {
      return +1;
    }
  }
  return 0;
};
ServiceFinder.sortIps_.toInt_ = function(i) { return +i };

/**
 * Returns the services found by this ServiceFinder, optionally filtered by IP.
 */
ServiceFinder.prototype.services = function(opt_ip) {
  var k = Object.keys(opt_ip ? this.byIP_[opt_ip] : this.byService_);
  k.sort();
  return k;
};

/**
 * Returns the IPs found by this ServiceFinder, optionally filtered by service.
 */
ServiceFinder.prototype.ips = function(opt_service) {
  var k = Object.keys(opt_service ? this.byService_[opt_service] : this.byIP_);
  return ServiceFinder.sortIps_(k);
};

/**
 * Handles an incoming UDP packet.
 * @private
 */
ServiceFinder.prototype.onReceive_ = function(info) {
  var getDefault_ = function(o, k, def) {
    (k in o) || false == (o[k] = def);
    return o[k];
  };

  // Update our local database.
  // TODO: Resolve IPs using the dns extension.
  var packet = DNSPacket.parse(info.data);
  var byIP = getDefault_(this.byIP_, info.remoteAddress, {});

  packet.each('an', 12, function(rec) {
    var ptr = rec.asName();
    var byService = getDefault_(this.byService_, ptr, {})
    byService[info.remoteAddress] = true;
    byIP[ptr] = true;
  }.bind(this));

  // Ping! Something new is here. Only update every 25ms.
  if (!this.callback_pending_) {
    this.callback_pending_ = true;
    setTimeout(function() {
      this.callback_pending_ = undefined;
      this.callback_();
    }.bind(this), 25);
  }
};

/**
 * Handles network error occured while waiting for data.
 * @private
 */
ServiceFinder.prototype.onReceiveError_ = function(info) {
  this.callback_(info.resultCode);
  return true;
}

/**
 * Broadcasts for services on the given socket/address.
 * @private
 */
ServiceFinder.prototype.broadcast_ = function(sock, address) {
  var packet = new DNSPacket();
  packet.push('qd', new DNSRecord('_services._dns-sd._udp.local', 12, 1));

  var raw = packet.serialize();
  chrome.sockets.udp.send(sock, raw, '224.0.0.251', 5353, function(sendInfo) {
    if (sendInfo.resultCode < 0)
      this.callback_('Could not send data to:' + address);
  });
};

ServiceFinder.prototype.shutdown = function() {
  // Remove event listeners.
  chrome.sockets.udp.onReceive.removeListener(this.onReceiveListener_);
  chrome.sockets.udp.onReceiveError.removeListener(this.onReceiveErrorListener_);
  // Close opened sockets.
  chrome.sockets.udp.getSockets(function(sockets) {
    sockets.forEach(function(sock) {
      chrome.sockets.udp.close(sock.socketId);
    });
  });
}<commit_msg>Specify service type to browse for on ServiceFinder creation<commit_after>/**
 * Construct a new ServiceFinder. This is a single-use object that does a DNS
 * multicast search on creation.
 * @constructor
 * @param {function} callback The callback to be invoked when this object is
 *                            updated, or when an error occurs (passes string).
 */
var ServiceFinder = function(callback, serviceType) {
  this.callback_ = callback;
  this.byIP_ = {};
  this.byService_ = {};

  this.serviceType_ = serviceType || '_services._dns-sd._udp.local';

  // Set up receive handlers.
  this.onReceiveListener_ = this.onReceive_.bind(this);
  chrome.sockets.udp.onReceive.addListener(this.onReceiveListener_);
  this.onReceiveErrorListener_ = this.onReceiveError_.bind(this);
  chrome.sockets.udp.onReceiveError.addListener(this.onReceiveErrorListener_);

  ServiceFinder.forEachAddress_(function(address, error) {
    if (error) {
      this.callback_(error);
      return true;
    }
    if (address.indexOf(':') != -1) {
      // TODO: ipv6.
      console.log('IPv6 address unsupported', address);
      return true;
    }
    console.log('Broadcasting to address', address);

    ServiceFinder.bindToAddress_(address, function(socket) {
      if (!socket) {
        this.callback_('could not bind UDP socket');
        return true;
      }
      // Broadcast on it.
      this.broadcast_(socket, address);
    }.bind(this));
  }.bind(this));

  // After a short time, if our database is empty, report an error.
  setTimeout(function() {
    if (!Object.keys(this.byIP_).length) {
      this.callback_('no mDNS services found!');
    }
  }.bind(this), 10 * 1000);
};

/**
 * Invokes the callback for every local network address on the system.
 * @private
 * @param {function} callback to invoke
 */
ServiceFinder.forEachAddress_ = function(callback) {
  chrome.system.network.getNetworkInterfaces(function(networkInterfaces) {
    if (!networkInterfaces.length) {
      callback(null, 'no network available!');
      return true;
    }
    networkInterfaces.forEach(function(networkInterface) {
      callback(networkInterface['address'], null);
    });
  });
};

/**
 * Creates UDP socket bound to the specified address, passing it to the
 * callback. Passes null on failure.
 * @private
 * @param {string} address to bind to
 * @param {function} callback to invoke when done
 */
ServiceFinder.bindToAddress_ = function(address, callback) {
  chrome.sockets.udp.create({}, function(createInfo) {
    chrome.sockets.udp.bind(createInfo['socketId'], address, 0,
        function(result) {
      callback((result >= 0) ? createInfo['socketId'] : null);
    });
  });
};

/**
 * Sorts the passed list of string IPs in-place.
 * @private
 */
ServiceFinder.sortIps_ = function(arg) {
  arg.sort(ServiceFinder.sortIps_.sort);
  return arg;
};
ServiceFinder.sortIps_.sort = function(l, r) {
  // TODO: support v6.
  var lp = l.split('.').map(ServiceFinder.sortIps_.toInt_);
  var rp = r.split('.').map(ServiceFinder.sortIps_.toInt_);
  for (var i = 0; i < Math.min(lp.length, rp.length); ++i) {
    if (lp[i] < rp[i]) {
      return -1;
    } else if (lp[i] > rp[i]) {
      return +1;
    }
  }
  return 0;
};
ServiceFinder.sortIps_.toInt_ = function(i) { return +i };

/**
 * Returns the services found by this ServiceFinder, optionally filtered by IP.
 */
ServiceFinder.prototype.services = function(opt_ip) {
  var k = Object.keys(opt_ip ? this.byIP_[opt_ip] : this.byService_);
  k.sort();
  return k;
};

/**
 * Returns the IPs found by this ServiceFinder, optionally filtered by service.
 */
ServiceFinder.prototype.ips = function(opt_service) {
  var k = Object.keys(opt_service ? this.byService_[opt_service] : this.byIP_);
  return ServiceFinder.sortIps_(k);
};

/**
 * Handles an incoming UDP packet.
 * @private
 */
ServiceFinder.prototype.onReceive_ = function(info) {
  var getDefault_ = function(o, k, def) {
    (k in o) || false == (o[k] = def);
    return o[k];
  };

  // Update our local database.
  // TODO: Resolve IPs using the dns extension.
  var packet = DNSPacket.parse(info.data);
  var byIP = getDefault_(this.byIP_, info.remoteAddress, {});

  packet.each('an', 12, function(rec) {
    var ptr = rec.asName();
    var byService = getDefault_(this.byService_, ptr, {})
    byService[info.remoteAddress] = true;
    byIP[ptr] = true;
  }.bind(this));

  // Ping! Something new is here. Only update every 25ms.
  if (!this.callback_pending_) {
    this.callback_pending_ = true;
    setTimeout(function() {
      this.callback_pending_ = undefined;
      this.callback_();
    }.bind(this), 25);
  }
};

/**
 * Handles network error occured while waiting for data.
 * @private
 */
ServiceFinder.prototype.onReceiveError_ = function(info) {
  this.callback_(info.resultCode);
  return true;
}

/**
 * Broadcasts for services on the given socket/address.
 * @private
 */
ServiceFinder.prototype.broadcast_ = function(sock, address) {
  var packet = new DNSPacket();
  packet.push('qd', new DNSRecord(this.serviceType_, 12, 1));

  var raw = packet.serialize();
  chrome.sockets.udp.send(sock, raw, '224.0.0.251', 5353, function(sendInfo) {
    if (sendInfo.resultCode < 0)
      this.callback_('Could not send data to:' + address);
  });
};

ServiceFinder.prototype.shutdown = function() {
  // Remove event listeners.
  chrome.sockets.udp.onReceive.removeListener(this.onReceiveListener_);
  chrome.sockets.udp.onReceiveError.removeListener(this.onReceiveErrorListener_);
  // Close opened sockets.
  chrome.sockets.udp.getSockets(function(sockets) {
    sockets.forEach(function(sock) {
      chrome.sockets.udp.close(sock.socketId);
    });
  });
}<|endoftext|>


<commit_before>/**
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

// DO NOT EDIT THIS GENERATED OUTPUT DIRECTLY!
// This file should be overwritten as part of your build process.
// If you need to extend the behavior of the generated service worker, the best approach is to write
// additional code and include it using the importScripts option:
//   https://github.com/GoogleChrome/sw-precache#importscripts-arraystring
//
// Alternatively, it's possible to make changes to the underlying template file and then use that as the
// new base for generating output, via the templateFilePath option:
//   https://github.com/GoogleChrome/sw-precache#templatefilepath-string
//
// If you go that route, make sure that whenever you update your sw-precache dependency, you reconcile any
// changes made to this original template file with your modified copy.

// This generated service worker JavaScript will precache your site's resources.
// The code needs to be saved in a .js file at the top-level of your site, and registered
// from your pages in order to be used. See
// https://github.com/googlechrome/sw-precache/blob/master/demo/app/js/service-worker-registration.js
// for an example of how you can register this script and handle various service worker events.

/* eslint-env worker, serviceworker */
/* eslint-disable indent, no-unused-vars, no-multiple-empty-lines, max-nested-callbacks, space-before-function-paren, quotes, comma-spacing */
'use strict';

var precacheConfig = [["2017/04/04/Issue-1.html","899a67e0e89d9904ad967b8cb5728b39"],["2017/04/11/Issue-2.html","00ef943782c754ff4630ef5b273e333d"],["2017/05/04/Issue-3.html","4a8173cef8177c904e7885d73dd7fbd3"],["404.html","654de47775fc221c5e783dd6f7df044a"],["archives.html","8817612ef050552762481e25f5451bc1"],["codelabs/index.html","f09ae6a89846b71b0b254a83844bd127"],["css/archives.css","f6958fb798d3df57c41b18bafbea2512"],["css/base.css","5195f6a38e5b35d8acf5f11f5e1d65fa"],["css/issues.css","44f04797aae512281953ca3718d97d07"],["css/main.css","4a726ce9502017fb68e06acf5cbb2101"],["css/menu.css","fd99f071408f5ff4c29de3faa198c280"],["css/modal.css","d91f766c5d64913352bfc34fdbdf08f4"],["css/opensources.css","fc12b6482842758c3b72c88ccdd81913"],["css/reset.css","7e9de0bae21fd193dd472c0d6f549a06"],["css/toast.css","fc3dfe3dc3bbb224a3a95849f583ac92"],["images/banner.png","0c7f1b0bf784a9138327951fae613ed3"],["images/engaging.png","f996517995fb7b9bac65587a3bbfc049"],["images/fast.png","4d3919c4f1630820874c225e4b530ee6"],["images/menu_black.svg","d346927b079c06d3a5364e5a8dd9a62c"],["images/pwa-codelabs.png","99ffcb4fd39c407d4e8d4caa6b7ac01a"],["images/reliable.png","42fb8def018bb3f80a3805226383a57f"],["index.html","c9175e9a063f3a8bafc49daa8542827f"],["js/main.js","19cdce47eb239f7c755d7547f7ea2c8e"],["js/menu.js","aba5e0ac92bedd7ce29db702399dbdf5"],["opensources.html","5c5a8ece7280ef9ae56d98f37fa4a407"]];
var cacheName = 'sw-precache-v3-sw-precache-' + (self.registration ? self.registration.scope : '');

var ignoreUrlParametersMatching = [/^utm_/];

var addDirectoryIndex = function (originalUrl, index) {
    var url = new URL(originalUrl);
    if (url.pathname.slice(-1) === '/') {
      url.pathname += index;
    }
    return url.toString();
  };

var cleanResponse = function (originalResponse) {
    // If this is not a redirected response, then we don't have to do anything.
    if (!originalResponse.redirected) {
      return Promise.resolve(originalResponse);
    }

    // Firefox 50 and below doesn't support the Response.body stream, so we may
    // need to read the entire body to memory as a Blob.
    var bodyPromise = 'body' in originalResponse ?
      Promise.resolve(originalResponse.body) :
      originalResponse.blob();

    return bodyPromise.then(function(body) {
      // new Response() is happy when passed either a stream or a Blob.
      return new Response(body, {
        headers: originalResponse.headers,
        status: originalResponse.status,
        statusText: originalResponse.statusText
      });
    });
  };

var createCacheKey = function (originalUrl, paramName, paramValue,
                           dontCacheBustUrlsMatching) {
    // Create a new URL object to avoid modifying originalUrl.
    var url = new URL(originalUrl);

    // If dontCacheBustUrlsMatching is not set, or if we don't have a match,
    // then add in the extra cache-busting URL parameter.
    if (!dontCacheBustUrlsMatching ||
        !(url.pathname.match(dontCacheBustUrlsMatching))) {
      url.search += (url.search ? '&' : '') +
        encodeURIComponent(paramName) + '=' + encodeURIComponent(paramValue);
    }

    return url.toString();
  };

var isPathWhitelisted = function (whitelist, absoluteUrlString) {
    // If the whitelist is empty, then consider all URLs to be whitelisted.
    if (whitelist.length === 0) {
      return true;
    }

    // Otherwise compare each path regex to the path of the URL passed in.
    var path = (new URL(absoluteUrlString)).pathname;
    return whitelist.some(function(whitelistedPathRegex) {
      return path.match(whitelistedPathRegex);
    });
  };

var stripIgnoredUrlParameters = function (originalUrl,
    ignoreUrlParametersMatching) {
    var url = new URL(originalUrl);

    url.search = url.search.slice(1) // Exclude initial '?'
      .split('&') // Split into an array of 'key=value' strings
      .map(function(kv) {
        return kv.split('='); // Split each 'key=value' string into a [key, value] array
      })
      .filter(function(kv) {
        return ignoreUrlParametersMatching.every(function(ignoredRegex) {
          return !ignoredRegex.test(kv[0]); // Return true iff the key doesn't match any of the regexes.
        });
      })
      .map(function(kv) {
        return kv.join('='); // Join each [key, value] array into a 'key=value' string
      })
      .join('&'); // Join the array of 'key=value' strings into a string with '&' in between each

    return url.toString();
  };

var hashParamName = '_sw-precache';
var urlsToCacheKeys = new Map(
  precacheConfig.map(function(item) {
    var relativeUrl = item[0];
    var hash = item[1];
    var absoluteUrl = new URL(relativeUrl, self.location);
    var cacheKey = createCacheKey(absoluteUrl, hashParamName, hash, false);
    return [absoluteUrl.toString(), cacheKey];
  })
);

function setOfCachedUrls(cache) {
  return cache.keys().then(function(requests) {
    return requests.map(function(request) {
      return request.url;
    });
  }).then(function(urls) {
    return new Set(urls);
  });
}

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(cacheName).then(function(cache) {
      return setOfCachedUrls(cache).then(function(cachedUrls) {
        return Promise.all(
          Array.from(urlsToCacheKeys.values()).map(function(cacheKey) {
            // If we don't have a key matching url in the cache already, add it.
            if (!cachedUrls.has(cacheKey)) {
              var request = new Request(cacheKey, {credentials: 'same-origin'});
              return fetch(request).then(function(response) {
                // Bail out of installation unless we get back a 200 OK for
                // every request.
                if (!response.ok) {
                  throw new Error('Request for ' + cacheKey + ' returned a ' +
                    'response with status ' + response.status);
                }

                return cleanResponse(response).then(function(responseToCache) {
                  return cache.put(cacheKey, responseToCache);
                });
              });
            }
          })
        );
      });
    }).then(function() {

      // Force the SW to transition from installing -> active state
      return self.skipWaiting();

    })
  );
});

self.addEventListener('activate', function(event) {
  var setOfExpectedUrls = new Set(urlsToCacheKeys.values());

  event.waitUntil(
    caches.open(cacheName).then(function(cache) {
      return cache.keys().then(function(existingRequests) {
        return Promise.all(
          existingRequests.map(function(existingRequest) {
            if (!setOfExpectedUrls.has(existingRequest.url)) {
              return cache.delete(existingRequest);
            }
          })
        );
      });
    }).then(function() {

      return self.clients.claim();

    })
  );
});

self.addEventListener('fetch', function(event) {
  if (event.request.method === 'GET') {
    // Should we call event.respondWith() inside this fetch event handler?
    // This needs to be determined synchronously, which will give other fetch
    // handlers a chance to handle the request if need be.
    var shouldRespond;

    // First, remove all the ignored parameter and see if we have that URL
    // in our cache. If so, great! shouldRespond will be true.
    var url = stripIgnoredUrlParameters(event.request.url, ignoreUrlParametersMatching);
    shouldRespond = urlsToCacheKeys.has(url);

    // If shouldRespond is false, check again, this time with 'index.html'
    // (or whatever the directoryIndex option is set to) at the end.
    var directoryIndex = 'index.html';
    if (!shouldRespond && directoryIndex) {
      url = addDirectoryIndex(url, directoryIndex);
      shouldRespond = urlsToCacheKeys.has(url);
    }

    // If shouldRespond is still false, check to see if this is a navigation
    // request, and if so, whether the URL matches navigateFallbackWhitelist.
    var navigateFallback = '';
    if (!shouldRespond &&
        navigateFallback &&
        (event.request.mode === 'navigate') &&
        isPathWhitelisted([], event.request.url)) {
      url = new URL(navigateFallback, self.location).toString();
      shouldRespond = urlsToCacheKeys.has(url);
    }

    // If shouldRespond was set to true at any point, then call
    // event.respondWith(), using the appropriate cache key.
    if (shouldRespond) {
      event.respondWith(
        caches.open(cacheName).then(function(cache) {
          return cache.match(urlsToCacheKeys.get(url)).then(function(response) {
            if (response) {
              return response;
            }
            throw Error('The cached response that was expected is missing.');
          });
        }).catch(function(e) {
          // Fall back to just fetch()ing the request if some unexpected error
          // prevented the cached response from being valid.
          console.warn('Couldn\'t serve response for "%s" from cache: %O', event.request.url, e);
          return fetch(event.request);
        })
      );
    }
  }
});

<commit_msg>Updated with issue #4<commit_after>/**
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

// DO NOT EDIT THIS GENERATED OUTPUT DIRECTLY!
// This file should be overwritten as part of your build process.
// If you need to extend the behavior of the generated service worker, the best approach is to write
// additional code and include it using the importScripts option:
//   https://github.com/GoogleChrome/sw-precache#importscripts-arraystring
//
// Alternatively, it's possible to make changes to the underlying template file and then use that as the
// new base for generating output, via the templateFilePath option:
//   https://github.com/GoogleChrome/sw-precache#templatefilepath-string
//
// If you go that route, make sure that whenever you update your sw-precache dependency, you reconcile any
// changes made to this original template file with your modified copy.

// This generated service worker JavaScript will precache your site's resources.
// The code needs to be saved in a .js file at the top-level of your site, and registered
// from your pages in order to be used. See
// https://github.com/googlechrome/sw-precache/blob/master/demo/app/js/service-worker-registration.js
// for an example of how you can register this script and handle various service worker events.

/* eslint-env worker, serviceworker */
/* eslint-disable indent, no-unused-vars, no-multiple-empty-lines, max-nested-callbacks, space-before-function-paren, quotes, comma-spacing */
'use strict';

var precacheConfig = [["2017/04/04/Issue-1.html","899a67e0e89d9904ad967b8cb5728b39"],["2017/04/11/Issue-2.html","00ef943782c754ff4630ef5b273e333d"],["2017/05/04/Issue-3.html","4a8173cef8177c904e7885d73dd7fbd3"],["2017/05/27/Issue-4.html","349b8d8ae204e2f009144a0d6fb44227"],["404.html","654de47775fc221c5e783dd6f7df044a"],["archives.html","2646ac1ff83f094d44aeb252dae69394"],["codelabs/index.html","c4c18ab3999eba438cf59a57d71d1bfc"],["css/archives.css","f6958fb798d3df57c41b18bafbea2512"],["css/base.css","10c71e1681edcb470318e1d558405060"],["css/issues.css","09ebe3c1cf53f5485753fe87fa50c06d"],["css/main.css","4a726ce9502017fb68e06acf5cbb2101"],["css/menu.css","fd99f071408f5ff4c29de3faa198c280"],["css/modal.css","d91f766c5d64913352bfc34fdbdf08f4"],["css/opensources.css","fc12b6482842758c3b72c88ccdd81913"],["css/reset.css","7e9de0bae21fd193dd472c0d6f549a06"],["css/toast.css","fc3dfe3dc3bbb224a3a95849f583ac92"],["images/banner.png","0c7f1b0bf784a9138327951fae613ed3"],["images/engaging.png","f996517995fb7b9bac65587a3bbfc049"],["images/fast.png","4d3919c4f1630820874c225e4b530ee6"],["images/menu_black.svg","d346927b079c06d3a5364e5a8dd9a62c"],["images/pwa-codelabs.png","99ffcb4fd39c407d4e8d4caa6b7ac01a"],["images/reliable.png","42fb8def018bb3f80a3805226383a57f"],["index.html","51312ea80994c6411444d3bbcd2b0e53"],["js/main.js","0fa0bdcb1878e621a3d440cb0c618bfb"],["js/menu.js","aba5e0ac92bedd7ce29db702399dbdf5"],["opensources.html","5c5a8ece7280ef9ae56d98f37fa4a407"]];
var cacheName = 'sw-precache-v3-sw-precache-' + (self.registration ? self.registration.scope : '');

var ignoreUrlParametersMatching = [/^utm_/];

var addDirectoryIndex = function (originalUrl, index) {
    var url = new URL(originalUrl);
    if (url.pathname.slice(-1) === '/') {
      url.pathname += index;
    }
    return url.toString();
  };

var cleanResponse = function (originalResponse) {
    // If this is not a redirected response, then we don't have to do anything.
    if (!originalResponse.redirected) {
      return Promise.resolve(originalResponse);
    }

    // Firefox 50 and below doesn't support the Response.body stream, so we may
    // need to read the entire body to memory as a Blob.
    var bodyPromise = 'body' in originalResponse ?
      Promise.resolve(originalResponse.body) :
      originalResponse.blob();

    return bodyPromise.then(function(body) {
      // new Response() is happy when passed either a stream or a Blob.
      return new Response(body, {
        headers: originalResponse.headers,
        status: originalResponse.status,
        statusText: originalResponse.statusText
      });
    });
  };

var createCacheKey = function (originalUrl, paramName, paramValue,
                           dontCacheBustUrlsMatching) {
    // Create a new URL object to avoid modifying originalUrl.
    var url = new URL(originalUrl);

    // If dontCacheBustUrlsMatching is not set, or if we don't have a match,
    // then add in the extra cache-busting URL parameter.
    if (!dontCacheBustUrlsMatching ||
        !(url.pathname.match(dontCacheBustUrlsMatching))) {
      url.search += (url.search ? '&' : '') +
        encodeURIComponent(paramName) + '=' + encodeURIComponent(paramValue);
    }

    return url.toString();
  };

var isPathWhitelisted = function (whitelist, absoluteUrlString) {
    // If the whitelist is empty, then consider all URLs to be whitelisted.
    if (whitelist.length === 0) {
      return true;
    }

    // Otherwise compare each path regex to the path of the URL passed in.
    var path = (new URL(absoluteUrlString)).pathname;
    return whitelist.some(function(whitelistedPathRegex) {
      return path.match(whitelistedPathRegex);
    });
  };

var stripIgnoredUrlParameters = function (originalUrl,
    ignoreUrlParametersMatching) {
    var url = new URL(originalUrl);
    // Remove the hash; see https://github.com/GoogleChrome/sw-precache/issues/290
    url.hash = '';

    url.search = url.search.slice(1) // Exclude initial '?'
      .split('&') // Split into an array of 'key=value' strings
      .map(function(kv) {
        return kv.split('='); // Split each 'key=value' string into a [key, value] array
      })
      .filter(function(kv) {
        return ignoreUrlParametersMatching.every(function(ignoredRegex) {
          return !ignoredRegex.test(kv[0]); // Return true iff the key doesn't match any of the regexes.
        });
      })
      .map(function(kv) {
        return kv.join('='); // Join each [key, value] array into a 'key=value' string
      })
      .join('&'); // Join the array of 'key=value' strings into a string with '&' in between each

    return url.toString();
  };

var hashParamName = '_sw-precache';
var urlsToCacheKeys = new Map(
  precacheConfig.map(function(item) {
    var relativeUrl = item[0];
    var hash = item[1];
    var absoluteUrl = new URL(relativeUrl, self.location);
    var cacheKey = createCacheKey(absoluteUrl, hashParamName, hash, false);
    return [absoluteUrl.toString(), cacheKey];
  })
);

function setOfCachedUrls(cache) {
  return cache.keys().then(function(requests) {
    return requests.map(function(request) {
      return request.url;
    });
  }).then(function(urls) {
    return new Set(urls);
  });
}

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(cacheName).then(function(cache) {
      return setOfCachedUrls(cache).then(function(cachedUrls) {
        return Promise.all(
          Array.from(urlsToCacheKeys.values()).map(function(cacheKey) {
            // If we don't have a key matching url in the cache already, add it.
            if (!cachedUrls.has(cacheKey)) {
              var request = new Request(cacheKey, {credentials: 'same-origin'});
              return fetch(request).then(function(response) {
                // Bail out of installation unless we get back a 200 OK for
                // every request.
                if (!response.ok) {
                  throw new Error('Request for ' + cacheKey + ' returned a ' +
                    'response with status ' + response.status);
                }

                return cleanResponse(response).then(function(responseToCache) {
                  return cache.put(cacheKey, responseToCache);
                });
              });
            }
          })
        );
      });
    }).then(function() {

      // Force the SW to transition from installing -> active state
      return self.skipWaiting();

    })
  );
});

self.addEventListener('activate', function(event) {
  var setOfExpectedUrls = new Set(urlsToCacheKeys.values());

  event.waitUntil(
    caches.open(cacheName).then(function(cache) {
      return cache.keys().then(function(existingRequests) {
        return Promise.all(
          existingRequests.map(function(existingRequest) {
            if (!setOfExpectedUrls.has(existingRequest.url)) {
              return cache.delete(existingRequest);
            }
          })
        );
      });
    }).then(function() {

      return self.clients.claim();

    })
  );
});

self.addEventListener('fetch', function(event) {
  if (event.request.method === 'GET') {
    // Should we call event.respondWith() inside this fetch event handler?
    // This needs to be determined synchronously, which will give other fetch
    // handlers a chance to handle the request if need be.
    var shouldRespond;

    // First, remove all the ignored parameters and hash fragment, and see if we
    // have that URL in our cache. If so, great! shouldRespond will be true.
    var url = stripIgnoredUrlParameters(event.request.url, ignoreUrlParametersMatching);
    shouldRespond = urlsToCacheKeys.has(url);

    // If shouldRespond is false, check again, this time with 'index.html'
    // (or whatever the directoryIndex option is set to) at the end.
    var directoryIndex = 'index.html';
    if (!shouldRespond && directoryIndex) {
      url = addDirectoryIndex(url, directoryIndex);
      shouldRespond = urlsToCacheKeys.has(url);
    }

    // If shouldRespond is still false, check to see if this is a navigation
    // request, and if so, whether the URL matches navigateFallbackWhitelist.
    var navigateFallback = '';
    if (!shouldRespond &&
        navigateFallback &&
        (event.request.mode === 'navigate') &&
        isPathWhitelisted([], event.request.url)) {
      url = new URL(navigateFallback, self.location).toString();
      shouldRespond = urlsToCacheKeys.has(url);
    }

    // If shouldRespond was set to true at any point, then call
    // event.respondWith(), using the appropriate cache key.
    if (shouldRespond) {
      event.respondWith(
        caches.open(cacheName).then(function(cache) {
          return cache.match(urlsToCacheKeys.get(url)).then(function(response) {
            if (response) {
              return response;
            }
            throw Error('The cached response that was expected is missing.');
          });
        }).catch(function(e) {
          // Fall back to just fetch()ing the request if some unexpected error
          // prevented the cached response from being valid.
          console.warn('Couldn\'t serve response for "%s" from cache: %O', event.request.url, e);
          return fetch(event.request);
        })
      );
    }
  }
});

<|endoftext|>


<commit_before>/* Magic Mirror
 * Module: MMM-NFL
 *
 * By fewieden https://github.com/fewieden/MMM-NFL
 * MIT Licensed.
 */

Module.register("MMM-NFL", {

    modes: {
        "P": "Pre-Season",
        "R": "Regular-Season",
        "POST": "Post-Season"
    },

    details: {
        y: (new Date()).getFullYear(),
        t: "P"
    },

    states: {
        "1": "1ST_QUARTER",
        "2": "2ND_QUARTER",
        "3": "3RD_QUARTER",
        "4": "4th_QUARTER",
        "H": "HALF_TIME",
        "OT": "OVER_TIME",
        "F": "FINAL",
        "FO": "FINAL_OVERTIME",
        "T": "TIE",
        "P": "UPCOMING"
    },

    defaults: {
        colored: false,
        helmets: false,
        network: true,
        focus_on: false,
        format: "ddd h:mm",
        reloadInterval: 30 * 60 * 1000       // every 30 minutes
    },

    statistics: false,
    help: false,

    voice: {
        mode: "FOOTBALL",
        sentences: [
            "OPEN HELP",
            "CLOSE HELP",
            "SHOW HELMETS",
            "SHOW LOGOS",
            "COLOR ON",
            "COLOR OFF",
            "NETWORK ON",
            "NETWORK OFF",
            "SHOW PASSING YARDS STATISTIC",
            "SHOW RUSHING YARDS STATISTIC",
            "SHOW RECEIVING YARDS STATISTIC",
            "SHOW TACKLES STATISTIC",
            "SHOW SACKS STATISTIC",
            "SHOW INTERCEPTIONS STATISTIC",
            "HIDE STATISTIC"
        ]
    },

    getTranslations: function () {
        return {
            en: "translations/en.json",
            de: "translations/de.json"
        };
    },

    getScripts: function() {
        return ["moment.js"];
    },

    getStyles: function () {
        return ["font-awesome.css", "MMM-NFL.css"];
    },

    start: function () {
        Log.info("Starting module: " + this.name);
        this.sendSocketNotification("CONFIG", this.config);
        moment.locale(config.language);
    },

    notificationReceived: function (notification, payload, sender) {
        if(notification === "ALL_MODULES_STARTED"){
            this.sendNotification("REGISTER_VOICE_MODULE", this.voice);
        } else if(notification === "VOICE_FOOTBALL" && sender.name === "MMM-voice"){
            this.checkCommands(payload);
        }
    },

    socketNotificationReceived: function (notification, payload) {
        if (notification === "SCORES") {
            this.scores = payload.scores;
            this.details = payload.details;
            this.updateDom(300);
        } else if(notification === "STATISTICS"){
            this.help = false;
            this.statistics = payload;
            this.updateDom(300);
        }
    },

    checkCommands: function(data){
        if(/(HELP)/g.test(data)){
            if(/(OPEN)/g.test(data) || !this.help && !/(CLOSE)/g.test(data)){
                this.statistics = false;
                this.help = true;
            } else if(/(CLOSE)/g.test(data) || this.help && !/(OPEN)/g.test(data)){
                this.help = false;
            }
        } else if(/(HELMETS)/g.test(data)){
            this.config.helmets = true;
        } else if(/(LOGOS)/g.test(data)){
            this.config.helmets = false;
        } else if(/(COLOR)/g.test(data)){
            if(/(ON)/g.test(data) || !this.config.colored && !/(OFF)/g.test(data)){
                this.config.colored = true;
            } else if(/(OFF)/g.test(data) || this.config.colored && !/(ON)/g.test(data)){
                this.config.colored = false;
            }
        } else if(/(NETWORK)/g.test(data)){
            if(/(ON)/g.test(data) || !this.config.network && !/(OFF)/g.test(data)){
                this.config.network = true;
            } else if(/(OFF)/g.test(data) || this.config.network && !/(ON)/g.test(data)){
                this.config.network = false;
            }
        } else if(/(STATISTIC)/g.test(data)){
            if(/(HIDE)/g.test(data)){
                this.statistics = false;
            } else if(/(PASSING)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Passing Yards");
            } else if(/(RUSHING)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Rushing Yards");
            } else if(/(RECEIVING)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Receiving Yards");
            } else if(/(TACKLES)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Tackles");
            } else if(/(SACKS)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Sacks");
            } else if(/(INTERCEPTIONS)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Interceptions");
            }
        }
        this.updateDom(300);
    },

    getDom: function () {

        var wrapper = document.createElement("div");
        var scores = document.createElement("div");
        var header = document.createElement("header");
        header.innerHTML = "NFL " + this.modes[this.details.t] + " " + this.details.y;
        scores.appendChild(header);

        if (!this.scores) {
            var text = document.createElement("div");
            text.innerHTML = this.translate("LOADING");
            text.classList.add("dimmed", "light");
            scores.appendChild(text);
        } else {
            var table = document.createElement("table");
            table.classList.add("small", "table");

            table.appendChild(this.createLabelRow());

            for (var i = 0; i < this.scores.length; i++) {
                this.appendDataRow(this.scores[i].$, table);
            }

            scores.appendChild(table);

            var modules = document.querySelectorAll(".module");
            for (var i = 0; i < modules.length; i++) {
                if(!modules[i].classList.contains("MMM-NFL")){
                    if(this.statistics || this.help){
                        modules[i].classList.add("MMM-NFL-blur");
                    } else {
                        modules[i].classList.remove("MMM-NFL-blur");
                    }
                }
            }

            if(this.statistics || this.help){
                scores.classList.add("MMM-NFL-blur");
                var modal = document.createElement("div");
                modal.classList.add("modal");
                if(this.statistics){
                    this.appendStatistics(modal);
                } else {
                    this.appendHelp(modal);
                }
                wrapper.appendChild(modal);
            }
        }

        wrapper.appendChild(scores);

        return wrapper;
    },

    createLabelRow: function () {
        var labelRow = document.createElement("tr");

        var dateLabel = document.createElement("th");
        var dateIcon = document.createElement("i");
        dateIcon.classList.add("fa", "fa-calendar");
        dateLabel.appendChild(dateIcon);
        labelRow.appendChild(dateLabel);

        var homeLabel = document.createElement("th");
        homeLabel.innerHTML = this.translate("HOME");
        homeLabel.setAttribute("colspan", 3);
        labelRow.appendChild(homeLabel);

        var vsLabel = document.createElement("th");
        vsLabel.innerHTML = "";
        labelRow.appendChild(vsLabel);

        var awayLabel = document.createElement("th");
        awayLabel.innerHTML = this.translate("AWAY");
        awayLabel.setAttribute("colspan", 3);
        labelRow.appendChild(awayLabel);

        if(this.config.network){
            var tvLabel = document.createElement("th");
            var tvIcon = document.createElement("i");
            tvIcon.classList.add("fa", "fa-television", "dimmed");
            tvLabel.appendChild(tvIcon);
            labelRow.appendChild(tvLabel);
        }

        return labelRow;
    },

    appendDataRow: function (data, appendTo) {
        if(!this.config.focus_on || this.config.focus_on.indexOf(data.h) !== -1 || this.config.focus_on.indexOf(data.v) !== -1) {
            var row = document.createElement("tr");
            row.classList.add("row");

            var date = document.createElement("td");
            if (data.q in ["1", "2", "3", "4", "H", "OT"]) {
                var quarter = document.createElement("div");
                quarter.innerHTML = this.translate(this.states[data.q]);
                if (data.hasOwnProperty("k")) {
                    quarter.classList.add("live");
                    date.appendChild(quarter);
                    var time = document.createElement("div");
                    time.classList.add("live");
                    time.innerHTML = data.k + ' ' + this.translate('TIME_LEFT');
                    date.appendChild(time);
                } else {
                    date.appendChild(quarter);
                }
            } else if (data.q === "P") {
                date.innerHTML = moment(data.starttime).format(this.config.format);
            } else {
                date.innerHTML = this.translate(this.states[data.q]);
                date.classList.add("dimmed");
            }
            row.appendChild(date);

            var homeTeam = document.createElement("td");
            homeTeam.classList.add("align-right");
            this.appendBallPossession(data, true, homeTeam);
            var homeTeamSpan = document.createElement("span");
            homeTeamSpan.innerHTML = data.h;
            homeTeam.appendChild(homeTeamSpan);
            row.appendChild(homeTeam);

            var homeLogo = document.createElement("td");
            var homeIcon = document.createElement("img");
            homeIcon.src = this.file("icons/" + data.h + (this.config.helmets ? "_helmet" : "") + ".png");
            if (!this.config.colored) {
                homeIcon.classList.add("icon");
            }
            homeLogo.appendChild(homeIcon);
            row.appendChild(homeLogo);

            var homeScore = document.createElement("td");
            homeScore.innerHTML = data.hs;
            row.appendChild(homeScore);

            var vs = document.createElement("td");
            vs.innerHTML = ":";
            row.appendChild(vs);

            var awayScore = document.createElement("td");
            awayScore.innerHTML = data.vs;
            row.appendChild(awayScore);

            var awayLogo = document.createElement("td");
            var awayIcon = document.createElement("img");
            awayIcon.src = this.file("icons/" + data.v + (this.config.helmets ? "_helmet" : "") + ".png");
            if (!this.config.colored) {
                awayIcon.classList.add("icon");
            }
            if (this.config.helmets) {
                awayIcon.classList.add("away");
            }
            awayLogo.appendChild(awayIcon);
            row.appendChild(awayLogo);

            var awayTeam = document.createElement("td");
            awayTeam.classList.add("align-left");
            var awayTeamSpan = document.createElement("span");
            awayTeamSpan.innerHTML = data.v;
            awayTeam.appendChild(awayTeamSpan);
            this.appendBallPossession(data, false, awayTeam);
            row.appendChild(awayTeam);

            if (this.config.network) {
                var tv = document.createElement("td");
                tv.classList.add("dimmed");
                tv.innerHTML = data.hasOwnProperty("n") ? data.n : "X";
                row.appendChild(tv);
            }

            appendTo.appendChild(row);
        }
    },

    appendBallPossession: function(data, homeTeam, appendTo){
        var team = homeTeam ? data.h : data.v;
        if(data.p === team){
            var ballIcon = document.createElement("img");
            ballIcon.src = this.file("icons/football.png");
            if(homeTeam){
                ballIcon.classList.add("ball-home");
            } else {
                ballIcon.classList.add("ball-away");
            }
            if(data.rz === "1"){
                ballIcon.classList.add("redzone");
            }
            appendTo.appendChild(ballIcon);
        }
    },

    appendStatistics: function(appendTo){
        var type = document.createElement("div");
        type.classList.add("large");
        type.innerHTML = this.statistics.type;
        appendTo.appendChild(type);

        var table = document.createElement("table");
        table.classList.add("medium", "table");

        var labelRow = document.createElement("tr");

        var posLabel = document.createElement("th");
        posLabel.innerHTML = "#";
        labelRow.appendChild(posLabel);

        var playerLabel = document.createElement("th");
        playerLabel.innerHTML = this.translate("PLAYER");
        labelRow.appendChild(playerLabel);

        var teamLabel = document.createElement("th");
        teamLabel.setAttribute("colspan", 2);
        teamLabel.innerHTML = this.translate("TEAM");
        labelRow.appendChild(teamLabel);

        var unitLabel = document.createElement("th");
        unitLabel.innerHTML = this.statistics.data.unit;
        labelRow.appendChild(unitLabel);

        table.appendChild(labelRow);

        for (var i = 0; i < this.statistics.data.players.length; i++) {
            var row = document.createElement("tr");
            row.classList.add("row");

            var position = document.createElement("td");
            position.innerHTML = this.statistics.data.players[i].position;
            row.appendChild(position);

            var player = document.createElement("td");
            player.classList.add("align-left");
            player.innerHTML = this.statistics.data.players[i].player;
            row.appendChild(player);

            var teamName = document.createElement("td");
            teamName.innerHTML = this.statistics.data.players[i].team;
            row.appendChild(teamName);

            var team = document.createElement("td");
            var teamIcon = document.createElement("img");
            teamIcon.src = this.file("icons/" + this.statistics.data.players[i].team + (this.config.helmets ? "_helmet" : "") + ".png");
            if (!this.config.colored) {
                teamIcon.classList.add("icon");
            }
            team.appendChild(teamIcon);
            row.appendChild(team);

            var value = document.createElement("td");
            value.innerHTML = this.statistics.data.players[i].value;
            row.appendChild(value);

            table.appendChild(row);
        }

        appendTo.appendChild(table);
    },

    appendHelp: function(appendTo){
        var title = document.createElement("h1");
        title.classList.add("medium");
        title.innerHTML = this.name + " - " + this.translate("COMMAND_LIST");
        appendTo.appendChild(title);

        var mode = document.createElement("div");
        mode.innerHTML = this.translate("MODE") + ": " + this.voice.mode;
        appendTo.appendChild(mode);

        var listLabel = document.createElement("div");
        listLabel.innerHTML = this.translate("VOICE_COMMANDS") + ":";
        appendTo.appendChild(listLabel);

        var list = document.createElement("ul");
        for(var i = 0; i < this.voice.sentences.length; i++){
            var item = document.createElement("li");
            item.innerHTML = this.voice.sentences[i];
            list.appendChild(item);
        }
        appendTo.appendChild(list);
    }
});<commit_msg>close modals when mode gets changed<commit_after>/* Magic Mirror
 * Module: MMM-NFL
 *
 * By fewieden https://github.com/fewieden/MMM-NFL
 * MIT Licensed.
 */

Module.register("MMM-NFL", {

    modes: {
        "P": "Pre-Season",
        "R": "Regular-Season",
        "POST": "Post-Season"
    },

    details: {
        y: (new Date()).getFullYear(),
        t: "P"
    },

    states: {
        "1": "1ST_QUARTER",
        "2": "2ND_QUARTER",
        "3": "3RD_QUARTER",
        "4": "4th_QUARTER",
        "H": "HALF_TIME",
        "OT": "OVER_TIME",
        "F": "FINAL",
        "FO": "FINAL_OVERTIME",
        "T": "TIE",
        "P": "UPCOMING"
    },

    defaults: {
        colored: false,
        helmets: false,
        network: true,
        focus_on: false,
        format: "ddd h:mm",
        reloadInterval: 30 * 60 * 1000       // every 30 minutes
    },

    statistics: false,
    help: false,

    voice: {
        mode: "FOOTBALL",
        sentences: [
            "OPEN HELP",
            "CLOSE HELP",
            "SHOW HELMETS",
            "SHOW LOGOS",
            "COLOR ON",
            "COLOR OFF",
            "NETWORK ON",
            "NETWORK OFF",
            "SHOW PASSING YARDS STATISTIC",
            "SHOW RUSHING YARDS STATISTIC",
            "SHOW RECEIVING YARDS STATISTIC",
            "SHOW TACKLES STATISTIC",
            "SHOW SACKS STATISTIC",
            "SHOW INTERCEPTIONS STATISTIC",
            "HIDE STATISTIC"
        ]
    },

    getTranslations: function () {
        return {
            en: "translations/en.json",
            de: "translations/de.json"
        };
    },

    getScripts: function() {
        return ["moment.js"];
    },

    getStyles: function () {
        return ["font-awesome.css", "MMM-NFL.css"];
    },

    start: function () {
        Log.info("Starting module: " + this.name);
        this.sendSocketNotification("CONFIG", this.config);
        moment.locale(config.language);
    },

    notificationReceived: function (notification, payload, sender) {
        if(notification === "ALL_MODULES_STARTED"){
            this.sendNotification("REGISTER_VOICE_MODULE", this.voice);
        } else if(notification === "VOICE_FOOTBALL" && sender.name === "MMM-voice"){
            this.checkCommands(payload);
        } else if(notification === "VOICE_MODE_CHANGED" && sender.name === "MMM-voice" && payload.old === this.voice.mode){
            this.help = false;
            this.statistics = false;
            this.updateDom(300);
        }
    },

    socketNotificationReceived: function (notification, payload) {
        if (notification === "SCORES") {
            this.scores = payload.scores;
            this.details = payload.details;
            this.updateDom(300);
        } else if(notification === "STATISTICS"){
            this.help = false;
            this.statistics = payload;
            this.updateDom(300);
        }
    },

    checkCommands: function(data){
        if(/(HELP)/g.test(data)){
            if(/(OPEN)/g.test(data) || !this.help && !/(CLOSE)/g.test(data)){
                this.statistics = false;
                this.help = true;
            } else if(/(CLOSE)/g.test(data) || this.help && !/(OPEN)/g.test(data)){
                this.help = false;
            }
        } else if(/(HELMETS)/g.test(data)){
            this.config.helmets = true;
        } else if(/(LOGOS)/g.test(data)){
            this.config.helmets = false;
        } else if(/(COLOR)/g.test(data)){
            if(/(ON)/g.test(data) || !this.config.colored && !/(OFF)/g.test(data)){
                this.config.colored = true;
            } else if(/(OFF)/g.test(data) || this.config.colored && !/(ON)/g.test(data)){
                this.config.colored = false;
            }
        } else if(/(NETWORK)/g.test(data)){
            if(/(ON)/g.test(data) || !this.config.network && !/(OFF)/g.test(data)){
                this.config.network = true;
            } else if(/(OFF)/g.test(data) || this.config.network && !/(ON)/g.test(data)){
                this.config.network = false;
            }
        } else if(/(STATISTIC)/g.test(data)){
            if(/(HIDE)/g.test(data)){
                this.statistics = false;
            } else if(/(PASSING)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Passing Yards");
            } else if(/(RUSHING)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Rushing Yards");
            } else if(/(RECEIVING)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Receiving Yards");
            } else if(/(TACKLES)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Tackles");
            } else if(/(SACKS)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Sacks");
            } else if(/(INTERCEPTIONS)/g.test(data)){
                this.sendSocketNotification("GET_STATISTICS", "Interceptions");
            }
        }
        this.updateDom(300);
    },

    getDom: function () {

        var wrapper = document.createElement("div");
        var scores = document.createElement("div");
        var header = document.createElement("header");
        header.innerHTML = "NFL " + this.modes[this.details.t] + " " + this.details.y;
        scores.appendChild(header);

        if (!this.scores) {
            var text = document.createElement("div");
            text.innerHTML = this.translate("LOADING");
            text.classList.add("dimmed", "light");
            scores.appendChild(text);
        } else {
            var table = document.createElement("table");
            table.classList.add("small", "table");

            table.appendChild(this.createLabelRow());

            for (var i = 0; i < this.scores.length; i++) {
                this.appendDataRow(this.scores[i].$, table);
            }

            scores.appendChild(table);

            var modules = document.querySelectorAll(".module");
            for (var i = 0; i < modules.length; i++) {
                if(!modules[i].classList.contains("MMM-NFL")){
                    if(this.statistics || this.help){
                        modules[i].classList.add("MMM-NFL-blur");
                    } else {
                        modules[i].classList.remove("MMM-NFL-blur");
                    }
                }
            }

            if(this.statistics || this.help){
                scores.classList.add("MMM-NFL-blur");
                var modal = document.createElement("div");
                modal.classList.add("modal");
                if(this.statistics){
                    this.appendStatistics(modal);
                } else {
                    this.appendHelp(modal);
                }
                wrapper.appendChild(modal);
            }
        }

        wrapper.appendChild(scores);

        return wrapper;
    },

    createLabelRow: function () {
        var labelRow = document.createElement("tr");

        var dateLabel = document.createElement("th");
        var dateIcon = document.createElement("i");
        dateIcon.classList.add("fa", "fa-calendar");
        dateLabel.appendChild(dateIcon);
        labelRow.appendChild(dateLabel);

        var homeLabel = document.createElement("th");
        homeLabel.innerHTML = this.translate("HOME");
        homeLabel.setAttribute("colspan", 3);
        labelRow.appendChild(homeLabel);

        var vsLabel = document.createElement("th");
        vsLabel.innerHTML = "";
        labelRow.appendChild(vsLabel);

        var awayLabel = document.createElement("th");
        awayLabel.innerHTML = this.translate("AWAY");
        awayLabel.setAttribute("colspan", 3);
        labelRow.appendChild(awayLabel);

        if(this.config.network){
            var tvLabel = document.createElement("th");
            var tvIcon = document.createElement("i");
            tvIcon.classList.add("fa", "fa-television", "dimmed");
            tvLabel.appendChild(tvIcon);
            labelRow.appendChild(tvLabel);
        }

        return labelRow;
    },

    appendDataRow: function (data, appendTo) {
        if(!this.config.focus_on || this.config.focus_on.indexOf(data.h) !== -1 || this.config.focus_on.indexOf(data.v) !== -1) {
            var row = document.createElement("tr");
            row.classList.add("row");

            var date = document.createElement("td");
            if (data.q in ["1", "2", "3", "4", "H", "OT"]) {
                var quarter = document.createElement("div");
                quarter.innerHTML = this.translate(this.states[data.q]);
                if (data.hasOwnProperty("k")) {
                    quarter.classList.add("live");
                    date.appendChild(quarter);
                    var time = document.createElement("div");
                    time.classList.add("live");
                    time.innerHTML = data.k + ' ' + this.translate('TIME_LEFT');
                    date.appendChild(time);
                } else {
                    date.appendChild(quarter);
                }
            } else if (data.q === "P") {
                date.innerHTML = moment(data.starttime).format(this.config.format);
            } else {
                date.innerHTML = this.translate(this.states[data.q]);
                date.classList.add("dimmed");
            }
            row.appendChild(date);

            var homeTeam = document.createElement("td");
            homeTeam.classList.add("align-right");
            this.appendBallPossession(data, true, homeTeam);
            var homeTeamSpan = document.createElement("span");
            homeTeamSpan.innerHTML = data.h;
            homeTeam.appendChild(homeTeamSpan);
            row.appendChild(homeTeam);

            var homeLogo = document.createElement("td");
            var homeIcon = document.createElement("img");
            homeIcon.src = this.file("icons/" + data.h + (this.config.helmets ? "_helmet" : "") + ".png");
            if (!this.config.colored) {
                homeIcon.classList.add("icon");
            }
            homeLogo.appendChild(homeIcon);
            row.appendChild(homeLogo);

            var homeScore = document.createElement("td");
            homeScore.innerHTML = data.hs;
            row.appendChild(homeScore);

            var vs = document.createElement("td");
            vs.innerHTML = ":";
            row.appendChild(vs);

            var awayScore = document.createElement("td");
            awayScore.innerHTML = data.vs;
            row.appendChild(awayScore);

            var awayLogo = document.createElement("td");
            var awayIcon = document.createElement("img");
            awayIcon.src = this.file("icons/" + data.v + (this.config.helmets ? "_helmet" : "") + ".png");
            if (!this.config.colored) {
                awayIcon.classList.add("icon");
            }
            if (this.config.helmets) {
                awayIcon.classList.add("away");
            }
            awayLogo.appendChild(awayIcon);
            row.appendChild(awayLogo);

            var awayTeam = document.createElement("td");
            awayTeam.classList.add("align-left");
            var awayTeamSpan = document.createElement("span");
            awayTeamSpan.innerHTML = data.v;
            awayTeam.appendChild(awayTeamSpan);
            this.appendBallPossession(data, false, awayTeam);
            row.appendChild(awayTeam);

            if (this.config.network) {
                var tv = document.createElement("td");
                tv.classList.add("dimmed");
                tv.innerHTML = data.hasOwnProperty("n") ? data.n : "X";
                row.appendChild(tv);
            }

            appendTo.appendChild(row);
        }
    },

    appendBallPossession: function(data, homeTeam, appendTo){
        var team = homeTeam ? data.h : data.v;
        if(data.p === team){
            var ballIcon = document.createElement("img");
            ballIcon.src = this.file("icons/football.png");
            if(homeTeam){
                ballIcon.classList.add("ball-home");
            } else {
                ballIcon.classList.add("ball-away");
            }
            if(data.rz === "1"){
                ballIcon.classList.add("redzone");
            }
            appendTo.appendChild(ballIcon);
        }
    },

    appendStatistics: function(appendTo){
        var type = document.createElement("div");
        type.classList.add("large");
        type.innerHTML = this.statistics.type;
        appendTo.appendChild(type);

        var table = document.createElement("table");
        table.classList.add("medium", "table");

        var labelRow = document.createElement("tr");

        var posLabel = document.createElement("th");
        posLabel.innerHTML = "#";
        labelRow.appendChild(posLabel);

        var playerLabel = document.createElement("th");
        playerLabel.innerHTML = this.translate("PLAYER");
        labelRow.appendChild(playerLabel);

        var teamLabel = document.createElement("th");
        teamLabel.setAttribute("colspan", 2);
        teamLabel.innerHTML = this.translate("TEAM");
        labelRow.appendChild(teamLabel);

        var unitLabel = document.createElement("th");
        unitLabel.innerHTML = this.statistics.data.unit;
        labelRow.appendChild(unitLabel);

        table.appendChild(labelRow);

        for (var i = 0; i < this.statistics.data.players.length; i++) {
            var row = document.createElement("tr");
            row.classList.add("row");

            var position = document.createElement("td");
            position.innerHTML = this.statistics.data.players[i].position;
            row.appendChild(position);

            var player = document.createElement("td");
            player.classList.add("align-left");
            player.innerHTML = this.statistics.data.players[i].player;
            row.appendChild(player);

            var teamName = document.createElement("td");
            teamName.innerHTML = this.statistics.data.players[i].team;
            row.appendChild(teamName);

            var team = document.createElement("td");
            var teamIcon = document.createElement("img");
            teamIcon.src = this.file("icons/" + this.statistics.data.players[i].team + (this.config.helmets ? "_helmet" : "") + ".png");
            if (!this.config.colored) {
                teamIcon.classList.add("icon");
            }
            team.appendChild(teamIcon);
            row.appendChild(team);

            var value = document.createElement("td");
            value.innerHTML = this.statistics.data.players[i].value;
            row.appendChild(value);

            table.appendChild(row);
        }

        appendTo.appendChild(table);
    },

    appendHelp: function(appendTo){
        var title = document.createElement("h1");
        title.classList.add("medium");
        title.innerHTML = this.name + " - " + this.translate("COMMAND_LIST");
        appendTo.appendChild(title);

        var mode = document.createElement("div");
        mode.innerHTML = this.translate("MODE") + ": " + this.voice.mode;
        appendTo.appendChild(mode);

        var listLabel = document.createElement("div");
        listLabel.innerHTML = this.translate("VOICE_COMMANDS") + ":";
        appendTo.appendChild(listLabel);

        var list = document.createElement("ul");
        for(var i = 0; i < this.voice.sentences.length; i++){
            var item = document.createElement("li");
            item.innerHTML = this.voice.sentences[i];
            list.appendChild(item);
        }
        appendTo.appendChild(list);
    }
});<|endoftext|>


<commit_before>define([
  'jquery' /* $ */,
  'jquery.instructure_misc_plugins' /* fragmentChange */,
  'jquery.templateData' /* getTemplateData */,
  'vendor/jquery.scrollTo' /* /\.scrollTo/ */,
  'compiled/behaviors/quiz_selectmenu'
], function($) {

  var parentWindow = {
    exists: function(){
      return (window.parent && window.parent.INST);
    },

    respondsTo: function(funcName){
      return (parentWindow.exists() && $.isFunction(window.parent.INST[funcName]));
    },

    hasProperty: function(propName){
      return (parentWindow.exists() && window.parent.INST[propName]);
    },

    set: function(propName, value){
      if(parentWindow.exists()){
        window.parent.INST[propName] = value;
      }
    },

    get: function(propName){
      if(parentWindow.hasProperty(propName)){
        return window.parent.INST[propName];
      }
    }
  };
  // end parentWindow object

  var data = $("#submission_details").getTemplateData({textValues: ['version_number', 'user_id']});

  var scoringSnapshot = {
    snapshot: {
      user_id: data.user_id || null,
      version_number: data.version_number,
      last_question_touched: null,
      question_updates: {},
      fudge_points: 0
    },

    $quizBody: null,

    jumpPosition: function(question_id) {
      $question = $("#question_" + question_id);
      if($question.length > 0) {
        return $question.offset().top - 110;
      } else {
        return 0;
      }
    },

    checkQuizBody: function() {
      if(scoringSnapshot.$quizBody === null){
        scoringSnapshot.$quizBody = $('html,body');
      }
    },

    // Animates scrolling to question if there is no page reload
    jumpToQuestion: function(question_id) {
      var top = scoringSnapshot.jumpPosition(question_id);
      scoringSnapshot.checkQuizBody();
      scoringSnapshot.$quizBody.stop();
      scoringSnapshot.$quizBody.clearQueue();
      scoringSnapshot.$quizBody.animate({scrollTop: top}, 500);
    },

    // Jumps directly to question upon a page reload
    jumpDirectlyToQuestion: function(question_id) {
      var top = scoringSnapshot.jumpPosition(question_id);
      scoringSnapshot.checkQuizBody();
      scoringSnapshot.$quizBody.scrollTop(top);
    },

    externallySet: false,

    setSnapshot: function(data, cancelIfAlreadyExternallySet) {
      if(data) {
        if(cancelIfAlreadyExternallySet && scoringSnapshot.externallySet) { return; }
        scoringSnapshot.externallySet = true;
        scoringSnapshot.snapshot = data;
        for(var idx in data.question_updates) {
          var question = data.question_updates[idx];
          var $question = $("#question_" + idx);
          if (!ENV.GRADE_BY_QUESTION) {
            $question.addClass('modified_but_not_saved');
          }
          $question.find(".user_points :text").val(question.points).end()
            .find(".question_neutral_comment .question_comment_text textarea").val(question.comments);
        }
        if(parentWindow.hasProperty('lastQuestionTouched') && !ENV.GRADE_BY_QUESTION) {
          scoringSnapshot.jumpToQuestion(window.parent.INST.lastQuestionTouched);
        } else if(scoringSnapshot.snapshot.last_question_touched && !ENV.GRADE_BY_QUESTION) {
          scoringSnapshot.jumpToQuestion(scoringSnapshot.snapshot.last_question_touched);
        }
      } else if(cancelIfAlreadyExternallySet) {
        if(parentWindow.hasProperty('lastQuestionTouched') && !ENV.GRADE_BY_QUESTION) {
          scoringSnapshot.jumpToQuestion(window.parent.INST.lastQuestionTouched);
        }
      }
      if(scoringSnapshot.externallySet || cancelIfAlreadyExternallySet) {
        $("#feel_free_to_toggle_message").show();
      }
      if(parentWindow.respondsTo('refreshQuizSubmissionSnapshot')) {
        window.parent.INST.refreshQuizSubmissionSnapshot(scoringSnapshot.snapshot);
      }
    },

    update: function(question_id, data){
      scoringSnapshot.snapshot.question_updates[question_id] = data;
      scoringSnapshot.snapshot.last_question_touched = question_id;
      scoringSnapshot.setSnapshot();
    }
  }
  //end of scoringSnapshot object

  var gradingForm = {
    ensureSelectEventsFire: function(){
      $("input[type=text]").focus(function() {
        $(this).select();
      });
    },

    scrollToUpdatedQuestion: function(event, hash) {
      if(hash.indexOf("#question") == 0) {
        var id = hash.substring(10);
        scoringSnapshot.jumpToQuestion(id);
      }
    },

    updateSnapshotFor: function($question){
      var question_id = $question.attr('id').substring(9) || null;
      if(question_id) {
        var data = {};
        if (!ENV.GRADE_BY_QUESTION) {
          $question.addClass('modified_but_not_saved');
        }
        data.points = parseFloat($question.find(".user_points :text").val(), 10);
        data.comments = $question.find(".question_neutral_comment .question_comment_text textarea").val() || "";
        scoringSnapshot.update(question_id, data);
      }
      $(document).triggerHandler('score_changed');
    },

    addFudgePoints: function(points){
      if(points || points === 0) {
        scoringSnapshot.snapshot.fudge_points = points;
        scoringSnapshot.setSnapshot();
      }
      $(document).triggerHandler('score_changed');
    },

    setInitialSnapshot: function(data){
      $("#feel_free_to_toggle_message").show();
      if(data) {
        scoringSnapshot.setSnapshot(data);
      } else {
        scoringSnapshot.setSnapshot(null, true);
      }
    },

    onScoreChanged: function(){
      var $total = $("#after_fudge_points_total");
      var total = 0;
      $(".display_question .user_points:visible").each(function() {
        var points = parseFloat($(this).find("input[type=number]").val(), 10) || 0;
        points = Math.round(points * 100.0) / 100.0;
        total = total + points;
      });
      var fudge = (parseFloat($("#fudge_points_entry").val(), 10) || 0);
      fudge = Math.round(fudge * 100.0) / 100.0;
      total = total + fudge;
      $total.text(total || "0");
    },

    questions: function(){
      return $('.question_holder').map(function(index, el) {
        return $(el).position().top - 320;
      }).toArray();
    },

    onScroll: function(){
      var qNum = quizNavBar.activateCorrectLink();
      quizNavBar.toggleDropShadow();
    },

    onWindowResize: function(){
      //Add padding to the bottom of the last question
      var winHeight = $(window).innerHeight();
      var lastHeight = $('div.question_holder:last-child').outerHeight();
      var fixedButtonHeight = $('#speed_update_scores_container').outerHeight();
      var paddingHeight = Math.max(winHeight - lastHeight - 150, fixedButtonHeight);
      $('#update_history_form .quiz-submission.headless').css('marginBottom', paddingHeight + 'px');
    }

  };
  //end of gradingForm object

  var quizNavBar = {
    index: 0,
    windowSize: 10,
    minWidth: 66,
    startingLeftPos: 32,
    navItemWidth: 34,

    initialize: function(){
      $('.user_points > .question_input').each(function(index){
        quizNavBar.updateStatusFor($(this));
      });

      if (ENV.GRADE_BY_QUESTION) {
        var questionIndex = parseInt(parentWindow.get('active_question_index'));
        var questionId = $('.q' + questionIndex).data('id');
        if(!isNaN(questionId)){
          scoringSnapshot.jumpDirectlyToQuestion(questionId);
        }
      }

      quizNavBar.updateWindowSize();
      quizNavBar.setScrollWindowPosition(0);
    },

    size: function(){
      return $('.question-nav-link').length;
    },

    tooBig: function(){
      return quizNavBar.size() > quizNavBar.windowSize;
    },

    updateWindowSize: function(){
      var fullWidth = $('.quiz-nav, .quiz-nav-fullpage').width();
      var minPadding = 10;
      var maxWidth = fullWidth - (minPadding * 2);
      var itemCount = Math.floor((maxWidth - quizNavBar.minWidth) / quizNavBar.navItemWidth);
      quizNavBar.windowSize = itemCount;
      var actualWidth = (itemCount * quizNavBar.navItemWidth) + quizNavBar.minWidth;
      $('.quiz-nav .nav, .quiz-nav-fullpage .nav').animate({width: actualWidth + 'px'}, 10);
    },

    navArrowCache: null,

    $navArrows: function(){
      if(quizNavBar.navArrowCache === null){
        quizNavBar.navArrowCache = $('.quiz-nav .nav-arrow, .quiz-nav-fullpage .nav-arrow');
      }
      return quizNavBar.navArrowCache;
    },

    navWrapperCache: null,

    $navWrapper: function(){
      if(quizNavBar.navWrapperCache === null){
        quizNavBar.navWrapperCache = $('#quiz-nav-inner-wrapper');
      }
      return quizNavBar.navWrapperCache;
    },

    updateArrows: function(){
      if(quizNavBar.tooBig()){
        quizNavBar.$navArrows().show();
        quizNavBar.$navWrapper().css({position: 'absolute'});
      } else {
        quizNavBar.$navArrows().hide();
        quizNavBar.$navWrapper().css({position: 'relative'});
      }
    },

    toggleDropShadow: function(){
      //Add shadow to top bar
      $('.quiz-nav').toggleClass('drshadow', ($(document).scrollTop() > 0));
    },

    updateStatusFor: function($scoreInput){
      try{
        var questionId = $scoreInput.attr('name').split('_')[2];
        var scoreValue = $scoreInput.val();
        $('#quiz_nav_' + questionId).toggleClass('complete', (!isNaN(parseFloat(scoreValue))));
      } catch(err) {
        // do nothing; if there's no status to update, continue with other execution
      }
    },

    activateLink: function(index){
      $('.quiz-nav li').removeClass('active');
      $('.q' + index).addClass('active');
    },

    activateCorrectLink: function(){
      var qNum = 1;
      var qArray = gradingForm.questions();
      var docScroll = $(document).scrollTop();
      var maxScroll = $(document).height() - $('body').height();
      if (docScroll >= maxScroll) {
        qNum = qArray.length;
        quizNavBar.activateLink(qNum);
      } else {
        $questions = $('.question')
        for(var t = 0; t <= qArray.length; t++) {
          $question = $($questions[t])
          qNum = t + 1;
          if ( (docScroll > qArray[t] && docScroll < qArray[t+1])  || ( t == (qArray.length - 1) && docScroll > qArray[t])) {
            parentWindow.set('active_question_index', qNum);
            quizNavBar.activateLink(qNum);
            $question.addClass('selected_single_question');
          } else {
            $('.q'+ qNum).removeClass('active');
            $question.removeClass('selected_single_question');
          }
        }
      }
      quizNavBar.setScrollWindowPosition(qNum);
      return qNum;
    },

    showQuestionsInWindow: function(startingIndex, endingIndex){
      var $navWrapper = $('#quiz-nav-inner-wrapper');
      var leftPosition = quizNavBar.startingLeftPos - (startingIndex * quizNavBar.navItemWidth);
      var newPos = '' + leftPosition + 'px';
      var currentPos = $navWrapper.css('left');
      if(newPos !== currentPos){
        $navWrapper.stop();
        $navWrapper.clearQueue();
        $navWrapper.animate({left: leftPosition + 'px'}, 300);
      }
    },

    windowScrollLength: function(){
      return Math.floor(quizNavBar.windowSize/2.0);
    },

    setScrollWindowPosition: function(currentIndex){
      if(isNaN(currentIndex)){
        currentIndex = 0;
      }
      quizNavBar.index = currentIndex;
      quizNavBar.updateArrows();
      if(quizNavBar.tooBig()){
        var startingIndex = currentIndex - quizNavBar.windowScrollLength();
        var maxStartingIndex = quizNavBar.size() - quizNavBar.windowSize;

        if(startingIndex < 0){
          startingIndex = 0;
          quizNavBar.index = 0;
        }else if(startingIndex > maxStartingIndex){
          startingIndex = maxStartingIndex;
          quizNavBar.index = maxStartingIndex + quizNavBar.windowScrollLength();
        }

        endingIndex = startingIndex + quizNavBar.windowSize - 1;
        quizNavBar.showQuestionsInWindow(startingIndex, endingIndex);
      }
    },

    previousQuestionBlock: function(){
      quizNavBar.setScrollWindowPosition(quizNavBar.index - quizNavBar.windowSize);
    },

    nextQuestionBlock: function(){
      quizNavBar.setScrollWindowPosition(quizNavBar.index + quizNavBar.windowSize);
    }
  };
  //End of quizNavBar object

  $(document).ready(function() {
    gradingForm.ensureSelectEventsFire();

    if (ENV.GRADE_BY_QUESTION) {
      $(document).scroll(gradingForm.onScroll);
      gradingForm.onWindowResize();

      $('.question_holder').click(function() {
        $('.quiz-nav li').removeClass('active');
        $('.question').removeClass('selected_single_question');

        var $questions = $('.question')
        var $question = $(this).find('.question');
        var questionIndex = $questions.index($question) + 1;
        parentWindow.set('active_question_index', questionIndex);
        $('.q' + questionIndex).addClass('active');
        $question.addClass('selected_single_question');
      });
    }

    quizNavBar.initialize();

    $(document).fragmentChange(gradingForm.scrollToUpdatedQuestion);

    if(parentWindow.respondsTo('getQuizSubmissionSnapshot')) {
      var data = window.parent.INST.getQuizSubmissionSnapshot(scoringSnapshot.snapshot.user_id, scoringSnapshot.snapshot.version_number);
      gradingForm.setInitialSnapshot(data);
    }

    $(".question_holder .user_points input[type=number],.question_holder .question_neutral_comment .question_comment_text textarea").change(function() {
      var $question = $(this).parents(".display_question");
      var questionId = $question.attr('id');
      gradingForm.updateSnapshotFor($question);
      if($(this).hasClass('question_input')){
        quizNavBar.updateStatusFor($(this));
      }
    });

    $("#fudge_points_entry").change(function() {
      var points = parseFloat($(this).val(), 10);
      gradingForm.addFudgePoints(points);
    });

    $(document).bind('score_changed', gradingForm.onScoreChanged);

    $('.question-nav-link').click(function(e) {
      e.preventDefault();
      var questionId = $(this).attr('data-id');
      scoringSnapshot.jumpToQuestion(questionId);
    });

    $('#nav-prev').click(function(e){
      e.preventDefault();
      quizNavBar.previousQuestionBlock();
    });

    $('#nav-next').click(function(e){
      e.preventDefault();
      quizNavBar.nextQuestionBlock();
    });

    $(window).resize(function () {
      quizNavBar.updateWindowSize();
      quizNavBar.setScrollWindowPosition(quizNavBar.index);
      gradingForm.onWindowResize();
    });
  });

  if (ENV.SCORE_UPDATED) {
    $(document).ready(function() {
      if(parentWindow.respondsTo('refreshGrades')) {
        window.parent.INST.refreshGrades();
      }
      if(parentWindow.respondsTo('clearQuizSubmissionSnapshot')) {
        window.parent.INST.clearQuizSubmissionSnapshot(scoringSnapshot.snapshot);
      }
    });
  }

});

<commit_msg>keep current question number in scroll view<commit_after>define([
  'jquery' /* $ */,
  'jquery.instructure_misc_plugins' /* fragmentChange */,
  'jquery.templateData' /* getTemplateData */,
  'vendor/jquery.scrollTo' /* /\.scrollTo/ */,
  'compiled/behaviors/quiz_selectmenu'
], function($) {

  var parentWindow = {
    exists: function(){
      return (window.parent && window.parent.INST);
    },

    respondsTo: function(funcName){
      return (parentWindow.exists() && $.isFunction(window.parent.INST[funcName]));
    },

    hasProperty: function(propName){
      return (parentWindow.exists() && window.parent.INST[propName]);
    },

    set: function(propName, value){
      if(parentWindow.exists()){
        window.parent.INST[propName] = value;
      }
    },

    get: function(propName){
      if(parentWindow.hasProperty(propName)){
        return window.parent.INST[propName];
      }
    }
  };
  // end parentWindow object

  var data = $("#submission_details").getTemplateData({textValues: ['version_number', 'user_id']});

  var scoringSnapshot = {
    snapshot: {
      user_id: data.user_id || null,
      version_number: data.version_number,
      last_question_touched: null,
      question_updates: {},
      fudge_points: 0
    },

    $quizBody: null,

    jumpPosition: function(question_id) {
      $question = $("#question_" + question_id);
      if($question.length > 0) {
        return $question.offset().top - 110;
      } else {
        return 0;
      }
    },

    checkQuizBody: function() {
      if(scoringSnapshot.$quizBody === null){
        scoringSnapshot.$quizBody = $('html,body');
      }
    },

    // Animates scrolling to question if there is no page reload
    jumpToQuestion: function(question_id) {
      var top = scoringSnapshot.jumpPosition(question_id);
      scoringSnapshot.checkQuizBody();
      scoringSnapshot.$quizBody.stop();
      scoringSnapshot.$quizBody.clearQueue();
      scoringSnapshot.$quizBody.animate({scrollTop: top}, 500);
    },

    // Jumps directly to question upon a page reload
    jumpDirectlyToQuestion: function(question_id) {
      var top = scoringSnapshot.jumpPosition(question_id);
      scoringSnapshot.checkQuizBody();
      scoringSnapshot.$quizBody.scrollTop(top);
    },

    externallySet: false,

    setSnapshot: function(data, cancelIfAlreadyExternallySet) {
      if(data) {
        if(cancelIfAlreadyExternallySet && scoringSnapshot.externallySet) { return; }
        scoringSnapshot.externallySet = true;
        scoringSnapshot.snapshot = data;
        for(var idx in data.question_updates) {
          var question = data.question_updates[idx];
          var $question = $("#question_" + idx);
          if (!ENV.GRADE_BY_QUESTION) {
            $question.addClass('modified_but_not_saved');
          }
          $question.find(".user_points :text").val(question.points).end()
            .find(".question_neutral_comment .question_comment_text textarea").val(question.comments);
        }
        if(parentWindow.hasProperty('lastQuestionTouched') && !ENV.GRADE_BY_QUESTION) {
          scoringSnapshot.jumpToQuestion(window.parent.INST.lastQuestionTouched);
        } else if(scoringSnapshot.snapshot.last_question_touched && !ENV.GRADE_BY_QUESTION) {
          scoringSnapshot.jumpToQuestion(scoringSnapshot.snapshot.last_question_touched);
        }
      } else if(cancelIfAlreadyExternallySet) {
        if(parentWindow.hasProperty('lastQuestionTouched') && !ENV.GRADE_BY_QUESTION) {
          scoringSnapshot.jumpToQuestion(window.parent.INST.lastQuestionTouched);
        }
      }
      if(scoringSnapshot.externallySet || cancelIfAlreadyExternallySet) {
        $("#feel_free_to_toggle_message").show();
      }
      if(parentWindow.respondsTo('refreshQuizSubmissionSnapshot')) {
        window.parent.INST.refreshQuizSubmissionSnapshot(scoringSnapshot.snapshot);
      }
    },

    update: function(question_id, data){
      scoringSnapshot.snapshot.question_updates[question_id] = data;
      scoringSnapshot.snapshot.last_question_touched = question_id;
      scoringSnapshot.setSnapshot();
    }
  }
  //end of scoringSnapshot object

  var gradingForm = {
    ensureSelectEventsFire: function(){
      $("input[type=text]").focus(function() {
        $(this).select();
      });
    },

    scrollToUpdatedQuestion: function(event, hash) {
      if(hash.indexOf("#question") == 0) {
        var id = hash.substring(10);
        scoringSnapshot.jumpToQuestion(id);
      }
    },

    updateSnapshotFor: function($question){
      var question_id = $question.attr('id').substring(9) || null;
      if(question_id) {
        var data = {};
        if (!ENV.GRADE_BY_QUESTION) {
          $question.addClass('modified_but_not_saved');
        }
        data.points = parseFloat($question.find(".user_points :text").val(), 10);
        data.comments = $question.find(".question_neutral_comment .question_comment_text textarea").val() || "";
        scoringSnapshot.update(question_id, data);
      }
      $(document).triggerHandler('score_changed');
    },

    addFudgePoints: function(points){
      if(points || points === 0) {
        scoringSnapshot.snapshot.fudge_points = points;
        scoringSnapshot.setSnapshot();
      }
      $(document).triggerHandler('score_changed');
    },

    setInitialSnapshot: function(data){
      $("#feel_free_to_toggle_message").show();
      if(data) {
        scoringSnapshot.setSnapshot(data);
      } else {
        scoringSnapshot.setSnapshot(null, true);
      }
    },

    onScoreChanged: function(){
      var $total = $("#after_fudge_points_total");
      var total = 0;
      $(".display_question .user_points:visible").each(function() {
        var points = parseFloat($(this).find("input[type=number]").val(), 10) || 0;
        points = Math.round(points * 100.0) / 100.0;
        total = total + points;
      });
      var fudge = (parseFloat($("#fudge_points_entry").val(), 10) || 0);
      fudge = Math.round(fudge * 100.0) / 100.0;
      total = total + fudge;
      $total.text(total || "0");
    },

    questions: function(){
      return $('.question_holder').map(function(index, el) {
        return $(el).position().top - 320;
      }).toArray();
    },

    onScroll: function(){
      var qNum = quizNavBar.activateCorrectLink();
      quizNavBar.toggleDropShadow();
    },

    onWindowResize: function(){
      //Add padding to the bottom of the last question
      var winHeight = $(window).innerHeight();
      var lastHeight = $('div.question_holder:last-child').outerHeight();
      var fixedButtonHeight = $('#speed_update_scores_container').outerHeight();
      var paddingHeight = Math.max(winHeight - lastHeight - 150, fixedButtonHeight);
      $('#update_history_form .quiz-submission.headless').css('marginBottom', paddingHeight + 'px');
    }

  };
  //end of gradingForm object

  var quizNavBar = {
    index: 0,
    windowSize: 10,
    minWidth: 66,
    startingLeftPos: 32,
    navItemWidth: 34,

    initialize: function(){
      $('.user_points > .question_input').each(function(index){
        quizNavBar.updateStatusFor($(this));
      });

      if (ENV.GRADE_BY_QUESTION) {
        var questionIndex = parseInt(parentWindow.get('active_question_index'));
        var questionId = $('.q' + questionIndex).data('id');
        if(!isNaN(questionId)){
          scoringSnapshot.jumpDirectlyToQuestion(questionId);
        }
      }

      quizNavBar.updateWindowSize();
      quizNavBar.setScrollWindowPosition(0);
    },

    size: function(){
      return $('.question-nav-link').length;
    },

    tooBig: function(){
      return quizNavBar.size() > quizNavBar.windowSize;
    },

    updateWindowSize: function(){
      var fullWidth = $('.quiz-nav, .quiz-nav-fullpage').width();
      var minPadding = 10;
      var maxWidth = fullWidth - (minPadding * 2);
      var itemCount = Math.floor((maxWidth - quizNavBar.minWidth) / quizNavBar.navItemWidth);
      quizNavBar.windowSize = itemCount;
      var actualWidth = (itemCount * quizNavBar.navItemWidth) + quizNavBar.minWidth;
      $('.quiz-nav .nav, .quiz-nav-fullpage .nav').animate({width: actualWidth + 'px'}, 10);
    },

    navArrowCache: null,

    $navArrows: function(){
      if(quizNavBar.navArrowCache === null){
        quizNavBar.navArrowCache = $('.quiz-nav .nav-arrow, .quiz-nav-fullpage .nav-arrow');
      }
      return quizNavBar.navArrowCache;
    },

    navWrapperCache: null,

    $navWrapper: function(){
      if(quizNavBar.navWrapperCache === null){
        quizNavBar.navWrapperCache = $('#quiz-nav-inner-wrapper');
      }
      return quizNavBar.navWrapperCache;
    },

    updateArrows: function(){
      if(quizNavBar.tooBig()){
        quizNavBar.$navArrows().show();
        quizNavBar.$navWrapper().css({position: 'absolute'});
      } else {
        quizNavBar.$navArrows().hide();
        quizNavBar.$navWrapper().css({position: 'relative'});
      }
    },

    toggleDropShadow: function(){
      //Add shadow to top bar
      $('.quiz-nav').toggleClass('drshadow', ($(document).scrollTop() > 0));
    },

    updateStatusFor: function($scoreInput){
      try{
        var questionId = $scoreInput.attr('name').split('_')[2];
        var scoreValue = $scoreInput.val();
        $('#quiz_nav_' + questionId).toggleClass('complete', (!isNaN(parseFloat(scoreValue))));
      } catch(err) {
        // do nothing; if there's no status to update, continue with other execution
      }
    },

    activateLink: function(index){
      $('.quiz-nav li').removeClass('active');
      $('.q' + index).addClass('active');
    },

    activateCorrectLink: function(){
      var qNum = 1;
      var qArray = gradingForm.questions();
      var docScroll = $(document).scrollTop();
      $questions = $('.question')
      for(var t = 0; t <= qArray.length; t++) {
        $question = $($questions[t])
        var currentQuestionNum = t + 1;
        if ( (docScroll > qArray[t] && docScroll < qArray[t+1])  || ( t == (qArray.length - 1) && docScroll > qArray[t])) {
          qNum = currentQuestionNum;
          parentWindow.set('active_question_index', currentQuestionNum);
          quizNavBar.activateLink(currentQuestionNum);
          $question.addClass('selected_single_question');
        } else {
          $('.q'+ currentQuestionNum).removeClass('active');
          $question.removeClass('selected_single_question');
        }
      }
      quizNavBar.setScrollWindowPosition(qNum);
      return qNum;
    },

    showQuestionsInWindow: function(startingIndex, endingIndex){
      var $navWrapper = $('#quiz-nav-inner-wrapper');
      var leftPosition = quizNavBar.startingLeftPos - (startingIndex * quizNavBar.navItemWidth);
      var newPos = '' + leftPosition + 'px';
      var currentPos = $navWrapper.css('left');
      if(newPos !== currentPos){
        $navWrapper.stop();
        $navWrapper.clearQueue();
        $navWrapper.animate({left: leftPosition + 'px'}, 300);
      }
    },

    windowScrollLength: function(){
      return Math.floor(quizNavBar.windowSize/2.0);
    },

    setScrollWindowPosition: function(currentIndex){
      if(isNaN(currentIndex)){
        currentIndex = 0;
      }
      quizNavBar.index = currentIndex;
      quizNavBar.updateArrows();
      if(quizNavBar.tooBig()){
        var startingIndex = currentIndex - quizNavBar.windowScrollLength();
        var maxStartingIndex = quizNavBar.size() - quizNavBar.windowSize;

        if(startingIndex < 0){
          startingIndex = 0;
          quizNavBar.index = 0;
        }else if(startingIndex > maxStartingIndex){
          startingIndex = maxStartingIndex;
          quizNavBar.index = maxStartingIndex + quizNavBar.windowScrollLength();
        }

        endingIndex = startingIndex + quizNavBar.windowSize - 1;
        quizNavBar.showQuestionsInWindow(startingIndex, endingIndex);
      }
    },

    previousQuestionBlock: function(){
      quizNavBar.setScrollWindowPosition(quizNavBar.index - quizNavBar.windowSize);
    },

    nextQuestionBlock: function(){
      quizNavBar.setScrollWindowPosition(quizNavBar.index + quizNavBar.windowSize);
    }
  };
  //End of quizNavBar object

  $(document).ready(function() {
    gradingForm.ensureSelectEventsFire();

    if (ENV.GRADE_BY_QUESTION) {
      $(document).scroll(gradingForm.onScroll);
      gradingForm.onWindowResize();

      $('.question_holder').click(function() {
        $('.quiz-nav li').removeClass('active');
        $('.question').removeClass('selected_single_question');

        var $questions = $('.question')
        var $question = $(this).find('.question');
        var questionIndex = $questions.index($question) + 1;
        parentWindow.set('active_question_index', questionIndex);
        $('.q' + questionIndex).addClass('active');
        $question.addClass('selected_single_question');
      });
    }

    quizNavBar.initialize();

    $(document).fragmentChange(gradingForm.scrollToUpdatedQuestion);

    if(parentWindow.respondsTo('getQuizSubmissionSnapshot')) {
      var data = window.parent.INST.getQuizSubmissionSnapshot(scoringSnapshot.snapshot.user_id, scoringSnapshot.snapshot.version_number);
      gradingForm.setInitialSnapshot(data);
    }

    $(".question_holder .user_points input[type=number],.question_holder .question_neutral_comment .question_comment_text textarea").change(function() {
      var $question = $(this).parents(".display_question");
      var questionId = $question.attr('id');
      gradingForm.updateSnapshotFor($question);
      if($(this).hasClass('question_input')){
        quizNavBar.updateStatusFor($(this));
      }
    });

    $("#fudge_points_entry").change(function() {
      var points = parseFloat($(this).val(), 10);
      gradingForm.addFudgePoints(points);
    });

    $(document).bind('score_changed', gradingForm.onScoreChanged);

    $('.question-nav-link').click(function(e) {
      e.preventDefault();
      var questionId = $(this).attr('data-id');
      scoringSnapshot.jumpToQuestion(questionId);
    });

    $('#nav-prev').click(function(e){
      e.preventDefault();
      quizNavBar.previousQuestionBlock();
    });

    $('#nav-next').click(function(e){
      e.preventDefault();
      quizNavBar.nextQuestionBlock();
    });

    $(window).resize(function () {
      quizNavBar.updateWindowSize();
      quizNavBar.setScrollWindowPosition(quizNavBar.index);
      gradingForm.onWindowResize();
    });
  });

  if (ENV.SCORE_UPDATED) {
    $(document).ready(function() {
      if(parentWindow.respondsTo('refreshGrades')) {
        window.parent.INST.refreshGrades();
      }
      if(parentWindow.respondsTo('clearQuizSubmissionSnapshot')) {
        window.parent.INST.clearQuizSubmissionSnapshot(scoringSnapshot.snapshot);
      }
    });
  }

});

<|endoftext|>