
function AjaxController(caller, sendRequestPrefix, sendRequestPostfix) {

	var showLoading = function(on) {
		caller.isLoading = on;
		caller.showLoading && caller.showLoading(on)
	}

	var onLoadError = function(err) {
		if (caller.onLoadError) {
			caller.onLoadError(err)
			return;
		}

		var msg = "Извините, произошла ошибка. Код:"+err.errcode
		//if (err.xhr && err.xhr.statusText) msg = msg+' '+err.xhr.statusText // e.g "OK"
		alert(msg)
	}

    this.sendRequest = function(req, nocache){
		var data = typeof req.data == 'string' ? req.data : $.param(req.data)
		var key = req.url+'/'+data
		var self = this

		/*
		if (!nocache && sendRequestCache[key]) {
			//caller.onLoaded(sendRequestCache[key])
			setTimeout(function() { caller.onLoaded(sendRequestCache[key]) }, 0)
			return;
		}
		*/
		showLoading(true);
		var onSuccess = function(data) {
		//	debugger
			if (typeof(data) == 'string') {
				eval('data=' + data);
			}
			
			if (!data.errcode) {
				sendRequestCache[key] = data;
				caller.onLoaded(data)
				showLoading(false)
			} else {
				showLoading(false)
				onLoadError(data)
			}
		}

		var onError = function(xhr, status, e){
			console.log(e);
			showLoading(false)
			onLoadError({errcode:status, xhr:xhr, event: e})
		}

		var url = (sendRequestPrefix || '')+req.url+(sendRequestPostfix || '')

		$.ajax({
			type: req.type || "GET",
			url: url,
			data: data,
			success: onSuccess,
			//dataType: "json",
			error: onError
		});

	}


}

