/******************************************************************************
*  cookie.js
* 	
*   Manage cookies to simulate sessions. This allows us to set cookies upon 
*   start of the application and read from them as we go along.
******************************************************************************/

/*
 * Set GLOBAL variables
 */
// this value can be set to seconds, minutes, or days
var TIMEOUT_INTERVAL="minutes";
var COOKIES_ENABLED=false;

/*
 * Set a cookie in memory. expires, path, domain, and secure are optional.
 */
function setCookie(name,value,expires,path,domain,secure){
    // set time, in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    // convert to the desired time format...
    if (expires){
        if (TIMEOUT_INTERVAL == "seconds") {
            expires=expires * 1000;
        } else if (TIMEOUT_INTERVAL == "minutes") {
            expires=expires * 1000 * 60;
        } else if (TIMEOUT_INTERVAL == "hours") {
            expires=expires * 1000 * 60 * 60;
        } else if (TIMEOUT_INTERVAL == "days") {
            expires=expires * 1000 * 60 * 60 * 24;
        }
    }
    var expires_date=new Date(today.getTime()+(expires));

    document.cookie = name + "=" +escape( value )+
    ((expires) ? ";expires=" + expires_date.toGMTString() : "") + 
    ((path) ? ";path=" + path : "") + 
    ((domain) ? ";domain=" + domain : "") +
    ((secure) ? ";secure" : "");
}

/*
 * Get a cookie stored in "memory" by name.
 */
function getCookie(name){
    var start=document.cookie.indexOf(name +"=");
    var len=start+name.length+1;

    // check to make sure that the cookie requested exists first....
    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 the value of the cookie...
    return unescape(document.cookie.substring(len,end));
}

/*
 * Delete a cookie. path and domain are optional.
 */
function deleteCookie(name,path,domain){
    if (getCookie(name)) document.cookie=name+"="+
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/*
 * Attempt to set a cookie and set the global variable COOKIES_ENABLED to true
 */
setCookie("testEnabled","someVal",1);
if (getCookie("testEnabled")){ COOKIES_ENABLED=true; };
