dojo.declare("AjaxRequest", null, {

    constructor: function(url, context, successHandler, handleAs, errorHandler, timeout) {
        this.url = url;
        this.successHandler = successHandler;
        this.errorHandler = errorHandler;
        this.context = context;
        this.handleAs = handleAs;
        this.timeout = timeout;
       
        if (this.handleAs == null)
            this.handleAs = "text";
           
        if (this.timeout == null)
            this.timeout = 5000;
    },

    post: function() {
		var _this = this;

		if (this.url.indexOf("?") == -1) {
			this.url += "?";
		} else {
			this.url += "&";
		}
		
		this.url += "handleAs=" + this.handleAs;

        dojo.xhrGet( {
                url: _this.url,
                handleAs: _this.handleAs,
                timeout: _this.timeout,
                load: function(data) {
                    var checkForError = false;

                    if (data != null && data.length != null && data.length <= constants.TIMEOUT_TOKEN.length) {
                        checkForError = true;
                    }

                    if (_this.handleAs == "json") {
                        checkForError = true;
                    }
               
                    if (checkForError) {
                       
                        var errorFound = false;
                        if (_this.handleAs == "text") {
                           
                            var errorTokenCheck = data.substring(0, constants.TIMEOUT_TOKEN.length);
                            if(errorTokenCheck == constants.TIMEOUT_TOKEN) {
                                errorFound = true;
                            }

                        } else if (_this.handleAs == "json") {
                            if (data.servletException != null)
                                errorFound = true;
                        }
                       
                       
                        if (errorFound) {
                            window.location = constants.URL_LOGOUT;
                            return;
                        }
                    }

                    if (_this.successHandler != null) {
                        _this.successHandler.call(_this.context, data);
                    }

                },
                error: function(response, ioArgs) {
                    if (_this.errorHandler != null) {
                        _this.errorHandler.call(_this.context, response);
                    } else {
                        console.error(response);
                    }
                 }
            });
    }
});
