/*===========================
  NAV TOGGLING
---------------------------*/
var navPref = new Cookie("navPref", daysFromNow(30), "", "/");
var STYLE_SHOW = "block";
var STYLE_HIDE = "none";

function initialNavState() {
  var navState = navPref.get();

  if (navState) {
    setSubNavDisplay(navState);
    navPref.set(navState); // extends cookie expiry date
    return;
  } 
  
  var body = document.getElementsByTagName("body")[0];
  if (body.className.indexOf("topLevel") < 0) {
    setSubNavDisplay(STYLE_HIDE);
  }
}

function toggle() { toggleNav(); }

function toggleNav() {
  document.subNavDisplay == STYLE_HIDE ? expandNav() : contractNav();
}
function expandNav() {
  setSubNavDisplay(STYLE_SHOW);
  navPref.set(STYLE_SHOW);
}
function contractNav() {
  setSubNavDisplay(STYLE_HIDE);
  navPref.set(STYLE_HIDE);
}
function setSubNavDisplay(status) {
  document.subNavDisplay = status;

  var mainNav = document.getElementById("mainNav");
  var subNavs = mainNav.getElementsByTagName("ul");

  for (var i=0;i<subNavs.length;i++) {
    subNavs[i].style.display = status;
  }
}

/*=========================
  COOKIE object
-------------------------*/
function Cookie(key, expiry, domain, path, bSecure) {
  var _me = this;
  this.key = key;
  this.expiry = expiry;
  this.domain = domain;
  this.path = path;
  this.bSecure = bSecure;

  /* sets the value of the cookie identified by key */
  this.set = function (val) {
    var dough = _me.key + "=" + escape(val);
    if (_me.expiry){dough += "; expires="+ _me.expiry.toGMTString();}
    if (_me.path){dough += "; path="+_me.path;}
    if (_me.domain){dough += "; domain="+_me.domain;}
    if (_me.bSecure){dough += "; secure";}

    document.cookie = dough;
  }

  /* returns the value of the cookie identified by key */
  this.get = function () {
    var pairs = document.cookie.split(';');
    for (var i=0;i<pairs.length;i++) {
      var p = lTrim(pairs[i]);
      if (p && p.indexOf(_me.key) == 0) {
        return p.substring(key.length+1);
      }
    }
  }

  /* deletes the cookie identified by key */
  this.nullify = function () {
    _me.expiry = new Date(0);
    _me.set("");
  }
}


/*=======================
  SUPPORT FUNCTIONS
-----------------------*/
/* returns the date in so many days from now */ 
function daysFromNow(days) {
  if (days) {
    var d = new Date();
    d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
    return d;
  }
}

/* removes whitespace from the start of a string */
function lTrim(str) {
  return str.replace(/^\s+/g, '');
}






