﻿var AjaxPro = {
    ID : "AjaxPro",
    token : "",
    version: "7.7.31.1",
    queueRequests : true,
    toJSON : Json.toString,
    processResponse : function(response, onsuccess, context, onfailure) {
        var o = null;
        eval("o = " + response + ";");
        if(o != null) {
            if(typeof o.value != "undefined" && typeof onsuccess == "function") {
                o.context = context;
                onsuccess(o);
                return;
            } else if(typeof o.error != "undefined" && typeof onfailure == "function") {
                onfailure(o.error);
                return;
            }
        }
        if(typeof onfailure == "function") {
            onfailure({"Message":"Request Failed."});
        }
    }
};

AjaxPro.Request = XHR.extend({
    options: {
		onRequest : function(){ if(AjaxPro.onLoading) { AjaxPro.onLoading(true); } },
        onFailure: AjaxPro.onError || Class.empty,
        onTimeout : AjaxPro.onTimeout || Class.empty,
        onStateChange : AjaxPro.onStateChanged || Class.empty,
        timeout : AjaxPro.timeoutPeriod || 10*1000
	},
	initialize: function(url, options){
	    this.options.autoCancel = !AjaxPro.queueRequests;
		this.url = url;
		this.addEvent('onSuccess', this.onComplete);
		this.parent(options);
		this.setHeader('X-Request', 'JSON');
	},
	send: function(obj){
	    if (this.options.timeout) {
            this.timeoutTimer=window.setTimeout(this.callTimeout.bindAsEventListener(this), this.options.timeout);
            this.addEvent('onComplete',this.removeTimer);
        }
        if(AjaxPro.token) {
            this.setHeader("X-AjaxPro-Token", AjaxPro.token);
        }

        if(!this.options.async) {
            return this.syncSend(Json.toString(obj));
        } else {
            return this.parent(this.url, Json.toString(obj));
        }
	},
	syncSend: function(obj) {
	    var req = this.parent(this.url, obj);
        return Json.evaluate(req.transport.responseText, this.options.secure);
	},
	onComplete: function(){
	    if(AjaxPro.onLoading) {
	        AjaxPro.onLoading(false);
	    }
	    var res = Json.evaluate(this.response.text, this.options.secure);
	    if(typeof res.error != "undefined" && typeof AjaxPro.onError == "function"){
	        AjaxPro.onError(res.error);
	    }
		this.fireEvent('onComplete', res);
	},
	callTimeout: function () {
        this.transport.abort();
        this.onFailure();
        if (this.options.onTimeout) {
            this.options.onTimeout();
        }
    },
    removeTimer: function() {
        window.clearTimeout(this.timeoutTimer);
    }
});