/* Erfordert jquery mit JSON-Plugin: 
   http://jquery.com/
   http://blog.nitrogenlabs.com/2009/03/json-plugin-for-jquery.html */

/* Beispiel:
   var api = new SeschatAttributeAPI("key", "/api/api.php");
   api.storeAttribute('name', 'value', function () { callback... }); */

function SeschatAttributeAPI(apiKey, apiURL)
{
	this.loadAttribute = function (name, callback)
	{
		if (!callback) {
			throw new Error('Kein Callback angegeben');
		}
		jQuery.ajax({
			type: 'POST',
			url: this.apiURL,
			data: {
				key: this.apiKey,
				action: 'get',
				name: name
			},
			dataType: 'json',
			cache: false,
			success: function (data, textStatus)
			{
				callback(data);
			},
			error: function (request, textStatus, errorThrown)
			{
				msg = 'AJAX-Fehler: ' + textStatus + '/' + errorThrown;
				throw new Error(msg);
			}
		});
	};
	this.loadMultiAttributes = function (names, callback)
	{
		if (!callback) {
			throw new Error('Kein Callback angegeben');
		}
		if (!(names instanceof Array)) {
			throw new Error('Array mit Attributnamen erwartet');
		}
		jQuery.ajax({
			type: 'POST',
			url: this.apiURL,
			data: {
				key: this.apiKey,
				action: 'get-multi',
				names: jQuery.json.serialize(names)
			},
			dataType: 'json',
			cache: false,
			success: function (data, textStatus)
			{
				callback(data);
			},
			error: function (request, textStatus, errorThrown)
			{
				msg = 'AJAX-Fehler: ' + textStatus + '/' + errorThrown;
				throw new Error(msg);
			}
		});
	};
	this.storeAttribute = function (name, value, callback)
	{
		jQuery.ajax({
			type: 'POST',
			url: this.apiURL,
			data: {
				key: this.apiKey,
				action: 'set',
				name: name,
				value: jQuery.json.serialize(value)
			},
			dataType: 'text',
			cache: false,
			success: function (data, textStatus)
			{
				if (callback) {
					callback();
				}
			},
			error: function (request, textStatus, errorThrown)
			{
				msg = 'AJAX-Fehler: ' + textStatus + '/' + errorThrown;
				throw new Error(msg);
			}
		});
	};
	this.storeMultiAttributes = function (namesAndValues, callback)
	{
		jsonData = jQuery.json.serialize(namesAndValues);
		jQuery.ajax({
			type: 'POST',
			url: this.apiURL,
			data: {
				key: this.apiKey,
				action: 'set-multi', 
				values: jsonData
			},
			dataType: 'text',
			cache: false,
			success: function (data, textStatus)
			{
				if (callback) {
					callback();
				}
			},
			error: function (request, textStatus, errorThrown)
			{
				msg = 'AJAX-Fehler in storeMultiAttributes: ' + textStatus + '/' + errorThrown + ' (JSON: ' + jsonData + ')';
				throw new Error(msg);
			}
		});
	};

	this.apiKey = apiKey;
	this.apiURL = apiURL;
}

