1 /**
  2  * Ajax
  3  *
  4  * Module for making ajax requests
  5  */
  6 (function (undefined){
  7 
  8 	"use strict";
  9 
 10 	var ajax = {
 11 		_do: function (url, data, success_callback, error_callback, isPost)
 12 		{
 13 			var type,
 14 				request = new XMLHttpRequest();
 15 
 16 			if (success_callback === undefined)
 17 			{
 18 				/**
 19 				 * @private
 20 				 */
 21 				success_callback = function (){};
 22 			}
 23 
 24 			type = (isPost) ? "POST" : "GET";
 25 
 26 			if (type === "GET")
 27 			{
 28 				url += (url.match(/\?/))
 29 					? this._serialize(data)
 30 					: "?" + this._serialize(data);
 31 			}
 32 
 33 			request.open(type, url);
 34 
 35 			request.onreadystatechange = function ()
 36 			{
 37 				if (request.readyState === 4)
 38 				{
 39 					if (request.status === 200)
 40 					{
 41 						success_callback.call(request.responseText, request.responseText);
 42 					}
 43 					else
 44 					{
 45 						if (error_callback !== undefined)
 46 						{
 47 							error_callback.call(request.status, request.status);
 48 						}
 49 					}
 50 
 51 				}
 52 			};
 53 
 54 			if (type === "POST")
 55 			{
 56 				request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 57 				request.send(this._serialize(data));
 58 			}
 59 			else
 60 			{
 61 				request.send(null);
 62 			}
 63 		},
 64 		_serialize: function (data)
 65 		{
 66 			var name,
 67 				value,
 68 				pairs = [];
 69 
 70 			for (name in data)
 71 			{
 72 				if ( ! data.hasOwnProperty(name) || $_.type(data[name]) === "function")
 73 				{
 74 					continue;
 75 				}
 76 
 77 				value = data[name].toString();
 78 
 79 				name = encodeURIComponent(name);
 80 				value = encodeURIComponent(value);
 81 
 82 				pairs.push(name + "=" + value);
 83 			}
 84 
 85 			return pairs.join("&");
 86 		}
 87 	};
 88 
 89 	/**
 90 	 * Sends a GET type ajax request
 91 	 *
 92 	 * @name get
 93 	 * @function
 94 	 * @memberOf $_
 95 	 * @param string url
 96 	 * @param object data
 97 	 * @param function success_callback
 98 	 * @param function error_callback
 99 	 */
100 	$_.ext('get', function (url, data, success_callback, error_callback){
101 		ajax._do(url, data, success_callback, error_callback, false);
102 	});
103 
104 	/**
105 	 * Sends a POST type ajax request
106 	 *
107 	 * @name post
108 	 * @function
109 	 * @memberOf $_
110 	 * @param string url
111 	 * @param object data
112 	 * @param function success_callback
113 	 * @param function error_callback
114 	 */
115 	$_.ext('post', function (url, data, success_callback, error_callback){
116 		ajax._do(url, data, success_callback, error_callback, true);
117 	});
118 }());
119