/////////////////////////////////////////////////////////////////////////////
// 
//                            HEATWAVE  FRAMEWORK
// 
// -------------------------------------------------------------------------
//                                 LICENSE
// -------------------------------------------------------------------------
// 
// This source file is under the License Agreement that is present in the
// file LICENSE.txt.
// 
// The License Agreement is also available at the following URL:
// http://heatwave.heartbeat.ro/license/
// 
// If you did not receive a copy of the license and are unable to obtain it
// through the world-wide-web, please send an e-mail to
// heatwave.license@heartbeat.ro so we can send you a copy immediately.
// 
/////////////////////////////////////////////////////////////////////////////

/**
 * @function send_request
 * 
 * @description
 * 		Sends an asynchronous request to the server.
 * 
 * @parameters
 * 		@param request
 * 			@type
 * 				Object
 * 
 * 			@description
 * 				The request object used to send the request.
 * 
 * 		@param method
 * 			@type
 * 				string
 * 
 * 			@description
 * 				The type of request used. It can only be 'GET' or 'POST'.
 * 
 * 		@param url
 * 			@type
 * 				string
 * 
 * 			@description
 * 				The script URL to send the request to.
 * 
 * 		@param ready_function
 * 			@type
 * 				string
 * 
 * 			@description
 * 				The name of the function to be used on ready state.
 * 
 * @changelog
 *		@version 1.0.0
 *			Creation of the function.
 */
function send_request(request, method, url, ready_function)
{
	// default values
	var allowed_methods = ["GET", "POST"];
	var parameters = null;
	
	// check request object and URL
	if ((request !== null) && (request !== undefined) && (request !== false) && (url !== null) && (url !== undefined) && (ready_function !== null) && (ready_function !== undefined))
	{
		// check method
		if (!allowed_methods.in_array(method.toUpperCase()))
		{
			// set default method
			method = "GET";
		}
		
		// set function to be used on state change
		request.onreadystatechange = function()
		{
			// call custom function
			window[ready_function](request);
		}
		
		// prepare request
		request.open(method, url, true);
		
		// check method type
		if (method == "POST")
		{
			// set POST header
			request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			
			// split url to get parameters
			var pieces = url.split("?");
			
			// check URL in pieces
			if ((pieces[0] !== null) && (pieces[0] !== undefined))
			{
				// set URL
				url = pieces[0];
			}
			
			// check parameters in pieces
			if ((pieces[1] !== null) && (pieces[1] !== undefined))
			{
				// set parameters
				parameters = pieces[1];
			}
		}
		
		// send request to server
		request.send(parameters);
	}
}
