if ('serviceWorker' in navigator) {
  //navigator.serviceWorker.register('./sw.js', {scope: './'}).then(function() {
      // Registration was successful. Now, check to see whether the Service Worker is controlling the page.
      if (navigator.serviceWorker.controller) {
        // If .controller is set, then this page is being actively controlled by the Service Worker.
        // Show the interface for sending messages to the service worker.
        showCommands();
      } else {
        // If .controller isn't set, then prompt the user to reload the page so that the Service Worker can take
        // control. Until that happens, the Service Worker's message handler won't be used.
        document.querySelector('#status').textContent =
          'Please reload this page to allow the service worker to take control.';
      }
  //}).catch(function(error) {
    // Something went wrong during registration. The service-worker.js file
    // might be unavailable or contain a syntax error.
  //  document.querySelector('#status').textContent = error;
  //});
} else {
  // The current browser doesn't support Service Workers.
  var aElement = document.createElement('a');
  aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq';
  aElement.textContent = 'Service Workers are not supported in the current browser.';
  document.querySelector('#status').appendChild(aElement);
}



function setStatus(statusMessage) {
  document.querySelector('#status').textContent = statusMessage;
}

function showCommands() {
  document.querySelector('#add').addEventListener('click', function() {
    var url = document.querySelector('#url').value;
    sendMessage({
      command: 'add',
      url: url,
      information: new Blob([document.querySelector('#information').value], {
          type: document.querySelector('#mimetype').value
        })
    }).then(function() {
      // If the promise resolves, just display a success message.
      setStatus('Added to cache:  ' + url + ' at ' +Date());
    }).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
  });

  document.querySelector('#delete').addEventListener('click', function() {
    sendMessage({
      command: 'delete',
      url: document.querySelector('#url').value
    }).then(function() {
      // If the promise resolves, just display a success message.
      setStatus('Deleted from cache.');
    }).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
  });

  document.querySelector('#list-contents').addEventListener('click', function() {
    sendMessage({
      command: 'keys'
    }).then(function(data) {
      var contentsElement = document.querySelector('#contents');
      // Clear out the existing items from the list.
      while (contentsElement.firstChild) {
        contentsElement.removeChild(contentsElement.firstChild);
      }

      // Add each cached URL to the list, one by one.
      data.urls.forEach(function(url) {
        var liElement = document.createElement('li');
        liElement.textContent = url;
        contentsElement.appendChild(liElement);
      });
    }).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
  });

  document.querySelector('#get').addEventListener('click', function() {
    getContent(document.querySelector('#url').value,
               function() {
                 document.querySelector('#mimetype').value = this.getResponseHeader("content-type");
                 document.querySelector('#information').value = this.responseText;
                 }
              );
  })

  document.querySelector('#save-contents').addEventListener('click', function() {
    sendMessage({
      command: 'keys'
    }).then(function(data) {
      // Add each cached URL to the list, one by one.
      data.urls.forEach(function(url) {
        getContent(url, 
                   function(){
                     var url_content = {'content_type': '', 'content':''};
                     url_content.content_type = this.getResponseHeader("content-type");
                     url_content.content = this.responseText;
                     localStorage.setItem(url, url_content);
                     }
                  );
      });
    }).catch(setStatus); // If the promise rejects, then setStatus will be called with the error.
  });

  document.querySelector('#commands').style.display = 'block';
}

function sendMessage(message) {
  // This wraps the message posting/response in a promise, which will resolve if the response doesn't
  // contain an error, and reject with the error if it does. If you'd prefer, it's possible to call
  // controller.postMessage() and set up the onmessage handler independently of a promise, but this is
  // a convenient wrapper.
  return new Promise(function(resolve, reject) {
    var messageChannel = new MessageChannel();
    messageChannel.port1.onmessage = function(event) {
      if (event.data.error) {
        reject(event.data.error);
      } else {
        resolve(event.data);
      }
    };

    // This sends the message data as well as transferring messageChannel.port2 to the service worker.
    // The service worker can then use the transferred port to reply via postMessage(), which
    // will in turn trigger the onmessage handler on messageChannel.port1.
    // See https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage
    navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2]);
  });
}

function getContent(url, reqListener) {
  var oReq = new XMLHttpRequest();
  oReq.onload = reqListener;
  oReq.open("get", url, true);
  oReq.send();
}