/**
 * Byng JSON handler
 * 
 * Handler for JSON data tags
 *
 * @copyright Byng Systems LLP
 * @see Mootools1.1
 * @author Ollie Maitland
 * 
 * @param String json
 * @param Boolean secure
 */
Byng.register('byng.ajax.json', 
{
	initialize : function (json, secure)
	{
		if (json) this.setJson(json, secure);		
	},
	
	/**
	 * Set the JSON data
	 */
	setJson : function (json, secure)
	{
		// check for string
		if ($type(json) != 'string' || !json.length) return null;
		if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(json.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null;
	
		/**
		 * Holds the data encapsulated in the JSON string
		 * 
		 * @param Object json
		 */
		this.data = eval('(' + json + ')');
	},
	
	encode : function(obj) 
	{
		if (!obj) obj = this.data;

		switch($type(obj)){
			case 'string':
				return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
			case 'array':
				return '[' + obj.map(this.encode.bind(this)).join(',') + ']';
			case 'object':
				var string = [];
				for (var property in obj) string.push(this.encode(property) + ':' + this.encode(obj[property]));
				return '{' + string.join(',') + '}';
			case 'number':
				if (isFinite(obj)) break;
			case false:
				return 'null';
		}
		return String(obj);
	},
	
	/**
	 * Get an element value
	 * 
	 * @param String element
	 * @param 
	 */
	get : function (element) 
	{
		return this.data[element];
	},
	
	/**
	 * Get an element value as a date
	 * 
	 * @param String element
	 */
	getDate : function (element)
	{
		return new Date(this.get(element)*1000);
	},
	
	/**
	 * Set an element value
	 * 
	 * @param String element Element value key name
	 * @param Mixed value
	 */
	set : function (element, value) 
	{
		this.data[element] = value;
	},
	
	/**
	 * Implement the filter() method on the JSON object
	 *
	 * @param fn Function
	 * @param bind Function
	 */
	filter : function (fn,bind)
	{
		return this.data.filter(fn,bind);
	},

	/**
	 * Implement the each() method on the JSON object
	 *
	 * @param fn Function
	 */
	each : function (fn)
	{
		return $each(this.data, fn);
	}
	
});
