/**
 *
 */
$(function() {
    var $headline = $('#content h6:first');
    $(document).ajaxSend(function() {
        $headline.show();
    });
    $(document).ajaxStop(function() {
        $headline.hide();
    });
});

/**
 * Calls an action with ajax, using the post method. When the server responds it
 * calls the funcCallback with the response from the server.
 * @param {String} action The name of the action
 * @param {String | Hash} params An encoded url string or a hashmap with the params
 * @param {Function} The function that will be executed with the response
 */
function doPost(action, params, funcCallback, failureFunction){
		
	 $.ajax({
	   type: 'GET',
	   dataType: 'json',
	   url: action,
	   data: params,
	   success: funcCallback,
	   error: failureFunction || defaultFailureFunction
	 });
}

/**
 * Calls an action with ajax, using the HEAD method. When the server responds it
 * calls the funcCallback with the response from the server.
 * @param {String} action The name of the action
 * @param {String | Hash} params An encoded url string or a hashmap with the params
 * @param {Function} The function that will be executed with the response
 */
function getHead(action, params, funcCallback, failureFunction) {
	$.ajax({
	   type: 'HEAD',
	   url: action,
	   data: params,
	   success: funcCallback,
	   error: failureFunction || defaultFailureFunction
	 });
}

/**
 * Gets a document only if exists, otherwise it executes a failure function.
 * @param action The name of the action
 * @param failureFunction The function that will be executed in case of the document is not found
 */
function getDocumentIfExists(action, failureFunction) {
	getHead(action, null, function(){ document.location = action; }, failureFunction);
}

/**
 * Fills a <select> element with the response from an action. The response should
 * be a collection.
 * @param {String} action The name of the action
 * @param {String | Hash} params An encoded url string or a hashmap with the params
 * @param {String | Element | JQuery} The id of the <select> element or the element itself 
 */
function fillPullDown(action, params, select){
	select = $(select);
	doPost(action, params, function(arr){
								jQuery.each(arr, function(i, a){
								addItem(select.get(0), a.name, a.id);
							});
	 		});	
}

/**
 * Fills a <select> element with the values from the values array.
 * Each element in the values array must have a name and id attribute.
 */
 function fillSimplePullDown(select, values){
 	jQuery.each(values,function(i, a){
		addItem(select, a.name, a.id);
	});
 }

/**
 * Sends the browser to the error page
 */
function defaultFailureFunction(XMLHttpRequest, textStatus, errorThrown){
	if(XMLHttpRequest.status == 500){
		alert('An error has ocurred, please try again or contact the administrator');
	}else{
		alert('Your session has expired, please login and try again');
	}
}
