/*
 * $Source: /home/cvsroot/fsc3/jsp/common/cookie.js,v $
 * $Revision: 1.1 $
 * $Author: dliu $
 * $Date: 2004/02/18 03:01:49 $
 * Copyright 2003 FulFil-Net
 */

// Calculate the time elasped since January 01 1970 plus parameter number of days
function getExpiryDate(numOfDays){
    // the coordinated universal time
    var UTCstring;
    Today = new Date();
    
    // number of milliseconds since January 01 1970
    numOfMilli = Date.parse(Today);

    // set the time in days
    Today.setTime(numOfMilli + numOfDays * 24 * 60 * 60 * 1000);
    
    // convert to universal time
    UTCstring = Today.toUTCString();
    return UTCstring;
}

// Get the value matching the parameter key from cookie
function getCookieValue(key) {
    // the cookie string from current document
    var cookieString = "" + document.cookie;

    // locate the index of the key
    var startIndex = cookieString.indexOf(key);
    
    // return if key is not found
    if (startIndex == -1 || key == ""){
        return "";
    }
    
    // locate the ending index for this keys value
    var endIndex = cookieString.indexOf(';', startIndex);
    
    // end delimiter cannot be found, return length of cookie string
    if (endIndex == -1){
        endIndex = cookieString.length; 
    }
    
    // get the starting index for value of the key
    var valueStartIndex = startIndex + key.length + 1;

    // return the value of the key
    return unescape(cookieString.substring(valueStartIndex, endIndex));
}

// Set a key value pair into the cookie for a specified number of days
function setCookieValue(key, value, duration){
    cookieString = key + "=" + escape(value) + ";EXPIRES=" + getExpiryDate(duration);
    
    // set new cookie 
    document.cookie = cookieString;        

    // test if value was set sucessfully
    if(!getCookieValue(key)){
        return false;
    }else{
        return true;
    }
}
