
Warenkorb.API = Class.create();
Object.extend(Warenkorb.API.prototype, { 
	initialize:					function(action, onComplete) {
		this.action = action;
		this.onComplete = onComplete;
		this.debug = false;
	},

	post:						function (paras) {
		this._call("post", paras)
	},

	get:						function (paras) {
		this._call("get", paras)
	},

	_call:						function (method, paras) {
		if (this.requesting) return;

		var url = "/cgi/runtime/engine/index.pl";
		if(paras == null) paras = {};
		paras.action = 'json/warenkorb/' + this.action;
		paras.rnd = Math.random();

		var para_string = null;
		
		if(paras != null) {
			para_string = $H(paras).toQueryString();	
			if(para_string == "") {
				para_string = null
			}
		}
		
		if (this.debug) alert("DEBUG Request URL: " + url + "\nMethod: " + method + "\nParameters: " + para_string);
		
		var me = this
		var ajax = new Ajax.Request(
				url, 
				{
					method:     method, 
					parameters: para_string, 
					onComplete: function (request) { me.handleResponse(request) }
				});
	},

	handleResponse:				function (request) {
		if (this.debug) alert("DEBUG Response-Text: " + request.responseText)

		var text = request.responseText;
		
		var obj;
		try {
			obj  = eval("obj="+text);
		} catch (e) {
			if (this.debug) alert('DEBUG JSON Exception while doing ' + this.action + "\n" + e);
		}
		try {
			if (this.debug) alert("DEBUG " + this.action + '->onComplete(...)');
			this.onComplete(obj, request.status);
		} catch (e) {
			if (this.debug) alert('DEBUG onComplete Exception while doing ' + this.action + "\n" + e);
		}
	}
});

