/*extern Pmx */

/**
 * Pelmorex Cookie class
 *
 * @fileoverview
 * This is the source file for the Cookie class. This class is used for
 * saving data between browser sessions.
 *
 * @author Jim Ing (jing@pelmorex.com)
 */

/**
 * Cookie class for saving data.
 *
 * @class
 */
Pmx.Cookie = function()
{
};

/**
 * @description
 * Create a cookie.
 *
 * @param {string} name
 * @param {string} value
 * @param {integer} days
 *
 * @example
 * var cookieObj = new Pmx.Cookie();
 * var cookieStr = 'lat=' + center.Latitude + '|lon=' + center.Longitude + '|zoom=' + Pmx.Map.zoomLevel + '|style=' + Pmx.Map.mapStyle;
 * cookieObj.create( Pmx.Map.cookieId, cookieStr, 1 );
 */
Pmx.Cookie.prototype.create = function( name, value, days )
{
    var expires = "";

    if( days )
    {
        var date = new Date();
        date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
        expires = "; expires=" + date.toGMTString();
    }

    document.cookie = name + "=" + value + expires + "; path=/";
};

/**
 * @description
 * Read a cookie.
 *
 * @param {string} name
 *
 * @return {string} The data stored in the cookie.
 *
 * @example
 * var cookieObj = new Pmx.Cookie();
 * var cookieStr = cookieObj.read( Pmx.Map.cookieId );
 * var pairs = cookieStr.split( '|' );
 * var keyval;
 * var settings = [];
 * for( var i = 0; i < pairs.length; i++ )
 * {
 *     keyval = pairs[ i ].split( '=' );
 *     settings[ keyval[ 0 ] ] = keyval[ 1 ];
 * }
 * Pmx.Map.latitude = settings.lat;
 * Pmx.Map.longitude = settings.lon;
 * Pmx.Map.zoomLevel = settings.zoom;
 * Pmx.Map.mapStyle = settings.style;
 */
Pmx.Cookie.prototype.read = function( name )
{
    var nameEQ = name + "=";
    var ca = document.cookie.split( ';' );

    for( var i = 0; i < ca.length; i++ )
    {
        var c = ca[ i ];
        while( c.charAt( 0 ) == ' ' )
        {
            c = c.substring( 1, c.length );
        }
        if( c.indexOf( nameEQ ) === 0 )
        {
            return c.substring( nameEQ.length, c.length );
        }
    }

    return null;
};

/**
 * @description
 * Remove a cookie.
 *
 * @param {string} name
 */
Pmx.Cookie.prototype.remove = function( name )
{
    Pmx.Cookie.create( name, "", -1 );
};
