/**
 * A collection of utility functions to access and modify cookies
 * 
 * @author Christophe Lauret (Allette Systems)
 * @version 18 May 2006
 */

/**
 * Returns the value of the specified cookie name.
 *
 * @param name The name of the requested cookie.
 */
function getCookie(name) {
  var start = document.cookie.indexOf(name+"=");
  var len = start+name.length+1;
  if ((!start) && (name != document.cookie.substring(0, name.length))) return null;
  if (start == -1) return null;
  var end = document.cookie.indexOf(";",len);
  if (end == -1) end = document.cookie.length;
  return unescape(document.cookie.substring(len,end));
}

/**
 * Sets the propeties of the specified cookie name.
 *
 * Only specified properties will be set in the cookie.
 *
 * @param name    The name of the cookie.
 * @param value   The value for that cookie.
 * @param expires The expiry date for the cookie.
 * @param path    The path
 * @param domain  The domain for the cookie
 * @param secure  Whether it is secure
 */
function setCookie(name, value, expires, path, domain, secure) {
  var cookieString = name + "=" +escape(value) +
    ( (expires) ? ";expires=" + expires.toGMTString() : "") +
    ( (path) ? ";path=" + path : "") +
    ( (domain) ? ";domain=" + domain : "") +
    ( (secure) ? ";secure" : "");
  document.cookie = cookieString;
}

/**
 * Delete the specified cookie.
 *
 * @param name    The name of the cookie.
 * @param path    The path
 * @param domain  The domain for the cookie
 */
function deleteCookie(name, path, domain) {
  if (getCookie(name)) document.cookie = name + "=" +
     ( (path) ? ";path=" + path : "") +
     ( (domain) ? ";domain=" + domain : "") +
     ";expires=Thu, 01-Jan-70 00:00:01 GMT";
}

/**
 * Returns the names of the cookies as an array.
 *
 * @param name    The name of the cookie.
 * @param path    The path
 * @param domain  The domain for the cookie
 */
function getCookieNames() {
  var tokens = document.cookie.split(/;\s*/);
  if (tokens) {
    for (var i=0; i < tokens.length; i++) {
      if (tokens[i].indexOf('=') != -1)
        tokens[i] = tokens[i].substring(0, tokens[i].indexOf('='));
    }
  }
  return tokens;
}
