let loadContent = function(hash, target, callback) {
  if(!target.touched) {
    target.defaultHTML = target.innerHTML;
  }

  if(hash === '') {
    target.innerHTML = target.defaultHTML;
    return;
  }

  let url = `/${hash.replace('#', '')}.html`;

  let request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.onreadystatechange = () => {
    if (request.readyState != 4 || request.status != 200) return;
    target.innerHTML = request.responseText;
    target.touched = true;
    
    callback();
  };

  request.send();
};

let hashNavigation = (container, callback = () => {}) => {
  window.addEventListener("hashchange", () => {
    loadContent(location.hash, container, callback);
  }, false);

  if(location.hash !== '') {
    loadContent(location.hash, container, callback);
  }
}

export default hashNavigation
