gCjs.util.ServiceProxy = function(provider) {
    //    EventBroadcaster.initialize(this);

    this._sUrl = GCJS_AJAX_PROVIDER + '/' + provider;

    gCjs.util.ServiceProxy._sUrl[provider] = this._sUrl;
    this._name = name;
    var _self = this;

    this.ajaxOptions = {
        global: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            _self.onSuccess(this.fMethod, response);
            gCjs.util.ServiceProxy._queue.shift();
            if (gCjs.util.ServiceProxy._queue.length > 0) {
                _self._call(gCjs.util.ServiceProxy._queue[0]);
            }
        },
        error: function(response) {
            _self.onError(this.fMethod, response);
            gCjs.util.ServiceProxy._queue.shift();
            if (gCjs.util.ServiceProxy._queue.length > 0) {
                _self._call(gCjs.util.ServiceProxy._queue[0]);
            }
        }
    };

    this.formSubmitOptions = {
        url: this._sUrl,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        clearForm: false,
        success: function(response) {
            var fDelegate = _self.fDelegate;
            _self.onSuccess(fDelegate, response);
        }
    }
}

gCjs.util.ServiceProxy._queue = [];
gCjs.util.ServiceProxy.isUpdating
gCjs.util.ServiceProxy.oProxy = {};
gCjs.util.ServiceProxy._sUrl = {};

gCjs.util.ServiceProxy.getService = function(provider, oCall){
    if (provider == undefined) provider = "default";
    if (gCjs.util.ServiceProxy.oProxy[provider] == undefined ) {
        gCjs.util.ServiceProxy.oProxy[provider] = new gCjs.util.ServiceProxy(provider);
    }
    return gCjs.util.ServiceProxy.oProxy[provider];
}

var a = gCjs.util.ServiceProxy;


a.prototype.onError = function(fMethod, response) {
    var r = eval('(' + response.responseText + ')');
    fMethod.setArguments(r);
    fMethod.executeError();
}

a.prototype.onSuccess = function(fMethod, response) {
    fMethod.setArguments(response);
    fMethod.execute();
}

a.prototype.formSubmit = function(fDelegate, oForm) {
gCjs.log(oForm);
    var options = jQuery.extend(this.formSubmitOptions, { fMethod: fDelegate });
    this.fDelegate = fDelegate;
    oForm.ajaxSubmit(options);
}

a.prototype.call = function(action, fDelegate, oData) {
    var options = {
        url: this._sUrl + '/' + action,
        data: $.toJSON(oData),
        fMethod: fDelegate
    };
    gCjs.util.ServiceProxy._queue.push(options);
    if (gCjs.util.ServiceProxy._queue.length == 1) {
        this._call(options);
    }
}

a.prototype._call = function(options){
    options = jQuery.extend(this.ajaxOptions, options);
    $.ajax(options);
}

gCjs.register("serviceproxy", gCjs.util.ServiceProxy);

delete(a);