/*
    Functions for dealing with cookies.
*/

// The subdomain of a domain. 
// subdomain('a.b.c.d.com') ==> b.c.d.com.
// subdomain('d.com')       ==> null
function subdomain(domain)
{
    var p = domain.indexOf('.');
    var result = domain.substring(p+1);
    return (
        result.indexOf('.') > 0
        ?   result
        :   null
        );
}

// The root domain of a domain. 
// rootDomain('a.b.c.d.com') ==> d.com
// rootDomain('d.com')       ==> d.com
function rootDomain(domain)
{
    var p = domain.lastIndexOf('.');
    if ( p > 0 )
    {
        p = domain.lastIndexOf('.', p - 1)
        if ( p > 0 )
        {
            return domain.substring(p + 1);
        }
    }
    return domain;
}

/*
    Whether this document has a cookie with a given name.
    Not perfect: will return true if another cookie name
    ends with 'name'.
*/
function hasCookie(name)
{
    return (' ' + document.cookie).indexOf(' ' + name + '=') >= 0;
}

/*
    The value of a cookie.
    Returns null if the cookie is not found.
*/
function cookieValue(name, defaultValue)
{
    var p1 = document.cookie.indexOf(name + '=');
    if ( p1 == -1 )
    {
        return defaultValue;
    }

    var p2 = document.cookie.indexOf(';', p1);
    if ( p2 == -1 )
    {
        p2 = document.cookie.length;
    }
    return document.cookie.substring(p1 + name.length + 1, p2);    
}

/*
    Create a cookie.
    If path is null, set to "/".
    If domain is null, set to document.domain.
    If days is null, cookie is temporary.
*/
function createCookie(name, value, days, path, domain)
{
    var expires;
    if ( days == null )
    {
        expires = "";
    }
    else
    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }

    var cookie = (
        name + "=" + value
        + expires
        + "; path=" + ( path == null ? "/" : path )
        + ( domain == null ? '' : '; domain=' + domain )
        );

    document.cookie = cookie;

    return hasCookie(name);
}

/*
    Delete a cookie.
    Path and Domain are optional.
*/
function deleteCookie(name, path, domain)
{
    var cookie = (
        name + "=" 
        + "; path=" + ((path == null) ? "/" : path) 
        + ((path == null) ? "" : "; path=" + path) 
        + ((domain == null) ? "" : "; domain=" + domain) 
        + "; expires=Wednesday, 09-Nov-99 23:12:40 GMT"
        );
    document.cookie = cookie;
}

/*
    Delete a cookie from all subdomains.
    (i.e. x.y.z.com: y.z.com, z.com)
*/
function deleteCookieSubdomains(name, path)
{
    var domain = document.domain;
    while ( ( domain = subdomain(domain) ) != null )
    {
        deleteCookie(name, path, domain);
    }
}

