/*
 *  Class: api
 *	Handles all communication with middleware. Triggers $popup by itself, if necessary.
 *
 *	Parameters:
 *		options - Object containing default-settings for future calls: resource(string), api_url(string)
 *		
 *	Returns:
 *		API - Object containing call() to make actual calls
 */
function API(options) {
	var self = this;
	
	this.defaults	= {api_url: API_URL};
	this.settings	= $.extend(self.settings, self.defaults, options);
	
	/*
	 *	Function: call
	 *	Makes the actual call to middleware.
	 *	
	 *	Parameters:
	 *		o - Object containing method(string), url_vars(string), data(object), success(function) and/or complete(function)
	 */
	this.call = function(o) {
		if(o.loading) var timeout = setTimeout(function() { $popup.loading(o.loading)}, 100);

		var data						= o.data;//(o.data) ? JSON.stringify(o.data) : "";
		var method		 			= (o.method) ? o.method : 'GET';
		var contentType			= (o.content_type) ? o.content_type : 'application/json';
		var url 						= self.settings.api_url + self.settings.resource;
		if(o.url_vars) 	{ url += '/' + o.url_vars };
		if(o.extension) { url += o.extension };		
		var authentication = false;
		
		var prevent_cache = new Date().getTime();
		url += '-' + prevent_cache;
			
		console.log('api.call() url: '+url+' method: '+method+' data: '+data);
		
		$.ajax({
			type: method,			
			data: data,
			url: url,
			dataType: 'json',
			success: function(data, status) {
				console.log('api.call() - success: '+status+' - '+data);
				console.log(data);

				if(data.error)	{
					$popup.error(data.error);
				} else {
					if($.isFunction(o.success)) o.success(data, status);
					if(o.info) $popup.info(o.info);
				}
			},
			complete: function(req, status) {
				//console.log('api.call() - complete: '+req+' - '+status);
				//console.log(req);
				
				//Hide loading
				if(timeout) { clearTimeout(timeout); $popup.hideLoading(o.loading)	}
				//ERROR
				if(req.status>200) {
					var error = JSON.parse(req.responseText).error;
					console.log('show errror');
					$popup.error(error);
				}
				//Optional complete-callback
				if($.isFunction(o.complete)) o.complete(req, status); 
			}
		});
	};
	
	return this;
};
