var historical = (function () {
    var iframe, hiddenField;
    var currentToken;
    var suspendEvent = false;
	var items = [];

    function getHash() {
        var href = top.location.href;
		var i = href.indexOf("#");
        return i >= 0 ? href.substr(i + 1) : null;
    }

    function doSave() {
        hiddenField.value = currentToken;
    }

    function handleStateChange(token) {
		currentToken = token;
		if (!suspendEvent) {
		    historical.fireEvent('change', token);
		} else {
		    suspendEvent = false;
		}
    }

    function updateIFrame (token) {
        currentToken = token;
		var html = ['<html><body><div id="state">',token,'</div></body></html>'].join('');
        try {
            var doc = iframe.contentWindow.document;
            doc.open();
            doc.write(html);
            doc.close();
            return true;
        } catch (e) {
            return false;
        }
    }

    function checkIFrame() {
        if (!iframe.contentWindow || !iframe.contentWindow.document) {
            setTimeout(checkIFrame, 10);
            return;
        }

        var doc = iframe.contentWindow.document;
        var elem = doc.getElementById("state");
        var token = elem ? elem.innerText : null;

        var hash = getHash();

        setInterval(function () {

            doc = iframe.contentWindow.document;
            elem = doc.getElementById("state");

            var newtoken = elem ? elem.innerText : null;

            var newHash = getHash();

            if (newtoken !== token) {
                token = newtoken;
                handleStateChange(token);
                top.location.hash = token;
                hash = token;
                doSave();
            } else if (newHash !== hash) {
                hash = newHash;
                updateIFrame(newHash);
            }

        }, 50);
    }

    function startUp() {
        currentToken = hiddenField.value ? hiddenField.value : getHash();

        if (Prototype.Browser.IEe) {
            checkIFrame();
        } else {
            var hash = getHash();
            setInterval(function () {
                var newHash = getHash();
                if (newHash !== hash) {
                    hash = newHash;
                    handleStateChange(hash);
                    doSave();
                }
            }, 50);
        }
    }

    return {
        
/**
         * The id of the hidden field required for storing the current history token.
         * @type String
         * @property
         */
        fieldId: 'history-field',
        
/**
         * The id of the iframe required by IE to manage the history stack.
         * @type String
         * @property
         */
        iframeId: 'history-frame',
        
        events:{},

        
/**
         * Initialize the global History instance.
         * @param {Boolean} onReady (optional) A callback function that will be called once the history
         * component is fully initialized.
         * @param {Object} scope (optional) The callback scope
         */
        init: function (onReady, scope) {
            hiddenField = $(historical.fieldId);
            if (Prototype.Browser.IE) {
                iframe = $(historical.iframeId);
            }
            startUp();
        },

        
/**
         * Add a new token to the history stack. This can be any arbitrary value, although it would
         * commonly be the concatenation of a component id and another id marking the specifc history
         * state of that component.  Example usage:
         * 


// Handle tab changes on a TabPanel
tabPanel.on('tabchange', function(tabPanel, tab){
    Ext.History.add(tabPanel.id + ':' + tab.id);
});


         * @param {String} token The value that defines a particular application-specific history state
         * @param {Boolean} preventDuplicates When true, if the passed token matches the current token
         * it will not save a new history step. Set to false if the same state can be saved more than once
         * at the same history stack location (defaults to true).
         */
        add: function (token, preventDup) {
            if(preventDup !== false){
                if(this.getToken() == token){
                    return true;
                }
            }
			items.push(token);
			actual = items.length - 1;
	    	suspendEvent = true;
            if (Prototype.Browser.IE) {
				return updateIFrame(token);
            } else {
				top.location.hash = token;
                return true;
            }
        },

        
/**
         * Programmatically steps back one step in browser history (equivalent to the user pressing the Back button).
         */
        back: function(){
            history.go(-1);
        },

        
/**
         * Programmatically steps forward one step in browser history (equivalent to the user pressing the Forward button).
         */
        forward: function(){
            history.go(1);
        },

        
/**
         * Retrieves the currently-active history token.
         * @return {String} The token
         */
        getToken: function() {
            return currentToken;
        }
    };
})();
FilmX.apply(historical, new Observable());


