/******************************************************************************\

	Title: jQuery JSON Module
	Author: Chase Mathewson
	Licence: http://creativecommons.org/licenses/by-sa/3.0/
	Requires: "json2.js" http://www.json.org/
	
	Adds a json module to the jQuery library.
	
		$.json( string:String ) :Object
			Pass a valid JSON string, will returns the javascript value.
			
		$.json( object:Object ) :String
			Pass any javascript data but a JSONstring, will return JSON string.
			
		$.json.decode( json:string ) :Object
			Accepts a JSON string, and returns the javascript value.
	
		$.json.encode( object:Object ) :String
			Accepts a javascript value, and returns the JSON string.
			
		$.json.decode( json:string ) :Object
			Accepts a JSON string, and returns the javascript value.
			
		$.json.test( string:String ) :Boolean
			Checks the JSON for bad format or data, and returns true if safe.
	
\******************************************************************************/

(function($, undefined) {
	
	//dependancy check
	if (!JSON) throw new Error('JSON support is required.');

/** Private Functions *********************************************************/

//determines if a string is a valid json string
function testJSONString(string) {
	if (typeof string !== "string") {
		return false;
	}
	else {
		string = string.replace(/\\["\\\/bfnrtu]/g, '@');
		string = string.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
		string = string.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
	}
	return (/^[\],:{}\s]*$/.test(string));
};

/** Create JSON Module ********************************************************/

//convert json if valid, or parse into json.
$.json = function json(Object_obj) {
	return (testJSONString(Object_obj)) ? JSON.parse(Object_obj) : JSON.stringify(Object_obj);
};
	
//convert an object to a json string
$.json.encode = function encodeJSON(Object_obj) {
	return JSON.stringify(Object_obj);
};
	
//convert a json string to a javascript object
$.json.decode = function decodeJSON(String_JSON) {
	return JSON.parse(String_JSON);
};

//tests a json string for a valid format
$.json.test = function testJSON(String_JSON) {
	return testJSONString(String_JSON);
};
	
})(jQuery);
