var History = {
    __altered: false,
    __currentHash: null,
    __previousHash: null,
    __iframe: false,
    __title: false,
    
    init: function() {
        var hash  = location.hash.substring(1);
        this.hash = $H(hash.toQueryParams());
        this.__currentHash  = hash;
        this.__previousHash = hash;

        this.__title = document.title;
    },
    
    set: function($name, $value) {
        this.__previousHash = this.hash.toQueryString();
        this.hash.set($name, $value);
        this.apply();
    },
    
    get: function($name) {
        return this.hash.get($name);
    },
    
    unset: function($name) {
        this.hash.unset($name);
        this.apply();
    },
    
    update: function() {
        this.__previousHash = this.hash.toQueryString();
        var hash = window.location.hash.substring(1);
        this.hash = $H(hash.toQueryParams());
        this.__currentHash = hash;
    },
    
    apply: function() {
        var newHash = this.hash.toQueryString();

        var path = window.location.href.replace(/#.*/g, '');
        window.location.replace(path +'#'+ newHash);
    },

    /**
     * @desc Return true if current hash is different of previous hash.
     * this.__altered allows to force the dispatch.
     */
    isAltered: function() {
        if(this.__altered == true) {
            return true;
        }
        this.__altered = false;

        return (History.__currentHash != History.__previousHash);
    },
    
    /**
     * @use  For IE compatibility
     * @desc Set hash value on iframe
     */
    setHashOnIframe: function(hash) {
        try {
            var doc = History.__iframe.contentWindow.document;
            doc.open();
            doc.write('<html><body id="history">' + hash + '</body></html>');
            doc.close();
        } catch(e) {}
    },
    
    /**
     * @use  For IE compatibility
     * @desc Get hash value on iframe
     */
    getHashOnIframe: function() {
        var doc = this.__iframe.contentWindow.document;
        if (doc && doc.body.id == 'history') {
            return doc.body.innerText;
        } else {
            return this.hash.toQueryString();
        }
    },
    
    setTitle: function(title) {
        if(document.title) {
            document.title = title;
        }
    },
    
    getTitle: function() {
        return this.__title;
    }
};

History.init();
