//Event.observe(window, 'load', function(e){
//	document.fire('window:loaded');
//});

var RDController = Class.create({
	initialize: function(start){
		this.defaultHash = start;
		this.lastHash = '';
		this.ready = true;
		
		if(this.getHash() == ''){
			this.setHash('');
			this.observeHash();
			this.observeLinks();
		} else {
			this.observeHash();
			this.observeLinks();
		}
	},
	observeLinks: function(){
		$$('a').each(function(link, i){
			if(link.rel == 'state'){
				link.observe('click', function(event){
					Event.stop(event);
					this.goingTo(this.getRelativeURL(link.href));
				}.bind(this));
			}
		}.bind(this));
	},
	observeHash: function(){
		
		new PeriodicalExecuter(function(pe){
			if (this.getHash() != this.lastHash) {
				// hash hasn't changed, bail
				//return;
			//} else {
				
				this.lastHash = this.getHash();
				document.fire('receiver:hashChange', {destination: this.lastHash});
				
			}
			// hash has changed, take note and fire receiver:stateChange
			 //window.location.hash.sub('#/', '');
			
		}.bind(this), .3);
		
  	},
	
	goingTo: function(destination){
		//method for flash to send destination'
		this.setHash(destination);
	},
	
	getHash: function(){
		// returns the hash stripped of #/
		return window.location.hash.sub('#/', '').strip();
	},
	
	setHash: function($destination){
		// formats hash to #/destination
		window.location.hash = '#/'+$destination.strip();
	},
	
	getRelativeURL: function($url){
		// pulls protocol, host and path from url to return location
		var absolute = window.location.protocol+'//'+window.location.host+window.location.pathname;
		return $url.sub(absolute, '');
	},
	
	isReady: function(){
		return this.ready;
	},
	
	clientReady: function(){
		document.fire('controller:clientReady');
	},
	
	pathArray: function(delimiter){
		return this.getHash().split('/');
	},
	//add full url
	getRegularURL: function(){
		return document.location.href;
		//return window.location.protocol+'//'+window.location.host+window.location.pathname+window.location.hash;
	}
	
});