/**
 * Ajax helper library. Contains wrappers for jQuery GET and POST functions
 */

/**
 * Wrapper for jQuery get. Works the same way as normal get except that the given callback function is called with the response object as parameter, rather than the response text.
 * The second difference is that the callback function is called only when the operation was a success. (See handleReturnData() for error handling)
 * 
 * @param uriSegments The URI segements where the call is made, in addition to site_url
 * @param callback The callback function
 */
function get(uriSegments, callback) {
	$.get(site_url + uriSegments, function(data) {
		var responseObject = handleReturnData(data);
		if (responseObject && typeof callback == 'function') {
			callback(responseObject);
		}
	});
}

/**
 * Wrapper for jQuery post. Works the same way as normal post except that the given callback function is called with the response object as parameter, rather than the response text.
 * The second difference is that the callback function is called only when the operation was a success. (See handleReturnData() for error handling).
 * The third diffrence is that all posts are appended with two additional parameters, authentication and current_url.
 * 
 * @param uriSegments The URI segements where the call is made, in addition to site_url
 * @param callback The callback function
 */
function post(uriSegments, params, callback) {
	//Add the authentication data to post
	if (typeof params == 'object') {
		params.authentication = authChecksum
		params.current_url = current_url
	}
	else {
		params = {authentication: authChecksum, current_url: current_url}
	}
	
	$.post(site_url + uriSegments, params, function(data) {
		var responseObject = handleReturnData(data);
		if (responseObject && typeof callback == 'function') {
			callback(responseObject);
		}
	});
}

/**
 * Handles ajax call return data.
 */
function handleReturnData(data) {
	var responseObject = eval("("+data+")");
	if (responseObject.result == 0) {
		//Generic error handling takes place here (showing error messages etc)
		addMessage('error', responseObject.errorMessage, 0, '.column2');
		//TODO it probably should be possible to override this error handling
		//console.log(data.errorMessage);
		return false;
	}
	return responseObject;	 
}

/**
 * Adds a system message on the current page
 */
function addMessage(type, text, delay, where) {
	var temp = new Date;
	var messageId = temp.getMilliseconds();

	var message = '<li id="message'+messageId+'" class="'+type+'" style="display:none;">'+text+'</li>';

	if($(where+' .systemMessages').length>0) {
		$(where+' .systemMessages').append(message);
	}
	else {
		message = '<ul id="systemMessages" class="systemMessages">'+message+'</ul>';
		$(where).append(message);
	}

	var cmd = "$('#message"+messageId+"').fadeIn(1000)";
	window.setTimeout(cmd, delay);
	
	return messageId;
}