

if ('serviceWorker' in navigator) {
    navigator.serviceWorker
            .register('/olimpiadageografia/serviceworker.js', {scope: '/olimpiadageografia/'})
            .then(function (reg) {
                console.log("Service Worker registered successfully. Scope: " + reg.scope);
            })
            .catch(function (error) {
                console.log("Service worker registration failed: " + error);
            });
}

var CACHE_NAME = 'lib-cache-v1';

var urlsToCache = [
    'index.php',
    'offline.html'
];

self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

self.addEventListener('activate', function(event) {

  var cacheWhitelist = [CACHE_NAME];

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});


self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
    .then(function(response) {
      return response || fetchAndCache(event.request);
    })
  );
});

function fetchAndCache(er) {
  return fetch(er)
  .then(function(response) {
    // Check if we received a valid response
    if (!response.ok) {
      throw Error(response.statusText);
    }
    return caches.open(CACHE_NAME)
    .then(function(cache) {
//      cache.put(er, response.clone());//insere a pagina solicitada no cache
        ext = er.url.substring(er.url.lastIndexOf('.'));//achando a extensao do arquivo
        if (ext == '.jpg' || ext == '.png' || ext == '.gif' || ext == '.js' || ext == '.css' || ext == '.html') cache.put(er, response.clone());
      return response;
    });
  })
  .catch(function(error) {
    console.log('Request failed:', error);
    // return a custom offline 404 page here
    return caches.match('offline.html');
  });
}
