// Derived from the Bill Dortch code at http://www.hidaho.com/cookies/cookie.txt
var today = new Date();
var expiry = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);

function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1) { endstr = document.cookie.length; }
  return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) {
      return getCookieVal (j);
      }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
    }
  return null;
}

function SetCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

var siteColors = ['blue', 'green', 'orange', 'red'];

// Set site color
function setSiteColor(color){
  if(color == 'random'){
    setSiteColorCookie(color);
  }
  else {
    var found = false;
    for(var i=0;i<siteColors.length;i++)
    {
      if(siteColors[i] == color) found=true;
    }
    // fallback
    if(!found) color = 'random';
    setSiteColorCookie(color);
  }
  applySiteColor();
}

function getRandomSiteColor(){
  return siteColors[Math.floor(Math.random()*siteColors.length)];
}

function setSiteColorCookie(color){
  SetCookie("LWEColorCookie", color, expiry, "/");
}

function applySiteColor(){
  // Get site color
  var color_cookie = GetCookie("LWEColorCookie");
  if(color_cookie != -1 && color_cookie != null)
  {
    // fetch a color if cookie says "random!"
    if(color_cookie =="random") color_cookie = getRandomSiteColor();
    document.getElementById('doc-body').setAttribute('class', color_cookie + '-grad');
  }
  else
  {
    setSiteColorCookie("blue");
  }
  return true;
}
