var HashRouter = function(availablePages, onHashChange, duration, hashPrefix){

	this.availablePages = availablePages || [];
	this.onHashChange = onHashChange || function() {};
	this.duration = duration || 50;
	this.hashPrefix = hashPrefix || '#!/';

	this.intervalID = false;
	this.currentHash = false;
	this.currentProduct;
	this.lastHash = false;
};

HashRouter.prototype.start = function() {

	this.intervalID = setInterval(this.checkHashChanges.bind(this), this.duration);
	return this;
};

HashRouter.prototype.stop = function() {

	clearInterval(this.intervalID);
	return this;
};

HashRouter.prototype.checkHashChanges = function() {

	var hash = document.location.hash.replace(this.hashPrefix, '');

	if(hash === this.currentHash || hash === this.currentProduct || hash === this.currentWishlist || hash === this.currentSearch )
		return;

	if( !hash || hash == this.hashPrefix ){
		document.location.hash = this.hashPrefix + this.availablePages[0];
		return;
	}

	if( this.availablePages.indexOf(hash) == -1 && !/product-/g.test(hash) && !/wishlist-/g.test(hash) && !/search-/g.test(hash) ){
		document.location.hash = this.hashPrefix + this.availablePages[this.availablePages.length -1];
		return
	}

	this.stop();

	this.lastHash = this.currentHash;
	this.currentHash = hash;

	this.lastProduct = this.currentProduct;
	this.currentProduct = hash;

	this.lastWishlist = this.currentWishlist;
	this.currentWishlist = hash;

	this.lastSearch = this.currentSearch;
	this.currentSearch = hash;

	if( /search-/g.test( hash ) ) this.currentHash = 'search';
	if( /product-/g.test( hash ) ) this.currentHash = 'product';
	if( /wishlist-/g.test( hash ) ) this.currentHash = 'wishlist';

	this.onHashChange() && this.start();

};
