﻿var ASP = {};
ASP.NET = {};
ASP.NET.ServiceProxy = XHR.extend({
	initialize : function (url, options)
	{
		this.url = url;
		if (options && options.methods)
		{
			for(var m in options.methods)
				this[m] = this.bindMethod(m, options.methods[m]);
			//delete options.methods;
		}
		this.parent(options);
		this.setHeader('Content-type', 'application/json');
	},
	
	bindMethod : function(method, params)
	{
		var bind = this;
		if ($chk(params) && $type(params) != 'array') params = [params];
		return function() {
			var j = $chk(params) ? params.length : 0, k = arguments.length;
			var o = j > 0 ? {} : null
			for (var i = 0; i < j && i < k; i++)
				o[params[i]] = arguments[i];
			bind.call(method, o, k >= j ? arguments[j] : null);
		};
	},
	
	call : function(method, paramobj, callbacks)
	{
		if (this.options.autoCancel) this.cancel();
		else if (this.running) return this;
	
		this.callbacks = callbacks;

		return this.send(this.url + '/' + method, $chk(paramobj) ? Json.toString(paramobj) : null);
	},
	
	onSuccess: function()
	{
		this.parent();
		var obj = Json.evaluate(this.response.text, this.options.secure);
		if (this.callbacks && this.callbacks.onComplete) this.callbacks.onComplete(obj);
		this.fireEvent('onComplete', obj);
	},
	
	onFailure: function()
	{
		if (this.transport && this.transport.status == 500)
		{
			var obj = Json.evaluate(this.transport.responseText, this.options.secure)
			if (this.callbacks && this.callbacks.onServerError) this.callbacks.onServerError(obj);
			this.fireEvent('onServerError', obj);
		}
		if (this.callbacks && this.callbacks.onFailure) this.callbacks.onFailure(obj);
		this.parent();
	}
});