/**
 * Provides a simple mechanism that allows your users to navigate with the
 * browser's Back and Forward buttons and bookmark a certain page of your
 * flash site or Ajax Application. For more info, visit: http://jbookmarker.it-base.ro
 * 
 * @copyright: MIT Licence
*  @author: Tudor Barbu
*  @version: 0.9.8
*/
 
jBookmarker = {
    interval: null,
    onChange: null,
    currentString: '',
 
    /**
    * save the value in the window.location.hash string
    *
    * @param string key
    * @param string value
    */
    set: function( key, value ) {
        var s = window.location.hash;
        if ( s.indexOf( key + '=' ) != -1 ) {
            var re = new RegExp( "(?=" + key + "=)[^&]+" );
            s = s.replace( re, key + '=' + encodeURIComponent( value ) );
        }
        else {
            if ( s.length == 0 ) {
                s = key + '=' + encodeURIComponent( value );
            }
            else {
                s = s.concat( '&' + key + '=' + encodeURIComponent( value ) );
            }
        }
        window.location.hash = s;
		jBookmarker.currentString = s;
		return false;
    },
 
    /**
    * gets the value associated with this key
    *
    * @param string key
    */
    get: function( key ) {
        var s = window.location.hash;
 
        if ( s.indexOf( key ) == -1 ) {
            return false;
        }
 
        var re = new RegExp( "(?=" + key + "=)[^&]+" );
        s = s.match( re );
        return decodeURIComponent( s[0].substring( key.length + 1, s[0].length ) );
    },
 
    /**
    * removes the value associated with this key
    *
    * @param string key
    */
    remove: function( key ) {
        var s = window.location.hash;
 
        if ( s.indexOf( key ) == -1 ) {
            return false;
        }
        var re = new RegExp( "(|&)(?=" + key + "=)[^&]+" );
        s = s.replace( re, '' );
        window.location.hash = s;
		return false;
    },
 
    /**
    * adds a listener
    *
    * @param function
    */
    addListener: function( pointer ) {
        jBookmarker.currentString = window.location.hash;
        jBookmarker.interval = window.setInterval( "jBookmarker.checkForChanges()", 500 );
        jBookmarker.onChange = pointer;
    },
 
    /**
    * removes the listener
    */
    stopListener: function() {
        window.clearInterval( jBookmarker.interval );
    },
 
    /**
     * checks for changes...
     *
     * @access private
     */
    checkForChanges: function() {
        if ( jBookmarker.currentString != window.location.hash ) {
            if ( jBookmarker.onChange != null ) {
                jBookmarker.onChange( jBookmarker.currentString, window.location.hash );
            }
            jBookmarker.currentString = window.location.hash;
        }
    },
    /**
     * cancels the event, this method should be used in the callback
     */
    cancelEvent: function() {
            window.location.hash = jBookmarker.currentString;
    }
}
 
// EOF

