Ajax.JSON = Class.create(Ajax.Request, {
    initialize: function($super, url, options) {
        options = options || {};
        options.method = 'post';
        options.contentType = 'application/json; charset=utf-8';
        options.postBody = Object.toJSON(options.object);
        $super(url, options);
    }
});

var Requester = Class.create({
    initialize: function(params) {
        this.objectToSend = params.object
        this.url = this.objectToSend.get('url')
        this.action = this.objectToSend.get('action')
        this.objectFromServer = null
        //metodi esterni!
        this.callBackBefore = params.callBackBefore
        this.callBackAfterRequest = params.callBackAfterRequest
        this.secondCallBackAfterRequest = params.secondCallBackAfterRequest
        this.paramsForCallBackAfterRequest = params.paramsForCallBackAfterRequest
        this.thirdCallBackAfterRequest = params.thirdCallBackAfterRequest
        this.mustBuildRequest = params.mustBuildRequest ? 1 : 0

    },
    sendRequest: function(){
        new Ajax.Request(this.url, {
              method: 'post',
              onCreate: this.callBackBefore ? this.callBackBefore.bindAsEventListener(this) : null,
              parameters: {
                  "action":this.action,
                  "stringa": Base64.encode(Object.toJSON(this.objectToSend))
              },
              onComplete:  this.callBackAfter.bindAsEventListener(this)
        });
    },
    callBackAfter: function(request){
        var  objectReceived = (Base64.decode(request.responseText)).evalJSON(true)
        this.callBackAfterRequest != null
            ?
                this.callBackAfterRequest({
                clientObject: this.paramsForCallBackAfterRequest,
                serverObject: objectReceived})
            :
                null
        this.secondCallBackAfterRequest ? this.secondCallBackAfterRequest(objectReceived) : null
        this.thirdCallBackAfterRequest ? this.thirdCallBackAfterRequest(objectReceived) : null
        if(this.mustBuildRequest){

            if(objectReceived.FBnotification) //merd!
                for(var i = 0; i < objectReceived.FBnotification.size(); i++)
                    if(objectReceived.FBnotification[i].msg)
                        objectReceived.FBnotification[i] = objectReceived.FBnotification[i].msg

            this.builderRequest = new BuilderMsg({
                msgToPrint: {msg: objectReceived},
                containerMsg: $$('.FeedbackFromNotificationRequest')[0] ? $$('.FeedbackFromNotificationRequest')[0] : $$('.FeedbackFromFlash')[0] ,
                containerFeedback: $$('.containerFeedBack')[0] ? $$('.containerFeedBack')[0] : $$('.containerFeedBackFlash')[0] ,
                classBtnClicked: "btnCloseAfterRequest",
                forWhat: "notification",
                left:100,
                top:100
            });
            this.builderRequest.build()
            objectReceived = null
        }

    }

})


