//==============================================================================
/// CommunicatorCookie class saves and restores preferences for Garmin Communicator Pages
///
/// Built from an idea for saving Cookies as JSON at http://www.phpied.com/json-javascript-cookies/
///
//------------------------------------------------------------------------------
/// Constructor
function
CommunicatorCookie()
{
this.load();
}

//------------------------------------------------------------------------------
// Properties
//------------------------------------------------------------------------------

CommunicatorCookie.prototype.name = "Communicator";
CommunicatorCookie.prototype.domain = ".garmin.com";
CommunicatorCookie.prototype.path = "/"
CommunicatorCookie.prototype.debug = false;
CommunicatorCookie.prototype.shelfLifeMilliseconds = 20000;

CommunicatorCookie.prototype.data = { 
	referrerIsDefault: true,
	referrerURL: "http://www.garmin.com/communicator/products/",
	referrerTitle: "Garmin | Communicator Plugin" 
}

//------------------------------------------------------------------------------
/// Read communicator product settings from the browser cookie
///
CommunicatorCookie.prototype.load = function()
{
var results = document.cookie.match ( this.name + '=(.*?)(;|$)' );

if( results )
    {
    if( this.debug )
        {
        alert( 'Loading Cookie = ' + unescape( results[1] ) );
        }
    this.data = unescape( results[1]).parseJSON();
    }
}

//------------------------------------------------------------------------------
/// Save communicator product settings to a cookie
///
CommunicatorCookie.prototype.save = function()
{
var theExpirationDate = new Date();
theExpirationDate.setTime( theExpirationDate.getTime() + this.shelfLifeMilliseconds );
var theNewCookie = this.name + '=' + escape(this.data.toJSONString()) + '; '
 + 'expires=' + theExpirationDate.toGMTString() + '; '
 + 'path=' + this.path + '; '
 + 'domain=' + this.domain + ';';
if( this.debug )
 {
 alert( 'The New Cookie = ' + theNewCookie );
 }
document.cookie = theNewCookie;
if( this.debug )
 {
 alert( 'TheModifiedCookie = ' + document.cookie );
 }
}

//------------------------------------------------------------------------------
/// Save communicator product settings to a cookie, unless another Garmin
/// page has already saved the referrerURL and referrerTitles this cookie.
/// For example, the unlock page might want the user to return there after
/// install.
///
CommunicatorCookie.prototype.saveReferrer = function( aReferrerURL, aReferrerTitle, aWriteOverExisting )
{
if( typeof aReferrerURL == "undefined" || typeof aReferrerTitle == "undefined" || typeof aWriteOverExisting == "undefined" )
 {
 return;
 }
if( this.data.referrerIsDefault || aWriteOverExisting )
 {
 this.data.referrerURL = aReferrerURL;
 this.data.referrerTitle = aReferrerTitle;
 this.data.referrerIsDefault = false;
 this.save();
 }
}
