﻿/**
 * @author POP WAD [tw]
 * @classDescription 	
 * ParamsHash is a class for use by window.location or links to manage key/value pairs
 * in the hash portion of a url. 
 * e.g. index.html#name=value&pairs=true
 * @lastModified 10/14/2009
 * This class depends on Prototype v1.6+
 * 
 * Sample Usage:
 * var locationHash = new ParamsHash(window.location, '/');
 * locationHash.get('key');
 * locationHash.set('key', value);
 * 
 * var linkHash = new ParamsHash($('myLink'), '&');
 * linkHash.get('key');
 * linkHash.update({a:1, b:52, c: 'beyond'});
 * 
*/
var ParamsHash = Class.create({
	// obj can be window.location or an element, separator and writeEventKey are optional (e.g. 'locationhash:updated)
	initialize: function(obj, separator, writeEventKey){
		this.srcObj = obj;
		if(Object.isUndefined(obj) || !('hash' in obj)){
			throw new Error("The object passed to ParamsHash is undefined or does not have a 'hash' property.");
		}
		this.separator = separator || '&';
		this.writeEventKey = writeEventKey || false;
	},
	// parses the hash property of the oject into a Hash 
	read: function(){
		var sHash = this.srcObj.hash.replace('#','');
		return $H(sHash.toQueryParams(this.separator));
	},
	// Convenience for getting an object literal of all key/value pairs.
	toObject: function(){
		return this.read().toObject();
	},
	// Writes to the hash property of the relevant object (location, or link)
	write: function(oHash){
		this.srcObj.hash = '#' + $H(oHash).toQueryString().replace('&', this.separator, 'gi');
		if(Object.isString(this.writeEventKey)){
			document.fire(this.writeEventKey, {instance: this, 'value': this.srcObj.hash});
		}
		return this.srcObj.hash;
	},
	// Updates with the given object or Hash (use for multiple key/value updates)
	update: function(oHash){
		return this.write(this.read().update(oHash));
	},
	// Gets a value
	get: function(key){
		return this.read().get(key);
	},
	// Adds/Updates a key/value pair
	set: function(key, value){
		var _hash = this.read(), val = _hash.set(key, value);
		this.write(_hash);
		return val;
	},
	// Removes a key/value pair
	unset: function(key){
		var _hash = this.read(), val = _hash.unset(key);
		this.write(_hash);
		return val;
	},
	// returns a an array of all keys.
	keys: function(){
		return this.read().keys();
	},
	// Checks if a given key exists in the hash.
	include: function(key){
		return this.read().keys().include(key);
	},
	// Replaces all key/value pairs with given object literal/hash.
	replace: function(oHash){
		this.write(oHash);
	},	
	// Clears all values from the hash
	clear: function(){
		this.write({});
	},
	// Returns the raw hash as it's native string
	toString: function(){
		return this.srcObj.hash;
	}
});

// Single instance to be used for the page.
var LocationHash = new ParamsHash(window.location);
