/**
 * This file must be included to support JavaScript Object Notation (JSON). When an instance of the JSON class is created, the request function
 * may be used to post a JSON request. A handlers must be passed as argument. See also <a href="http://www.json.org/json2.js">json2.js</a>.
 * 
 * @version 2010-10-15
 * @author <a href="mailto:r.tennapel@griponservice.nl?SUBJECT=json.js">R. ten Napel, ing.</a>
 **/

/**
 * The class that handles JSON requests. Instantiate this class for JSON support / calls.
 * 
 * @param url				The URL to request.
 * @param handler			The JSON callBack handler function.
 **/
JSON = function(url, handler) {
	this.url = url;
	this.handler = handler;
};

/**
 * Static function that creates a JavaScript object from textual data (in JSON format).
 * 
 * @param data				The JSON textual data to convert to a Javascript object.
 * 
 * @return					A JavaScript object.
 **/
JSON.parse = function(data) {
	return new Function("return " + data)();
};

/**
 * Convert a JavaScript element / object to a JSON-formatted text.
 * 
 * @param element			The element to convert.
 * 
 * @return					Tje JSON-text.
 **/
JSON.stringify = function(element) {
	var json = "";
	
	// Build the JSON-string according to the element type:
	if (typeof element == "string") {
		//alert("STRING: " + element);
		json += "\"" + element.replaceAll("\"", "\\\"") + "\"";
	} else if (GlobalKit.isArray(element)) {
		//alert("ARRAY");
		json += "[ ";
		
		for (var i = 0; i < element.length; i++) {
			json += (i > 0) ? ", " : "";
			json += JSON.stringify(element[i]);
		}
		
		json += " ]";
	} else if (typeof element == "object") {
		//alert("OBJECT (" + element.length + ")");
		json += "{ ";
		
		var i = 0;
		for (var child in element) {
			var key = new String(child);
			var value = element[key];
			
			json += (i > 0) ? ", " : "";
			json += "\"" + key + "\": " + JSON.stringify(value);
			
			i++;
		}
		
		json += " }";
	} else {
		//alert("NUMBER");
		json += element;
	}
	
	return json;
};

/**
 * Request JSON data by means of an Ajax call. The retrieved data will be handled by the given callBack function / JSON handler.
 **/
JSON.prototype.request = function() {
	new Ajax(null, this.url, null, null, this.handler).request();
};
