// =================================================================================================
//
// cookie.js
//
// =================================================================================================

function Cookie ( _document , _name , _hours , _path , _domain , _secure ) {
    this.$document     = _document ;
    this.$name         = _name ;
    this.$expiration   = ( ! _hours )  ? null  : new Date ( (new Date()).getTime() + _hours*3600000 ) ;
    this.$path         = ( ! _path )   ? null  : _path ;
    this.$domain       = ( ! _domain ) ? null  : _domain ;
    this.$secure       = ( ! _secure ) ? false : _secure ;
}

Cookie.prototype.store = function ( ) {
    var cookie_value = ""

    for ( var prop in this ) {
        if ( (prop.charAt(0)=='$') || ((typeof this[prop])=='function') ) {
            continue ;
        }
        cookie_value += ( cookie_value != '' ) ? '&' : '' ;
        cookie_value += prop + ':' + escape(this[prop]) ;
    }

    var cookie = this.$name + '=' + cookie_value ;

    if ( this.$expiration ) {
        cookie += '; expires=' + this.$expiration.toGMTString() ;
    }
    if ( this.$path ) {
        cookie += '; path=' + this.$path ;
    }
    if ( this.$domain ) {
        cookie += '; domain=' + this.$domain ;
    }
    if ( this.$secure ) {
        cookie += '; secure=' + this.$secure ;
    }

    this.$document.cookie = cookie ;
}

Cookie.prototype.load = function ( ) {
    var all_cookies = this.$document.cookie ;
    if ( all_cookies == '' ) return false ;

    var start_pos = all_cookies.indexOf(this.$name + '=') ;
    if ( start_pos == -1 ) return false ;
    start_pos += this.$name.length + 1 ;

    var end_pos = all_cookies.indexOf(';', start_pos) ;
    if ( end_pos == -1 ) end_pos = all_cookies.length ;

    var cookie_value = all_cookies.substring(start_pos, end_pos) ;

    var a = cookie_value.split('&') ;
    for ( var i=0 ; i<a.length ; i++ ) {
        a[i] = a[i].split(':') ;
    }

    for ( var i=0 ; i<a.length ; i++ ) {
        this[a[i][0]] = unescape(a[i][1]) ;
    }
    return true ;
}

Cookie.prototype.remove = function ( ) {
    var cookie ;
    cookie = this.$name + '=' ;
    if ( this.$path )   cookie += '; path='     + this.$path ;
    if ( this.$domain ) cookie += '; domain='   + this.$domain ;
    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT' ;

    this.$document.cookie = cookie ;
}
