/*

	HashChangeFallback.js
	
	Purpose:
	Provides window.hashchange cross browser
	
	e.g. 
	
	window.addEvent('hashchange', function(val){
		console.log(val);
	});
	
	Created:
	Wednesday 02/11/2010
	
	Created By:
	Ryan Mitchell


*/

var HashChangeFallback = new Class({

	// hold my hash
	myhash: '',
	
	// use iframe?
	useIframe: false,
	
	// use native
	useNative: false,

	// initialize
	initialize: function(){
		    
	    // native hashchange, or not
	    if ("onhashchange" in window){
	    
	    	this.useNative = true;
	    	
	    	window.onhashchange = this.native;
	    	document.onhashchange = this.native;
	    	
	    } else {
	   
	    
			// iframe fallback
			if (window.ActiveXObject){
				this.useIframe = true;
		        if (!document.documentMode || document.documentMode < 8){
					this.iframeFallback();	        	
		        }
		    };
	    
	    	// setup polling
			this.poll.periodical(50);
			
	    }


	},
	
	// mootool-ize the hash change event
	native: function(){
        var value = (location.hash.indexOf('#') == 0 ? location.hash.substr(1) : location.hash);
		window.fireEvent('hashchange', value);
		document.fireEvent('hashchange', value);
	},
	
	// polling function
	poll: function(){
		
		// only if we don't have native
		if (this.useNative) return;
	
		// hash change
		if(this.myhash != location.hash){
		
			// set newhash
			this.myhash = location.hash;
			
			// set iframe value (IE 6/7 only)
			try { if (this.useIframe) this.setIframe(lastHash); } catch (e) { }

			// get hash value to pass
            var value = (location.hash.indexOf('#') == 0 ? location.hash.substr(1) : location.hash);
            
            // fire on window and document
            window.fireEvent('hashchange', value);
            document.fireEvent('hashchange', value);
            
		}
	
	},

	// iframe fallback
	iframeFallback: function(){
	        
    	// create an iframe
    	this.iframe = new IFrame({ id: 'ieframe' }).setStyle('display', 'none');
    	
    	// append to document
    	$(document.body).adopt(this.iframe);		    
	    				
	    // Create a history entry for the initial state.
	    this.setIframe(location.hash);
	    var data = location.hash;
	
		// run an interval function
	    setInterval( function (){
	        var curData, curHash;
	
	        try {
	            curData = iframe.contentWindow.document.body.innerText;
	            if (curData != data) {
	                data = curData;
	                location.hash = curData;
	            }
	        } catch (e){ }
	    }, 50);

	},
	
	// set iframe
	setIframe: function(newHash){
	
	    try {
	        var doc = this.iframe.contentWindow.document;
	        doc.open();
	        doc.write('<html><body>' + newHash + '</body></html>');
	        doc.close();
	        hash = newHash;
	    } catch (e) {
	        setTimeout(function(){ this.setIframe(newHash); }, 10);
	    }
	    
	}

});

// start me
window.addEvent('domready', function(){
	new HashChangeFallback();
});
