// -*-c++-*-
// Author : Philippe Le Hegaret

// insert this function in your HTML document :
// <html> <head> ...
// <style src="<this_file"></style>
// ... </head> <body onKeyPress="eventDispatcher(findDocument())"> ...
// ... </body></html>

var activeDispatcher = true;


// active the event dispatcher
function activeDispatcher() {
  activeDispatcher = true;
}

// don't ative the event dispatcher
function desactiveDispatcher() {
  activeDispatcher = false;
}

// go to a page
function gotoPage(newPage) {
  window.location = newPage;
  return true;
}

// get the keycode of a key event
function getKeyCode(event) {
  var prefix = '';
  
  if (event.shiftKey) {
    prefix = 's';
  }
  if (event.ctrlKey) {
    prefix += 'c'; 
  }
  if (event.altKey) {
    prefix += 'a';
  }
  return prefix + event.keyCode;
}

// define a page object
function Page(next, previous, size, toc) {
  this.next_page = next;
  this.previous_page = previous;
  this.size_page = size;
  this.toc_page = toc;
}

// goto to the next page of the current page
function next(page) {
  if (page.next_page != null) {
    return gotoPage(page.next_page);
  }
  return false;
}

// goto to the previous page of the current page
function previous(page) {
  if (page.previous_page != null) {
    return gotoPage(page.previous_page);
  }
}

// goto to the size page of the current page
function sizer(page) {
  if (page.size_page != null) {
    return gotoPage(page.size_page);
  }
  return false;
}

// goto to the table of content page
function toc(page) {
  if (page.toc_page != null) {
    return gotoPage(page.toc_page);
  }
  return false;
}

// the event dispatcher
function eventDispatcher(page) {
  var keyCode = getKeyCode(window.event);
  
  switch (keyCode) {
  case '13': // return
  case '32': // space. used by IE to scroll the document ...
  case '110': // N
  case '78': // n
    return next(page);
    //  case 'c32': // ctrl+space
  case '98': // b
  case '66': // B
  case '112': // p
  case '80': // P
    return previous(page);
  case '115': // s
  case '83': // S
    return sizer(page);
  case '116': // T
  case '84': // t
    return toc(page);
  default:
    return false;
  }
}

// find link informations in the HTML document
function findDocument() {
  // i.e. getElementsByTagName() in DOM Level 1.
  //  document.all.tags() is DOM Level 0.
  // coll is a NodeList
  var coll = document.all.tags("LINK");
  var next = null;
  var prev = null;
  var size = null;
  var toc  = null;
  
  for (i = 0; i < coll.length; i++) {
    // get the attribute rel on the LINK element node
    switch (coll(i).rel.toLowerCase()) {
    case 'next':
      next = coll(i).href;
      break;
    case 'prev':
      prev = coll(i).href;
      break;
    case 'change-size':
      size = coll(i).href;
      break;
    case 'contents':
    case 'index':
    case 'toc':
      toc = coll(i).href;
      break;
    }
  }
  
  return new Page(next, prev, size, toc);
}

