/**
 * This file should go in the same folder as its calling HTML
 *
 * Add this line in the head:
 * <script type="text/javascript" src="categories.js"></script>
 *
 * Add a catInit() call to the body:
 * <body onload="catsInit();">
 */

// configuration
ROOT_CAT = 'subcategory'; // id of arch-ul
CURRENT_CAT_INPUT = 'categoryID'; // id of hidden input box

// init values
DISPLAY_DEFAULTS = [];

// function to close a category
function catClose(element) {
  if(element.style.display=='') element.style.display='block';
  if(!DISPLAY_DEFAULTS[element.id]) DISPLAY_DEFAULTS[element.id]=element.style.display;
  element.style.display = 'none';
  return true;
}

// function to close all categories
function catCloseAll() {
  catsFromRoot('catClose', true);
  catsFromRoot('catOpen');
}

// function to open a category
function catOpen(element) {
  if(DISPLAY_DEFAULTS[element.id]) element.style.display = DISPLAY_DEFAULTS[element.id];
  return true;
}

// call toCall for each element under root cat
function catsFromRoot(toCall, isDeep, element) {
  if(!isDeep) isDeep=false;
  if(!element) element=getRootCat();
  // children
  for(var i=0; i<element.childNodes.length; i++) {
    if(element.childNodes[i].nodeName=='UL') {
      eval(toCall+'(element.childNodes[i]);');
    }
    if(isDeep) catsFromRoot(toCall, isDeep, element.childNodes[i]);
  }
  return true;
}

// function to be called on document load
function catsInit() {
  CURRENT_CAT = document.getElementById(CURRENT_CAT_INPUT).value;
  // close all
  catCloseAll();
  // open desired chain
  if(CURRENT_CAT!='all') catsToRoot('catOpen', getOpenCat());
  catsFromRoot('catOpen', false, getOpenCat());
}

// call toCall for each element until hit root cat
function catsToRoot(toCall, element) {
  if(element.id!=ROOT_CAT) {
    if(element.nodeName=='UL') {
      eval(toCall+'(element);');
    }
    catsToRoot(toCall, element.parentNode);
  }
}

// function to get the currently open category
function getOpenCat() {
  return document.getElementById(CURRENT_CAT);
}

// function to get the root cat
function getRootCat() {
  return document.getElementById(ROOT_CAT);
}

